Todos os produtos
Search
Central de documentação

Object Storage Service:Pagamento pelo solicitante (C++ SDK)

Última atualização: Jul 03, 2026

Quando o modo de pagamento pelo solicitante está ativado para um bucket no 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. Esse recurso permite compartilhar dados sem que você precise pagar pelas requisições e pelo tráfego gerados pelo acesso ao seu bucket.

Observações

  • Este tópico utiliza o endpoint público da região China (Hangzhou). Para acessar o OSS a partir de outros serviços da Alibaba Cloud na mesma região, use um endpoint interno. Para obter mais informações sobre regiões e endpoints do OSS, consulte Regiões e endpoints.

  • O exemplo a seguir demonstra como criar uma instância OssClient com um endpoint do OSS. Para outras configurações, como uso de domínio personalizado ou autenticação via Security Token Service (STS), consulte Criar uma instância OssClient.

  • Para ativar o pagamento pelo solicitante, você precisa da permissão oss:PutBucketRequestPayment. Para consultar as configurações desse recurso, é necessária a permissão oss:GetBucketRequestPayment. Para obter mais informações, consulte Conceder uma política personalizada.

Definir o modo de pagamento pelo solicitante

O código a seguir exemplifica como ativar o pagamento pelo solicitante em um bucket:

#include <alibabacloud/oss/OssClient.h>
using namespace AlibabaCloud::OSS;

int main(void)
{
    /* Initialize the OSS account information. */
    
    /* Set yourEndpoint to the endpoint of the region where the bucket is located. For example, if the bucket is in the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com. */
    std::string Endpoint = "yourEndpoint";
    
    /* Set yourRegion to the region where the bucket is located. For example, if the bucket is in the China (Hangzhou) region, set the region to cn-hangzhou. */
    std::string Region = "yourRegion";
    
    /* Specify the bucket name. For example, examplebucket. */
    std::string BucketName = "examplebucket";

    /* Initialize network resources. */
    InitializeSdk();

    ClientConfiguration conf;
    conf.signatureVersion = SignatureVersionType::V4;
    /* Obtain access credentials from environment variables. Before you run this sample code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are set. */
    auto credentialsProvider = std::make_shared<EnvironmentVariableCredentialsProvider>();
    OssClient client(Endpoint, credentialsProvider, conf);
    client.SetRegion(Region);

    /* Set the pay-by-requester mode. */
    SetBucketRequestPaymentRequest request(BucketName);
    request.setRequestPayer(RequestPayer::Requester);

    auto outcome = client.SetBucketRequestPayment(request);

    if (!outcome.isSuccess()) {
        /* Handle the exception. */
        std::cout << "SetBucketRequestPayment fail" <<
        ",code:" << outcome.error().Code() <<
        ",message:" << outcome.error().Message() <<
        ",requestId:" << outcome.error().RequestId() << std::endl;
        return -1;
    }

    /* Release network resources. */
    ShutdownSdk();
    return 0;
}

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

O código a seguir mostra como consultar as configurações de pagamento pelo solicitante de um bucket:

#include <alibabacloud/oss/OssClient.h>
using namespace AlibabaCloud::OSS;

const char* ToRequestPayerName(RequestPayer payer)
{
    static const char* PayerName[] = { "NotSet", "BucketOwner", "Requester"};
    return PayerName[static_cast<int>(payer) - static_cast<int>(RequestPayer::NotSet)];
}

int main(void)
{
    /* Initialize the OSS account information. */
    
    /* Set yourEndpoint to the endpoint of the region where the bucket is located. For example, if the bucket is in the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com. */
    std::string Endpoint = "yourEndpoint";
    
    /* Set yourRegion to the region where the bucket is located. For example, if the bucket is in the China (Hangzhou) region, set the region to cn-hangzhou. */
    std::string Region = "yourRegion";
    
    /* Specify the bucket name. For example, examplebucket. */
    std::string BucketName = "examplebucket";

    /* Initialize network resources. */
    InitializeSdk();

    ClientConfiguration conf;
    conf.signatureVersion = SignatureVersionType::V4;
    /* Obtain access credentials from environment variables. Before you run this sample code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are set. */
    auto credentialsProvider = std::make_shared<EnvironmentVariableCredentialsProvider>();
    OssClient client(Endpoint, credentialsProvider, conf);
    client.SetRegion(Region);

    /* Get the pay-by-requester mode configuration. */
    GetBucketRequestPaymentRequest request(BucketName);
    auto outcome = client.GetBucketRequestPayment(request);

    if (outcome.isSuccess())
    {
        std::cout << "GetBucketRequestPayment success Payer:" << ToRequestPayerName(outcome.result().Payer()) << std::endl;
    }
    else {
        /* Handle the exception. */
        std::cout << "GetBucketPayment fail" <<
        ",code:" << outcome.error().Code() <<
        ",message:" << outcome.error().Message() <<
        ",requestId:" << outcome.error().RequestId() << std::endl;
        return -1;
    }

    /* Release network resources. */
    ShutdownSdk();
    return 0;
}

Acesso de terceiros a objetos com pagamento pelo solicitante

Se você configurar o bucket para cobrar terceiros pelo acesso aos objetos, os solicitantes deverão incluir o cabeçalho x-oss-request-payer:requester nas requisições HTTP para executar operações nos seus objetos. A ausência desse cabeçalho resulta em erro.

O código a seguir ilustra como especificar que terceiros pagam pelo acesso aos objetos ao chamar as operações PutObject, GetObject e DeleteObject. Use essa mesma abordagem para definir o pagamento por terceiros em outras operações de leitura e escrita de objetos via API.


#include <alibabacloud/oss/OssClient.h>
#include <fstream>
using namespace AlibabaCloud::OSS;
int main(void)
{
    /* Initialize the OSS account information. */
    
    /* Set yourEndpoint to the endpoint of the region where the bucket is located. For example, if the bucket is in the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com. */
    std::string Endpoint = "yourEndpoint";
    
    /* Set yourRegion to the region where the bucket is located. For example, if the bucket is in the China (Hangzhou) region, set the region to cn-hangzhou. */
    std::string Region = "yourRegion";
    
    /* Specify the name of the bucket that the requester wants to access. For example, examplebucket. */
    std::string BucketName = "examplebucket";    
    /* Specify the full path of the object that the requester wants to access. The full path cannot contain the bucket name. For example, exampledir/exampleobject.txt. */
    std::string ObjectName = "exampleobject.txt";
    /* Initialize network resources. */
    InitializeSdk();

    ClientConfiguration conf;
    conf.signatureVersion = SignatureVersionType::V4;
    /* Obtain access credentials from environment variables. Before you run this sample code, make sure that the requester's OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET are set as environment variables. */
    auto credentialsProvider = std::make_shared<EnvironmentVariableCredentialsProvider>();
    OssClient client(Endpoint, credentialsProvider, conf);
    client.SetRegion(Region);    

    /* Set the pay-by-requester mode when you upload a file. */
    std::shared_ptr<std::iostream> content = std::make_shared<std::stringstream>();
    *content << "test cpp sdk";
    PutObjectRequest putrequest(BucketName, ObjectName, content);
    putrequest.setRequestPayer(RequestPayer::Requester);
    auto putoutcome = client.PutObject(putrequest);

    /* Set the pay-by-requester mode when you download a file to the local memory. */
    GetObjectRequest getrequest(BucketName, ObjectName);
    getrequest.setRequestPayer(RequestPayer::Requester);
    auto getoutcome = client.GetObject(getrequest);

    /* Set the pay-by-requester mode when you delete a file. */
    DeleteObjectRequest delrequest(BucketName, ObjectName);
    delrequest.setRequestPayer(RequestPayer::Requester);
    auto deloutcome = client.DeleteObject(delrequest);

    /* Release network resources. */
    ShutdownSdk();
    return 0;
}

Referências

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

  • Para obter mais informações sobre a operação de API usada para ativar o pagamento pelo solicitante, consulte PutBucketRequestPayment.

  • Para obter mais informações sobre a operação de API usada para consultar as configurações de pagamento pelo solicitante, consulte GetBucketRequestPayment.