Todos os produtos
Search
Central de documentação

Object Storage Service:Ativar o pagamento pelo solicitante com o OSS SDK for PHP 2.0

Última atualização: Jul 03, 2026

Quando o pagamento pelo solicitante está ativado para um bucket, quem faz a requisição arca com as taxas de requisição e tráfego, enquanto o proprietário do bucket paga apenas os custos de armazenamento. Esse recurso permite compartilhar dados sem que você precise custear as requisições e o tráfego gerados por acessos externos ao seu bucket.

Observações de uso

  • O código de exemplo deste tópico utiliza o ID da região cn-hangzhou, correspondente à região China (Hangzhou). Por padrão, o acesso aos recursos de um bucket ocorre via endpoint público. Para acessar esses recursos usando outros serviços da Alibaba Cloud na mesma região do bucket, utilize um endpoint interno. Para mais detalhes sobre regiões e endpoints do OSS, consulte Regiões e endpoints.

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

Exemplos

Ativar o pagamento pelo solicitante

O código abaixo demonstra como ativar o pagamento pelo solicitante:

<?php

require_once __DIR__ . '/../vendor/autoload.php'; // Automaticically load objects and dependency libraries.

use AlibabaCloud\Oss\V2 as Oss;

// Specify command line parameters.
$optsdesc = [
    "region" => ['help' => The region in which the bucket is located.', 'required' => True],  // (Required) Specify the region in which the bucket is located. Example: oss-cn-hangzhou. 
    "endpoint" => ['help' => The domain names that other services can use to access OSS.', 'required' => False], // (Optional) Specify the endpoint that can be used by other services to access OSS. 
    "bucket" => ['help' => The name of the bucket, 'required' => True], // (Required) Specify the name of the bucket. 
];
$longopts = \array_map(function ($key) {
    return "$key:"; // Add a colon (:) to the end of each parameter to indicate that a value is required.
}, array_keys($optsdesc));

// Parse command line parameters.
$options = getopt("", $longopts); 

// Check whether the required parameters are configured.
foreach ($optsdesc as $key => $value) {
    if ($value['required'] === True && empty($options[$key])) {
        $help = $value['help'];
        echo "Error: the following arguments are required: --$key, $help"; // Specifies that the required parameters are not configured.
        exit(1); 
    }
}

// Obtain the values of the command line parameters.
$region = $options["region"]; // The region in which the bucket is located. 
$bucket = $options["bucket"]; // The name of the bucket. 

// Use environment variables to load the credential information (AccessKey ID and AccessKey secret).
$credentialsProvider = new Oss\Credentials\EnvironmentVariableCredentialsProvider(); 

// Use the default configurations of the SDK.
$cfg=Oss\Config::loadDefault(); // Load the default configurations of the SDK. 
$cfg->setCredentialsProvider($credentialsProvider); // Specify the credential provider. 
$cfg->setRegion($region); // Specify the region. 
if (isset($options["endpoint"])) {
    $cfg->setEndpoint($options["endpoint"]); // Specify the endpoint if an endpoint is provided. 
}

// Create an OSSClient instance.
$client = new Oss\Client($cfg); 

// Create a request to specify the payer of the request.
$request = new Oss\Models\PutBucketRequestPaymentRequest(
    $bucket,
    new Oss\Models\RequestPaymentConfiguration('Requester') 
);

// Use the putBucketRequestPayment method to specify the payer of the request.
$result = $client->putBucketRequestPayment($request); 

// Display the returned result.
printf(
    'status code:' . $result-> statusCode. PHP_EOL . // The HTTP response status code. 
    'request id:' . $result->requestId // The unique identifier of the request. 
);

Consultar as configurações de pagamento pelo solicitante de um bucket

O código abaixo demonstra como consultar as configurações de pagamento pelo solicitante de um bucket:

<?php

require_once __DIR__ . '/../vendor/autoload.php'; // Automatically load objects and dependency libraries.

use AlibabaCloud\Oss\V2 as Oss;

// Specify command line parameters.
$optsdesc = [
    "region" => ['help' => The region in which the bucket is located.', 'required' => True], // (Required) Specify the region in which the bucket is located. Example: oss-cn-hangzhou. 
    "endpoint" => ['help' => The domain names that other services can use to access OSS.', 'required' => False], // (Optional) Specify the endpoint that can be used by other services to access OSS. 
    "bucket" => ['help' => The name of the bucket, 'required' => True], // (Required) Specify the name of the bucket. 
];
$longopts = \array_map(function ($key) {
    return "$key:"; // Add a colon (:) to the end of each parameter to indicate that a value is required.
}, array_keys($optsdesc));

// Parse command line parameters.
$options = getopt("", $longopts); 

// Check whether the required parameters are configured.
foreach ($optsdesc as $key => $value) {
    if ($value['required'] === True && empty($options[$key])) {
        $help = $value['help'];
        echo "Error: the following arguments are required: --$key, $help"; // Specifies that the required parameters are not configured.
        exit(1); 
    }
}

// Obtain the values of the command line parameters.
$region = $options["region"]; // The region in which the bucket is located. 
$bucket = $options["bucket"]; // The name of the bucket. 

// Use environment variables to load the credential information (AccessKey ID and AccessKey secret).
$credentialsProvider = new Oss\Credentials\EnvironmentVariableCredentialsProvider(); 

// Use the default configurations of the SDK.
$cfg=Oss\Config::loadDefault(); // Load the default configurations of the SDK. 
$cfg->setCredentialsProvider($credentialsProvider); // Specify the credential provider. 
$cfg->setRegion($region); // Specify the region. 
if (isset($options["endpoint"])) {
    $cfg->setEndpoint($options["endpoint"]); // Specify the endpoint if an endpoint is provided. 
}

// Create an OSSClient instance.
$client = new Oss\Client($cfg); 

// Create a request to query the pay-by-requester configurations of the bucket.
$request = new Oss\Models\GetBucketRequestPaymentRequest($bucket); 

// Use the getBucketRequestPayment method to query the pay-by-requester configurations of the bucket.
$result = $client->getBucketRequestPayment($request); 

// Display the returned result.
printf(

    'status code:' . $result-> statusCode. PHP_EOL . // The HTTP response status code. 
    'request id:' . $result-> requestId. PHP_EOL . // The unique identifier of the request. 
    'request payer:' . $result->requestPaymentConfiguration->payer // The payer of requests. Valid values: BucketOwner or Requester. 
);

Referências

  • Para obter o código completo de ativação do pagamento pelo solicitante, acesse o GitHub.

  • Para detalhes sobre a operação de API usada para ativar esse recurso, consulte PutBucketRequestPayment.

  • Para obter o código completo de consulta das configurações de pagamento pelo solicitante, acesse o GitHub.

  • Para mais informações sobre a operação de API usada para consultar essas configurações, consulte GetBucketRequestPayment.