# Update payment method for a customer

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


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

[Payment Sources](/docs/api/payment_sources) comes with additional options and improvements to the [Card APIs](/docs/api/cards) . For this operation, use the [Create using temporary token](/docs/api/payment_sources/create-using-gateway-temporary-token) API or [Create using permanent token](/docs/api/payment_sources/create-using-permanent-token) API under Payment Sources to update payment method for the customer.

Updates payment method details for a customer.

**Note:** If you wish to pass the card number, CVV, or the single-use card tokens provided by gateways like Stripe, then use the [Update card for a customer](/docs/api/cards/update-card-for-a-customer) API under Cards resource. This API is not supported for Chargebee Test Gateway, it is provided to help you understand the billing workflow in Chargebee.

**PayPal Express Checkout**  
You can use this API if you are directly integrating PayPal Express Checkout in your website instead of using Chargebee's hosted pages. When your customer updates his payment method using PayPal Express Checkout, you will be provided with the _Billing Agreement ID_ by PayPal. You can update the payment method for that customer in Chargebee by passing `type` as `paypal_express_checkout` and `reference_id` with the _Billing Agreement ID_.

**Login and Pay with Amazon**  
You can use this API if you are directly integrating _Login and Pay with Amazon_ in your website instead of using Chargebee's hosted pages. When your customer updates Amazon as a payment method, you will be provided with the _Billing Agreement ID_ by Amazon. You can update the payment method for that customer in Chargebee by passing `type` as `amazon_payments` and `reference_id` with the _Billing Agreement ID_.

**Card Payments**  
When the card details of your customer are stored in the vault of gateways such as Stripe or Braintree, you can use this API to update the _reference id_ provided by them in Chargebee. To use this API, pass

-   `type` as `card`.
-   `gateway` with the gateway associated with the card. If the gateway is not specified, the default gateway will be used.
-   `reference_id` with the identifier provided by the gateway/Spreedly to reference that specific card.

**Reference id format for Card Payments**  
The format of reference\_id will differ based on where the card is stored.

**Stripe:** In case of Stripe, the reference\_id consists of combination of Stripe Customer ID and Stripe Card ID separated by forward slash (e.g. _cus\_63MnDn0t6kfDW7/card\_6WjCF20vT9WN1G_). If you are passing Stripe Customer ID alone, then Chargebee will store the card marked as active for that customer in Stripe.

**Braintree:** In case of Braintree, the reference\_id consists of combination of Braintree Customer ID and Braintree Payment Method Token separated by forward slash  
(e.g. _cus\_63MnDn0t6kfDW7/card\_6WjCF20vT9WN1G_ ). If you are passing Braintree Customer ID alone, then Chargebee will store the card marked as default for that customer in Braintree.

**Spreedly Card vault:** If the card details are stored in Spreedly vault, then you need to provide the Spreedly token as `reference_id`.

**Direct Debit Payments**  
When the bank account details of your customer are stored in the gateway vault, you can use this API to update the reference id provided by them in Chargebee. To use this API, pass

-   `type` as `direct_debit`.
-   `gateway` with the gateway where the bank account details are stored (e.g. _authorize\_net_). If the gateway is not specified, the gateway supporting the direct debit will be used.
-   `reference_id` with the identifier provided by the gateway to reference the customer's bank account details.
-   `tmp_token` with the single use token provided by the gateway ( Should be passed only if reference\_id is not passed ).

**Reference id format for Direct Debit Payments**  
The format of reference\_id will differ based on where the bank account is stored.

**Stripe:** In case of Stripe, the reference\_id consists of combination of Stripe Customer ID and Stripe Bank Account ID separated by forward slash  
(e.g. _cus\_8suoHaLQH4G5AW/ba\_18b8z2KmcbENlhgU03RznRYW_). If you are passing Stripe Customer ID alone, then Chargebee will store the first bank account details present in payment profile list of that customer in Stripe.

**Authorize.Net:** The reference\_id consists of combination of Authorize.Net's Customer Profile ID and Payment Profile ID separated by forward slash (e.g. _2384383/34834382_). If you are passing Authorize.Net's Customer Profile ID alone, then Chargebee will store the first bank account details present in payment profile list of that customer in Authorize.Net.

**GoCardless:** The reference\_id is the GoCardless Customer Mandate ID (e.g. _MD0077Z99TTQXK_).

**Note:** While using this API to update payment method details, [Card Verification](https://www.chargebee.com/docs/cards.html#card-verification) will not happen even if it is enabled for that particular gateway.

## Sample Request

#### cURL

```bash
curl  https://{site}.chargebee.com/api/v2/customers/__test__KyVnHhSBWlHEO2eE/update_payment_method \
     -u {site_api_key}:\
     -d "payment_method[type]"="CARD" \
     -d "payment_method[gateway_account_id]"="gw___test__KyVnGlSBWl8M41ju" \
     -d "payment_method[reference_id]"="cus_I58QViSiwuelqF"
```

#### .NET

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

ApiConfig.Configure("{site}","{site_api_key}");
EntityResult result = Customer.UpdatePaymentMethod("__test__KyVnHhSBWlHEO2eE")
		.PaymentMethodType(TypeEnum.Card)
		.PaymentMethodGatewayAccountId("gw___test__KyVnGlSBWl8M41ju")
		.PaymentMethodReferenceId("cus_I58QViSiwuelqF")
		.Request();

Customer customer = result.Customer;
Card card = result.Card;
```

#### 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.UpdatePaymentMethod("__test__KyVnHhSBWlHEO2eE", &customer.UpdatePaymentMethodRequestParams{
        PaymentMethod : &customer.UpdatePaymentMethodPaymentMethodParams{
            Type : enum.TypeCard,
            GatewayAccountId : "gw___test__KyVnGlSBWl8M41ju",
            ReferenceId : "cus_I58QViSiwuelqF",
        },
    }).Request()
    if err != nil {
        fmt.Println(err)
    } else {
        Customer := res.Customer
        Card := res.Card
    }
}
```

#### 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.CustomerUpdatePaymentMethodRequest{
    PaymentMethod : &chargebee.CustomerUpdatePaymentMethodPaymentMethod{
        Type : chargebee.TypeCard,
        GatewayAccountId : "gw___test__KyVnGlSBWl8M41ju",
        ReferenceId : "cus_I58QViSiwuelqF",
    },
}
  res, err := client.Customer.UpdatePaymentMethod("__test__KyVnHhSBWlHEO2eE", req)
      if err != nil {
        fmt.Println(err)
    } else {
        Customer := res.Customer
        Card := res.Card
    }
}
```

#### 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.updatePaymentMethod("__test__KyVnHhSBWlHEO2eE")
            .paymentMethodType(Type.CARD)
            .paymentMethodGatewayAccountId("gw___test__KyVnGlSBWl8M41ju")
            .paymentMethodReferenceId("cus_I58QViSiwuelqF")
            .request();

        Customer customer = result.customer();
        Card card = result.card();
    }
}
```

#### Java

```java
import com.chargebee.v4.client.ChargebeeClient;
import com.chargebee.v4.models.card.Card;
import com.chargebee.v4.models.customer.Customer;
import com.chargebee.v4.models.customer.params.CustomerUpdatePaymentMethodParams;
import com.chargebee.v4.models.customer.responses.CustomerUpdatePaymentMethodResponse;

public class CustomerUpdatePaymentMethod {

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

        CustomerUpdatePaymentMethodParams.PaymentMethodParams paymentMethodParams =
            CustomerUpdatePaymentMethodParams.PaymentMethodParams.builder()
                .type(CustomerUpdatePaymentMethodParams.PaymentMethodParams.Type.CARD)
                .gatewayAccountId("gw___test__KyVnGlSBWl8M41ju")
                .referenceId("cus_I58QViSiwuelqF")
                .build();

        CustomerUpdatePaymentMethodParams params = CustomerUpdatePaymentMethodParams.builder()
            .paymentMethod(paymentMethodParams)
            .build();

        CustomerUpdatePaymentMethodResponse response = client
            .customers()
            .updatePaymentMethod("__test__KyVnHhSBWlHEO2eE", params);

        Customer customer = response.getCustomer();
        Card card = response.getCard();
    }
}
```

#### Node.js

```node
import Chargebee from "chargebee";

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

try {
    const result = await chargebee.customer.updatePaymentMethod("__test__KyVnHhSBWlHEO2eE", {
        payment_method: {
            type: "card",
            gateway_account_id: "gw___test__KyVnGlSBWl8M41ju",
            reference_id: "cus_I58QViSiwuelqF"
        }
    });

    console.log(result);
    const customer = result.customer;
    const card = result.card;
} 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()->updatePaymentMethod("__test__KyVnHhSBWlHEO2eE", [
    "payment_method" => [
        "type" => "card",
        "gateway_account_id" => "gw___test__KyVnGlSBWl8M41ju",
        "reference_id" => "cus_I58QViSiwuelqF"
    ]
]);
$customer = $result->customer;
$card = $result->card;
```

#### Python

```python
import chargebee
from chargebee import Chargebee

cb_client = Chargebee(api_key="{site_api_key}", site="{site}")
response = cb_client.Customer.update_payment_method("__test__KyVnHhSBWlHEO2eE",
    cb_client.Customer.UpdatePaymentMethodParams(
        payment_method=cb_client.Customer.UpdatePaymentMethodPaymentMethodParams(
            type=chargebee.Type.CARD,
            gateway_account_id="gw___test__KyVnGlSBWl8M41ju",
            reference_id="cus_I58QViSiwuelqF"
        )
    )
)
customer = response.customer
card = response.card
```

#### Ruby

```ruby
require 'chargebee'

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

result = ChargeBee::Customer.update_payment_method("__test__KyVnHhSBWlHEO2eE",{
  :payment_method => {
    :type => "CARD",
    :gateway_account_id => "gw___test__KyVnGlSBWl8M41ju",
    :reference_id => "cus_I58QViSiwuelqF"
  }
})

customer = result.customer
card = result.card
```

## Sample Response

```json
{
  "card": {
    "card_type": "visa",
    "created_at": 1517505769,
    "customer_id": "__test__KyVnHhSBWlHEO2eE",
    "expiry_month": 12,
    "expiry_year": 2022,
    "funding_type": "credit",
    "gateway": "stripe",
    "gateway_account_id": "gw___test__KyVnGlSBWl8M41ju",
    "iin": "******",
    "issuing_country": "US",
    "last4": "1111",
    "masked_number": "************1111",
    "object": "card",
    "payment_source_id": "pm___test__KyVnHhSBWlHbr2eJ",
    "powered_by": "not_applicable",
    "resource_version": 1517505769000,
    "status": "valid",
    "updated_at": 1517505769
  },
  "customer": {
    "allow_direct_debit": false,
    "auto_collection": "on",
    "card_status": "valid",
    "created_at": 1517505767,
    "deleted": false,
    "excess_payments": 0,
    "first_name": "David",
    "id": "__test__KyVnHhSBWlHEO2eE",
    "last_name": "Young",
    "net_term_days": 0,
    "object": "customer",
    "payment_method": {
      "gateway": "stripe",
      "gateway_account_id": "gw___test__KyVnGlSBWl8M41ju",
      "object": "payment_method",
      "reference_id": "cus_I58QViSiwuelqF/card_1HUy9cJv9j0DyntJNR5sLhy1",
      "status": "valid",
      "type": "card"
    },
    "pii_cleared": "active",
    "preferred_currency_code": "USD",
    "primary_payment_source_id": "pm___test__KyVnHhSBWlHbr2eJ",
    "promotional_credits": 0,
    "refundable_credits": 0,
    "resource_version": 1517505769000,
    "taxability": "taxable",
    "unbilled_charges": 0,
    "updated_at": 1517505769
  }
}
```

## URL Format

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

## Input Parameters

- `payment_method` (optional, enumerated string)
  Parameters for payment\_method
  - `type` (required, enumerated string)
    The type of payment method. For more details refer [Update payment method for a customer](/docs/api/customers/update-payment-method-for-a-customer) API under Customer resource.
    Possible enum values:
      - `card`
        Card based payment including credit cards and debit cards. Details about the card can be obtained from the card resource.
      - `paypal_express_checkout`
        Payments made via PayPal Express Checkout.
      - `amazon_payments`
        Payments made via Amazon Payments.
      - `direct_debit`
        Represents bank account for which the direct debit or ACH agreement/mandate is created.
      - `generic`
        Payments made via Generic Payment Method.
      - `alipay`
        Payments made via Alipay.
        
        This payment source is deprecated.
      - `unionpay`
        Payments made via UnionPay.
      - `wechat_pay`
        Payments made via WeChat Pay.
        
        This payment source is deprecated.
      - `ideal`
        Payments made via iDEAL.
      - `google_pay`
        Payments made via Google Pay.
      - `sofort`
        Payments made via Sofort.
      - `bancontact`
        Payments made via Bancontact Card.
      - `giropay`
        Payments made via giropay.
      - `dotpay`
        Payments made via Dotpay.
      - `upi`
        UPI Payments.
      - `netbanking_emandates`
        Netbanking (eMandates) Payments.
      - `venmo`
        Payments made via Venmo
      - `pay_to`
        Payments made via PayTo
      - `faster_payments`
        Payments made via Faster Payments
      - `sepa_instant_transfer`
        Payments made via Sepa Instant Transfer
      - `automated_bank_transfer`
        Represents virtual bank account using which the payment will be done.
      - `klarna_pay_now`
        Payments made via Klarna Pay Now
      - `online_banking_poland`
        Payments made via Online Banking Poland
      - `payconiq_by_bancontact`
        Payments made via Payconiq by Bancontact.
      - `electronic_payment_standard`
        Electronic Payment Standard
      - `kbc_payment_button`
        KBC Payment Button
      - `pay_by_bank`
        Pay By Bank
      - `trustly`
        Trustly
      - `stablecoin`
        Payments made via Stablecoin.
      - `kakao_pay`
        Payments made via Kakao Pay.
      - `naver_pay`
        Payments made via Naver Pay.
      - `revolut_pay`
        Payments made via Revolut Pay.
      - `cash_app_pay`
        Payments made via Cash App Pay.
      - `twint`
        Payments made via Twint
      - `go_pay`
        Payments made via GoPay
      - `grab_pay`
        Payments made via GrabPay
      - `pay_co`
        Payments made via PayCo
      - `after_pay`
        Payments made via Afterpay
      - `swish`
        Payments made via Swish
      - `payme`
        Payments made via PayMe
      - `pix`
        Payments made via Pix
      - `klarna`
        Payments made via Klarna.
      - `alipay_hk`
        Payments made via Alipay HK.
      - `paypay`
        Payments made via PayPay
      - `gcash`
        Payments made via GCash.
      - `south_korean_cards`
        Payments made via South Korean Cards
      - `paynow`
      - `bizum`
      - `promptpay`
      - `dana`
        Payments made via Dana.
      - `touch_n_go`
        Payments made via Touch 'n Go.
      - `tamara`
        Payments made via Tamara.
      - `qpay`
        Payments made via Qpay.
      - `ovo`
      - `momo`
      - `mercado_pago`
      - `nequi`
      - `nupay`
      - `picpay`
      - `thai_qr`
      - `blik`
      - `fpx`
      - `wero`
      - `p24`
      - `affirm_pay`
      - `rakuten_pay`
  - `gateway_account_id` (optional, string, max chars=50)
    The gateway account in which this payment source is stored.
  - `reference_id` (optional, string, max chars=200)
    The reference id. In the case of Amazon and PayPal this will be the _billing agreement id_. For GoCardless direct debit this will be 'mandate id'. In the case of card this will be the identifier provided by the gateway/card vault for the specific payment method resource. **Note:** This is not the one-time temporary token provided by gateways like Stripe.
    
    For more details refer [Update payment method for a customer](/docs/api/customers/update-payment-method-for-a-customer) API under Customer resource.
  - `tmp_token` (required if reference_id not provided, string, max chars=65k)
    Single-use toke created by payment gateways. In Stripe, a single-use token is created for direct debit. In Braintree, a nonce is created for PayPal.
  - `issuing_country` (optional, string, max chars=50)
    [ISO 3166 alpha-2 country code](https://www.iso.org/iso-3166-country-codes.html) .
    
    **Note**: If you enter an invalid country code, the system will return an error.
    
    If you have enabled [EU VAT](https://www.chargebee.com/docs/eu-vat.html) in 2021 or have [manually enabled](https://www.chargebee.com/docs/brexit.html#what-needs-to-be-done-in-chargebee) the Brexit configuration, then `XI` (the code for **United Kingdom - Northern Ireland** ) is available as an option.
  - `additional_information` (optional, jsonobject)
    -   `checkout_com`: While adding a new payment method using [permanent token](/docs/api/payment_sources/create-using-permanent-token) or passing raw card details to Checkout.com, `document` ID and `country_of_residence` are required to support payments through [dLocal](https://www.checkout.com/docs/previous/payments/payment-methods/cards/dlocal).
        
        -   `payer`: User related information.
            -   `country_of_residence`: This is required since the billing country associated with the user's payment method may not be the same as their country of residence. Hence the user's country of residence needs to be specified. The country code should be a [two-character ISO code](https://docs.checkout.com/resources/codes/country-codes).
            -   `document`: Document ID is the user's [identification number](https://docs.dlocal.com/api-documentation/payins-api-reference/country-reference#documents) based on their country.
    -   `bluesnap`: While passing raw card details to BlueSnap, if `fraud_session_id` is added, [additional validation](https://developers.bluesnap.com/docs/fraud-prevention) is performed to avoid fraudulent transactions.
        
        -   `fraud`: Fraud identification related information.
            -   `fraud_session_id`: Your [BlueSnap fraud session ID](https://developers.bluesnap.com/docs/fraud-prevention#section-implementing-device-data-collector) required to perform anti-fraud validation.
    -   `braintree`: While passing raw card details to Braintree, your `fraud_merchant_id` and the user's `device_session_id` can be added to perform [additional validation](https://developers.braintreepayments.com/guides/premium-fraud-management-tools/device-data-collection/javascript/v3#collecting-device-data) and avoid fraudulent transactions.
        
        -   `fraud`: Fraud identification related information.
            -   `device_session_id`: Session ID associated with the user's device.
            -   `fraud_merchant_id`: Your [merchant ID](https://developers.braintreepayments.com/guides/premium-fraud-management-tools/device-data-collection/javascript/v3#collecting-device-data) for fraud detection.
    -   `chargebee_payments`: While passing raw card details to Chargebee Payments, if `fraud_session_id` is added, additional validation is performed to avoid fraudulent transactions.
        
        -   `fraud`: Fraud identification related information.
            -   `fraud_session_id`: Your Chargebee Payments fraud session ID required to perform anti-fraud validation.
    -   `bank_of_america`: While passing raw card details to Bank of America, your user's `device_session_id` can be added to perform additional validation and avoid fraudulent transactions.
        
        -   `fraud`: Fraud identification related information.
            -   `device_session_id`: Session ID associated with the user's device.
    -   `ecentric`: This parameter is used to verify and process payment method details in Ecentric. If the `merchant_id` parameter is included, Chargebee will vault it / perform a lookup and verification against this `merchant_id`, overriding the one configured in Chargebee. If tokens and processing occur in the same Merchant GUID, you can just skip this part.
        
        -   `merchant_id`: Merchant GUID where the card is vaulted or need to be vaulted.
    -   `ebanx`: While passing raw card details to EBANX, the user's `document` is required for some countries and `device_session_id` can be added to perform [additional validation](https://developer.ebanx.com/docs/payments/guides/features/device-fingerprint#device-fingerprint) and avoid fraudulent transactions.
        
        -   `payer`: User related information.
            -   `document`: Document is the user's identification number based on their country.
        -   `fraud`: Fraud identification related information.
            -   `device_session_id`: Session ID associated with the user's device

## Returns

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

- `card` (Card object)
  Resource object representing card
