# Assign payment role

> For the complete machine-readable documentation index, see [llms.txt](https://apidocs.chargebee.com/llms.txt).


[Idempotency Supported](/docs/api/idempotency)

Assign or unassign the [primary](/docs/api/customers/customer-object#primary_payment_source_id) or [backup](/docs/api/customers/customer-object#backup_payment_source_id) payment role for a payment source.

##### Set role when creating a payment source[](#set-role-when-creating-a-payment-source)

You can also assign a payment source as primary when you create it using APIs such as:

-   [Create a payment source using payment intent](/docs/api/payment_sources/create-using-payment-intent)
-   [Create a payment source using temporary token](/docs/api/payment_sources/create-using-gateway-temporary-token)
-   [Create a payment source using permanent token](/docs/api/payment_sources/create-using-chargebee-token)

##### Payment collection precedence[](#payment-collection-precedence)

Chargebee uses the following precedence to determine which payment source to use when it collects payments for a [subscription](/docs/api/subscriptions/list-subscriptions):

-   The [payment source](/docs/api/subscriptions/subscription-object#payment_source_id) attached to the subscription, if available.
-   The primary payment source of the customer.
-   The backup payment source of the customer, if available.

### Prerequisites & Constraints

-   The payment source must belong to the customer and must not be [`deleted`](/docs/api/payment_sources/payment_source-object#deleted).
-   The payment source must not be the current primary payment source of the customer.
-   This operation doesn't validate the `status` of the payment source. Check the `status` of the payment source before you assign it to the primary or backup role.

### Impacts

**

#### Payment collection[](#payment-collection)

**

The roles that you set using this API apply to all payments collected for the customer, except for subscriptions that have a payment source attached to them. Chargebee continues to collect such payments using the payment source attached to the subscription.

**

#### Customer[](#customer)

**

-   When you assign a payment source as primary, Chargebee unassigns the existing primary payment source and doesn't affect the backup payment source.
-   When you assign a payment source as backup, Chargebee unassigns the existing backup payment source and doesn't affect the primary payment source.
-   You can set the role of a `backup` payment source to `primary` or `none`.
-   You cannot set the role of a `primary` payment source to either `backup` or `none`.

### Implementation Notes

Before you call this API, ensure the following:

-   The [`payment_source.customer_id`](/docs/api/payment_sources/payment_source-object#customer_id) matches the `id` of the customer.
-   The `payment_source_id` isn't the same as the [`customer.primary_payment_source_id`](/docs/api/customers/customer-object#primary_payment_source_id).
-   Since this API doesn't validate the [`status`](/docs/api/payment_sources/payment_source-object#status) of the payment source, check the `payment_source.status` to ensure it isn't `expired`, `invalid`, or `pending_verification`.

## Sample Request

#### cURL

```bash
curl  https://{site}.chargebee.com/api/v2/customers/__test__KyVnHhSBWl4rs2au/assign_payment_role \
     -u {site_api_key}:\
     -d payment_source_id="pm___test__KyVnHhSBWl4te2ax" \
     -d role="PRIMARY"
```

#### .NET

```dotnet
using ChargeBee.Api;
using ChargeBee.Models;
using ChargeBee.Models.Enums;

ApiConfig.Configure("{site}","{site_api_key}");
EntityResult result = Customer.AssignPaymentRole("__test__KyVnHhSBWl4rs2au")
		.PaymentSourceId("pm___test__KyVnHhSBWl4te2ax")
		.Role(RoleEnum.Primary)
		.Request();

Customer customer = result.Customer;
PaymentSource paymentSource = result.PaymentSource;
```

#### Go

```go
package main
import (
    "fmt"
    "github.com/chargebee/chargebee-go/v3"
    customerAction "github.com/chargebee/chargebee-go/v3/actions/customer"
    "github.com/chargebee/chargebee-go/v3/models/customer"
    enum "github.com/chargebee/chargebee-go/v3/enum"
)
func main() {
    chargebee.Configure("{site_api_key}","{site}");
    res,err := customerAction.AssignPaymentRole("__test__KyVnHhSBWl4rs2au", &customer.AssignPaymentRoleRequestParams{
        PaymentSourceId : "pm___test__KyVnHhSBWl4te2ax",
        Role : enum.RolePrimary,
    }).Request()
    if err != nil {
        fmt.Println(err)
    } else {
        Customer := res.Customer
        PaymentSource := res.PaymentSource
    }
}
```

#### Go

```go
package main

import (
  "fmt"
  "github.com/chargebee/chargebee-go/v4"
)

func main() {
  config := &chargebee.ClientConfig{
    SiteName: "{site}",
    ApiKey: "{site_api_key}",
  }    
  client := chargebee.NewClient(config)
  req := &chargebee.CustomerAssignPaymentRoleRequest{
    PaymentSourceId : "pm___test__KyVnHhSBWl4te2ax",
    Role : chargebee.RolePrimary,
}
  res, err := client.Customer.AssignPaymentRole("__test__KyVnHhSBWl4rs2au", req)
      if err != nil {
        fmt.Println(err)
    } else {
        Customer := res.Customer
        PaymentSource := res.PaymentSource
    }
}
```

#### Java

```java
import com.chargebee.*;
import com.chargebee.ListResult;
import com.chargebee.models.*;
import com.chargebee.models.enums.*;
import java.io.IOException;

public class Sample {

    public static void main(String args[]) throws IOException, Exception {
        Environment.configure("{site}", "{site_api_key}");
        Result result = Customer.assignPaymentRole("__test__KyVnHhSBWl4rs2au")
            .paymentSourceId("pm___test__KyVnHhSBWl4te2ax")
            .role(Role.PRIMARY)
            .request();

        Customer customer = result.customer();
        PaymentSource paymentSource = result.paymentSource();
    }
}
```

#### Java

```java
import com.chargebee.v4.client.ChargebeeClient;
import com.chargebee.v4.models.customer.Customer;
import com.chargebee.v4.models.customer.params.CustomerAssignPaymentRoleParams;
import com.chargebee.v4.models.customer.responses.CustomerAssignPaymentRoleResponse;
import com.chargebee.v4.models.paymentSource.PaymentSource;

public class CustomerAssignPaymentRole {

    public static void main(String[] args) {
        ChargebeeClient client = ChargebeeClient.builder()
            .apiKey("{site_api_key}")
            .siteName("{site}")
            .build();

        CustomerAssignPaymentRoleParams params = CustomerAssignPaymentRoleParams.builder()
            .paymentSourceId("pm___test__KyVnHhSBWl4te2ax")
            .role(CustomerAssignPaymentRoleParams.Role.PRIMARY)
            .build();

        CustomerAssignPaymentRoleResponse response = client
            .customers()
            .assignPaymentRole("__test__KyVnHhSBWl4rs2au", params);

        Customer customer = response.getCustomer();
        PaymentSource paymentSource = response.getPaymentSource();
    }
}
```

#### Node.js

```node
import Chargebee from "chargebee";

const chargebee = new Chargebee({
    site: "{site}",
    apiKey: "{site_api_key}",
});

try {
    const result = await chargebee.customer.assignPaymentRole("__test__KyVnHhSBWl4rs2au", {
        payment_source_id: "pm___test__KyVnHhSBWl4te2ax",
        role: "primary"
    });

    console.log(result);
    const customer = result.customer;
    const paymentSource = result.payment_source;
} catch (err) {
    console.log(err);
}
```

#### PHP

```php
<?php

require __DIR__ . '/vendor/autoload.php';

use Chargebee\ChargebeeClient;

$chargebee = new ChargebeeClient(options: [
    "site" => "{site}",
    "apiKey" => "{site_api_key}",
]);
$result = $chargebee->customer()->assignPaymentRole("__test__KyVnHhSBWl4rs2au", [
    "payment_source_id" => "pm___test__KyVnHhSBWl4te2ax",
    "role" => "primary"
]);
$customer = $result->customer;
$paymentSource = $result->payment_source;
```

#### Python

```python
import chargebee
from chargebee import Chargebee

cb_client = Chargebee(api_key="{site_api_key}", site="{site}")
response = cb_client.Customer.assign_payment_role("__test__KyVnHhSBWl4rs2au",
    cb_client.Customer.AssignPaymentRoleParams(
        payment_source_id="pm___test__KyVnHhSBWl4te2ax",
        role=chargebee.Role.PRIMARY
    )
)
customer = response.customer
payment_source = response.payment_source
```

#### Ruby

```ruby
require 'chargebee'

ChargeBee.configure(:site => "{site}",
  :api_key => "{site_api_key}")

result = ChargeBee::Customer.assign_payment_role("__test__KyVnHhSBWl4rs2au",{
  :payment_source_id => "pm___test__KyVnHhSBWl4te2ax",
  :role => "PRIMARY"
})

customer = result.customer
payment_source = result.payment_source
```

## Sample Response

```json
{
  "customer": {
    "allow_direct_debit": false,
    "auto_collection": "on",
    "card_status": "valid",
    "created_at": 1517505720,
    "deleted": false,
    "excess_payments": 0,
    "first_name": "Mark",
    "id": "__test__KyVnHhSBWl4rs2au",
    "last_name": "Henry",
    "net_term_days": 0,
    "object": "customer",
    "payment_method": {
      "gateway": "chargebee",
      "gateway_account_id": "gw___test__KyVnGlSBWl4T71j4",
      "object": "payment_method",
      "reference_id": "tok___test__KyVnHhSBWl4tX2aw",
      "status": "valid",
      "type": "card"
    },
    "pii_cleared": "active",
    "preferred_currency_code": "USD",
    "primary_payment_source_id": "pm___test__KyVnHhSBWl4te2ax",
    "promotional_credits": 0,
    "refundable_credits": 0,
    "resource_version": 1517505720000,
    "taxability": "taxable",
    "unbilled_charges": 0,
    "updated_at": 1517505720
  },
  "payment_source": {
    "card": {
      "brand": "american_express",
      "expiry_month": 12,
      "expiry_year": 2022,
      "funding_type": "not_known",
      "iin": "378282",
      "last4": "0005",
      "masked_number": "***********0005",
      "object": "card"
    },
    "created_at": 1517505720,
    "customer_id": "__test__KyVnHhSBWl4rs2au",
    "deleted": false,
    "gateway": "chargebee",
    "gateway_account_id": "gw___test__KyVnGlSBWl4T71j4",
    "id": "pm___test__KyVnHhSBWl4te2ax",
    "object": "payment_source",
    "reference_id": "tok___test__KyVnHhSBWl4tX2aw",
    "resource_version": 1517505720000,
    "status": "valid",
    "type": "card",
    "updated_at": 1517505720
  }
}
```

## URL Format

**POST** https://[site].chargebee.com/api/v2/customers/{customer-id}/assign_payment_role

## Input Parameters

- `payment_source_id` (required, string, max chars=40)
  Payment source id this role will be assigned to.

- `role` (required, enumerated string)
  Indicates whether the payment source is Primary, Backup, or neither.
  Possible enum values:
    - `primary`
      Primary
    - `backup`
      Backup
    - `none`
      None

## Returns

- `customer` (Customer object)
  Resource object representing customer

- `payment_source` (Payment source object)
  Resource object representing payment\_source
