Todos os produtos
Search
Central de documentação

Object Storage Service:Modo de pagamento pelo solicitante (SDK para Node.js)

Última atualização: Jul 03, 2026

Quando o modo de pagamento pelo solicitante está ativado em um bucket do Object Storage Service (OSS), as taxas de requisição e tráfego são cobradas de quem acessa os dados, e não do proprietário do bucket. O proprietário arca apenas com os custos de armazenamento. Ative esse recurso para compartilhar dados sem pagar pelas taxas de requisição e tráfego geradas pelo acesso ao seu bucket.

Defina o modo de pagamento pelo solicitante

O exemplo a seguir mostra como ativar o pagamento pelo solicitante em um bucket:

const OSS = require('ali-oss')

const client = new OSS({
  // Set region to the region where the bucket is located. For example, if the bucket is in the China (Hangzhou) region, set region to oss-cn-hangzhou.
  region: 'yourregion',
  // Obtain access credentials from environment variables. Before running the sample code, make sure the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are set.
  accessKeyId: process.env.OSS_ACCESS_KEY_ID,
  accessKeySecret: process.env.OSS_ACCESS_KEY_SECRET,
  authorizationV4: true,
  // Set bucket to your bucket name.
  bucket: 'yourBucketName',

});

async function setBucketRequestPayment(bucket, Payer) {
  try {
    // Set bucket to the name of the bucket for which you want to set the pay-by-requester mode.
    // The value of Payer can be Requester or BucketOwner.
    // If Payer is set to Requester, the pay-by-requester mode is enabled for the bucket. The requester pays for the traffic and request fees generated when reading data from the bucket.
    // If Payer is set to BucketOwner, the pay-by-requester mode is disabled for the bucket (default). The fees are paid by the data owner (BucketOwner).
    const result = await client.putBucketRequestPayment(bucket, Payer);
    console.log(result);
  } catch (e) {
    console.log(e);
  }
}

setBucketRequestPayment('bucketName', 'Requester')

Consulte a configuração do modo de pagamento pelo solicitante

Use o código abaixo para consultar as configurações de pagamento pelo solicitante de um bucket:

const OSS = require('ali-oss')

const client = new OSS({
   // Set region to the region where the bucket is located. For example, if the bucket is in the China (Hangzhou) region, set region to oss-cn-hangzhou.
  region: 'yourregion',
  // Obtain access credentials from environment variables. Before running the sample code, make sure the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are set.
  accessKeyId: process.env.OSS_ACCESS_KEY_ID,
  accessKeySecret: process.env.OSS_ACCESS_KEY_SECRET,
  authorizationV4: true,
  // Set bucket to your bucket name.
  bucket: 'yourBucketName',
});

async function getBucketRequestPayment(bucket) {
  try {
    // Get the pay-by-requester mode configuration of the bucket.
    const result = await client.getBucketRequestPayment(bucket);
    console.log(result.payer);
  } catch (e) {
    console.log(e);
  }
}

getBucketRequestPayment('bucketName')

Acesso a objetos com pagamento pelo solicitante

Se você definir que terceiros devem pagar pelo acesso aos objetos de um bucket, os solicitantes precisam incluir o cabeçalho x-oss-request-payer:requester nas requisições HTTP para executar operações nesses objetos. A ausência desse cabeçalho resulta em erro.

Os exemplos a seguir demonstram o uso de PutObject, GetObject e DeleteObject para acessar um objeto como solicitante. O mesmo padrão se aplica a outras operações de leitura e escrita de objetos.

Veja como especificar que terceiros arcam com os custos ao acessar objetos:

const OSS = require('ali-oss');
const bucket = 'bucket-name';
const payer = 'Requester';

const client = new OSS({
  // Set region to the region where the bucket is located. For example, if the bucket is in the China (Hangzhou) region, set region to oss-cn-hangzhou.
  region: 'yourregion',
  // Obtain access credentials from environment variables. Before running the sample code, make sure the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are set.
  accessKeyId: process.env.OSS_ACCESS_KEY_ID,
  accessKeySecret: process.env.OSS_ACCESS_KEY_SECRET,
  authorizationV4: true,
  // Set bucket to your bucket name.
  bucket: 'yourBucketName',

});

async function main() {
  await put();
  await get();
  await del();
}

async function put() {
  const result = await client.putBucketRequestPayment(bucket, payer);
  console.log('putBucketRequestPayment:', result);
  // Specify the payer for the PutObject operation.
  const response = await client.put('fileName', path.normalize('D:\\localpath\\examplefile.txt'), {
    headers: {
      'x-oss-request-payer': 'requester'
    }
  });
  console.log('put:', response);
}

async function get() {
  const result = await client.putBucketRequestPayment(bucket, payer);
  console.log('putBucketRequestPayment:', result);
  // Specify the payer for the GetObject operation.
  const response = await client.get('fileName', {
    headers: {
      'x-oss-request-payer': 'requester'
    }
  });
  console.log('get:', response);
}

async function del() {
  const result = await client.putBucketRequestPayment(bucket, payer);
  console.log('putBucketRequestPayment:', result);
  // Specify the payer for the DeleteObject operation.
  const response = await client.delete('fileName', {
    headers: {
      'x-oss-request-payer': 'requester'
    }
  });
  console.log('delete:', response);
}

main();

Referências

  • Para obter o código de exemplo completo sobre o modo de pagamento pelo solicitante, consulte Exemplos no GitHub.

  • Para mais detalhes sobre a operação de API usada para definir o modo de pagamento pelo solicitante, consulte PutBucketRequestPayment.

  • Para obter mais informações sobre a operação de API que recupera a configuração do modo de pagamento pelo solicitante, consulte GetBucketRequestPayment.