All Products
Search
Document Center

Object Storage Service:Enable pay-by-requester to let requesters pay for traffic, requests, and data processing

Last Updated:Apr 19, 2025

In most cases, you must pay the fees generated by your buckets. However, you can enable pay-by-requester for your buckets to let authenticated requesters pay for the requests, data processing, and traffic generated when they access the data in the bucket. You only pay for other fees such as the storage fee. You can enable pay-by-requester to share your data in a bucket without paying fees generated by other requesters' access to the data.

Scenarios

  • Share large datasets. For example, a research institute wants all customers to access shared datasets that contain postal code directories, reference data, geospatial information, or web crawling data. The institute also wants the requesters to pay for the traffic and request fees generated when they download the data.

    To meet this business requirement, the research institute can configure the following settings in OSS:

    1. Set the access control list (ACL) of the bucket in which the public dataset is stored to public-read. For more information, see Set the ACL for a bucket.

    2. Enable pay-by-requester for the bucket.

  • Deliver production data to your customers or partners. For example, you want to make your production data in OSS accessible to your partners and let your partners pay the request and traffic fees when they download the production data.

    In this case, you can perform the following steps to configure pay-by-requester:

    1. Set the ACL of the bucket in which the production data is stored to private. For more information, see Set the ACL for a bucket.

    2. Enable pay-by-requester for the bucket.

    3. Use bucket policies to grant your partners permissions to access the production data in the bucket. For more information, see Use bucket policies to authorize other users to access OSS resources.

    Important

    Make sure that you grant permissions to the RAM users of your partners to access the production data in the bucket. For the purposes of pay-by-requester, do not share the AccessKey pairs of RAM users within your Alibaba Cloud account with your partners. Otherwise, you are charged the request and traffic fees because the requesters use the RAM users within your Alibaba Cloud account to access the production data.

Request method

  • Requests from anonymous users are not allowed

    If you enable pay-by-requester for a bucket, anonymous users cannot access the bucket. Requesters must provide authentication information so that OSS can identify requesters based on the given information. This way, the requesters are charged request and traffic fees.

    If a requester assumes a RAM role of an Alibaba Cloud account to request data, OSS charges the Alibaba Cloud account for the requests that are sent by the requester and the generated traffic.

  • The x-oss-request-payer header must be included in requests

    If you enable pay-by-requester for a bucket, the x-oss-request-payer header must be included in requests, and the value of the header must be set to requester to indicate that the requester understands that they are charged for the requests and downloads. Otherwise, the requests cannot be authenticated.

    When bucket owners access their buckets, they do not need to include the x-oss-request-payer header in requests. Bucket owners are charged for their own requests and generated traffic.

Pricing

Before pay-by-requester is enabled for a bucket, the owner of the bucket pays all fees associated with the bucket. After pay-by-requester is enabled for the bucket, billable items that apply to the bucket owner are different from those before pay-by-requester is enabled. The following table lists billable items on bucket owners and requesters after pay-by-requester is enabled.

Fee

Billable item

Payer

Storage fees

Storage usage of Standard LRS objects

Bucket owner

Storage usage of Standard ZRS objects

Bucket owner

Storage usage of IA LRS objects

Bucket owner

Storage usage of IA ZRS objects

Bucket owner

Storage usage of Archive LRS objects

Bucket owner

Storage usage of Archive ZRS objects

Bucket owner

Storage usage of Cold Archive LRS objects

Bucket owner

Storage usage of Deep Cold Archive LRS objects

Bucket owner

Storage usage of IA LRS objects that are stored for less than the minimum storage duration

Bucket owner

Storage usage of Archive LRS objects that are stored for less than the minimum storage duration

Bucket owner

Storage usage of Archive ZRS objects that are stored for less than the minimum storage duration

Bucket owner

Storage usage of Cold Archive objects that are stored for less than the minimum storage duration

Bucket owner

Storage usage of Deep Cold Archive objects that are stored for less than the minimum storage duration

Bucket owner

Traffic fees

outbound traffic over the Internet

Requester

inbound traffic over the Internet

Free

outbound traffic over the internal network

Free

inbound traffic over the internal network

Free

origin traffic

Requester

cross-region replication traffic

Bucket owner

Request fees

Number of PUT requests

Requester

Number of GET requests

Requester

Data retrieval requests

Bucket owner

Scanned data capacity for SelectObject

Bucket owner

Retrieval of IA objects

Requester

Retrieval of Archive objects

Requester

Retrieval of Archived objects for which real-time access is enabled

Bucket owner

Retrieval of Cold Archive objects

Bucket owner

Retrieval of Deep Cold Archive objects

Bucket owner

Object tagging fees

object tagging

Bucket owner

Transfer acceleration fees

Acceleration AccM2MIn

Bucket owner

Acceleration AccM2MOut

Bucket owner

Acceleration AccM2OIn

Bucket owner

Acceleration AccM2OOut

Bucket owner

Acceleration AccO2MIn

Bucket owner

Acceleration AccO2MOut

Bucket owner

Acceleration AccO2OIn

Bucket owner

Acceleration AccO2OOut

Bucket owner

Temporary storage fees

Temporary replica (LRS) capacity

Bucket owner

Anti-DDoS fees

Reserved OSS DDoS protection instances

Bucket owner

Remaining duration of OSS DDoS protection instances released within the minimum usage duration

Bucket owner

Traffic protected by OSS DDoS protection instances

Bucket owner

API requests protected by OSS DDoS protection instances

Bucket owner

Data indexing fees

Metadata management fees

In public preview and free of charge

Bucket query fees

In public preview and free of charge

Note

If the requester does not include the x-oss-request-payer header in a GET, HEAD, or POST request, the bucket owner is charged for the PUT and GET requests.

Operations

Use the OSS console

  1. Log on to the OSS console.

  2. In the left-side navigation pane, click Buckets. On the Buckets page, find and click the desired bucket.

  3. In the left navigation bar, select Bucket Settings > Pay-by-requester.

  4. On the Pay-by-requester page, turn on Pay-by-requester.

  5. In the dialog box that appears, click OK.

    Note

    If you want to disable pay-by-requester, you can turn off Pay-by-requester and then click OK.

Use Alibaba Cloud SDKs

The following code provides examples on how to configure pay-by-requester for a bucket by using OSS SDKs for common programming languages. For more information about how to configure pay-by-requester by using other SDKs, see SDK overview.

import com.aliyun.oss.OSS;
import com.aliyun.oss.common.auth.*;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.OSSException;
import com.aliyun.oss.model.*;

public class Demo {
    public static void main(String[] args) throws Exception{
        // In this example, the endpoint of the China (Hangzhou) region is used. Specify your actual endpoint. 
        String endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
        // Obtain access credentials from environment variables. Before you run the sample code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are configured. 
        EnvironmentVariableCredentialsProvider credentialsProvider = CredentialsProviderFactory.newEnvironmentVariableCredentialsProvider();
        // Specify the name of the bucket. Example: examplebucket. 
        String bucketName = "examplebucket";
        // Specify the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the region to cn-hangzhou.
        String region = "cn-hangzhou";
        
        // Create an OSSClient instance. 
        ClientBuilderConfiguration clientBuilderConfiguration = new ClientBuilderConfiguration();
        clientBuilderConfiguration.setSignatureVersion(SignVersion.V4);        
        OSS ossClient = OSSClientBuilder.create()
        .endpoint(endpoint)
        .credentialsProvider(credentialsProvider)
        .clientConfiguration(clientBuilderConfiguration)
        .region(region)               
        .build();
        try {
            // Enable pay-by-requester for the bucket. 
            Payer payer = Payer.Requester;
            ossClient.setBucketRequestPayment(bucketName, payer);
        } catch (OSSException oe) {
            System.out.println("Caught an OSSException, which means your request made it to OSS, "
                    + "but was rejected with an error response for some reason.");
            System.out.println("Error Message:" + oe.getErrorMessage());
            System.out.println("Error Code:" + oe.getErrorCode());
            System.out.println("Request ID:" + oe.getRequestId());
            System.out.println("Host ID:" + oe.getHostId());
        } catch (Throwable ce) {
            System.out.println("Caught an ClientException, which means the client encountered "
                    + "a serious internal problem while trying to communicate with OSS, "
                    + "such as not being able to access the network.");
            System.out.println("Error Message:" + ce.getMessage());
        } finally {
            // Shut down the OSSClient instance. 
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }
    }
}
const OSS = require('ali-oss')

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

});

async function setBucketRequestPayment(bucket, Payer) {
  try {
    // Specify the name of the bucket for which you want to enable pay-by-requester. 
    // Set Payer to Requester or BucketOwner. 
    // If Payer is set to Requester, pay-by-requester is enabled for the bucket. The requester is charged the traffic and request fees that are generated when the requester reads data in the bucket. 
    // If Payer is set to BucketOwner, pay-by-requester is disabled for the bucket. This is the default configuration for the bucket. In this case, the bucket owner is charged the generated request fees. 
    const result = await client.putBucketRequestPayment(bucket, Payer);
    console.log(result);
  } catch (e) {
    console.log(e);
  }
}

setBucketRequestPayment('bucketName', 'Requester')
using Aliyun.OSS;
using Aliyun.OSS.Common;

// Specify the endpoint of the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com. 
var endpoint = "yourEndpoint";
// Obtain access credentials from environment variables. Before you run the sample code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are configured. 
var accessKeyId = Environment.GetEnvironmentVariable("OSS_ACCESS_KEY_ID");
var accessKeySecret = Environment.GetEnvironmentVariable("OSS_ACCESS_KEY_SECRET");
// Specify the name of the bucket. 
var bucketName = "examplebucket";
// Specify the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the region to cn-hangzhou.
const string region = "cn-hangzhou";
            
// Create a ClientConfiguration instance and modify parameters as required.
var conf = new ClientConfiguration();
            
// Use the signature algorithm V4.
 conf.SignatureVersion = SignatureVersion.V4;
            
// Create an OSSClient instance.
var client = new OssClient(endpoint, accessKeyId, accessKeySecret, conf);
c.SetRegion(region);
try
{
    // Enable pay-by-requester for the bucket. 
    var request = new SetBucketRequestPaymentRequest(bucketName, RequestPayer.Requester);
    client.SetBucketRequestPayment(request);
    Console.WriteLine("Set bucket:{0} RequestPayment succeeded ", bucketName);
}
catch (OssException ex)
{
    Console.WriteLine("Failed with error code: {0}; Error info: {1}. \nRequestID:{2}\tHostID:{3}",
        ex.ErrorCode, ex.Message, ex.RequestId, ex.HostId);
}
catch (Exception ex)
{
    Console.WriteLine("Failed with error info: {0}", ex.Message);
}
#include <alibabacloud/oss/OssClient.h>
using namespace AlibabaCloud::OSS;

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

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

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

    /* Enable pay-by-requester for the bucket. */
    SetBucketRequestPaymentRequest request(BucketName);
    request.setRequestPayer(RequestPayer::Requester);

    auto outcome = client.SetBucketRequestPayment(request);

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

    /* Release resources such as network resources. */
    ShutdownSdk();
    return 0;
}
package main

import (
	"context"
	"flag"
	"log"

	"github.com/aliyun/alibabacloud-oss-go-sdk-v2/oss"
	"github.com/aliyun/alibabacloud-oss-go-sdk-v2/oss/credentials"
)

// Specify the global variables.
var (
	region     string // The region in which the bucket is located.
	bucketName string // The name of the bucket.
)

// Specify the init function used to initialize command line parameters.
func init() {
	flag.StringVar(&region, "region", "", "The region in which the bucket is located.")
	flag.StringVar(&bucketName, "bucket", "", "The name of the bucket.")
}

func main() {
	// Parse command line parameters.
	flag.Parse()

	// Check whether the bucket name is empty.
	if len(bucketName) == 0 {
		flag.PrintDefaults()
		log.Fatalf("invalid parameters, bucket name required")
	}

	// Check whether the region is empty.
	if len(region) == 0 {
		flag.PrintDefaults()
		log.Fatalf("invalid parameters, region required")
	}

	// Load the default configurations and specify the credential provider and region.
	cfg := oss.LoadDefaultConfig().
		WithCredentialsProvider(credentials.NewEnvironmentVariableCredentialsProvider()).
		WithRegion(region)

	// Create an OSS client.
	client := oss.NewClient(cfg)

	// Create a request to specify the payer of the request.
	putRequest := &oss.PutBucketRequestPaymentRequest{
		Bucket: oss.Ptr(bucketName), // The name of the bucket.
		PaymentConfiguration: &oss.RequestPaymentConfiguration{
			Payer: oss.Requester, // Set the payer of the request to the requester.
		},
	}

	// Send the request to specify the payer of the request.
	putResult, err := client.PutBucketRequestPayment(context.TODO(), putRequest)
	if err != nil {
		log.Fatalf("failed to put bucket request payment %v", err)
	}

	// Display the result of the request.
	log.Printf("put bucket request payment result:%#v\n", putResult)
}
import argparse
import alibabacloud_oss_v2 as oss

# Create a command line argument parser and describe the purpose of the script: Configure the request payment configuration for a bucket
parser = argparse.ArgumentParser(description="put bucket request payment sample")

# Define command line parameters, including the required region, bucket name, optional endpoint, and payer
parser.add_argument('--region', help='The region in which the bucket is located.', required=True)
parser.add_argument('--bucket', help='The name of the bucket.', required=True)
parser.add_argument('--endpoint', help='The domain names that other services can use to access OSS')
parser.add_argument('--payer', help='Indicates who pays the download and request fees. Possible values: "Requester" or "BucketOwner"', required=True)

def main():
    # Parse the command line parameters to obtain the values specified by the user
    args = parser.parse_args()

    # Obtain access credentials from environment variables for authentication
    credentials_provider = oss.credentials.EnvironmentVariableCredentialsProvider()

    # Use the default configurations of the SDK to create a configuration object and specify the credential provider
    cfg = oss.config.load_default()
    cfg.credentials_provider = credentials_provider

    # Specify the region attribute of the configuration object based on the command line parameters provided by the user
    cfg.region = args.region

    # If a custom endpoint is provided, update the endpoint attribute in the configuration object
    if args.endpoint is not None:
        cfg.endpoint = args.endpoint

    # Use the preceding configuration to initialize the OSSClient instance
    client = oss.Client(cfg)

    # Send a request to configure the request payment configuration for the specified bucket
    result = client.put_bucket_request_payment(oss.PutBucketRequestPaymentRequest(
            bucket=args.bucket,  # The bucket name.
            request_payment_configuration=oss.RequestPaymentConfiguration(
                payer=args.payer,  # The payer, which can be "Requester" or "BucketOwner".
            ),
    ))

    # Display the HTTP status code of the operation result and request ID to check the request status
    print(f'status code: {result.status_code},'
          f' request id: {result.request_id},'
          )

# Call the main function to start the processing logic when the script is directly run
if __name__ == "__main__":
    main()  # The entry point of the script, from which the program flow starts
<?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. 
);

Use the ossutil command-line tool

You can use the ossutil command-line tool to configure pay-by-requester. For more information about how to install ossutil, see Install ossutil.

The following example shows how to enable pay-by-requester for a bucket named examplebucket.

ossutil api put-bucket-request-payment --bucket examplebucket --request-payment-configuration "{\"Payer\":\"Requester\"}"

For more information about this command, see put-bucket-request-payment.

Related API operations

If your business requires a high level of customization, you can directly call RESTful APIs. To directly call an API, you must include the signature calculation in your code. For more information, see PutBucketRequestPayment.