# Create using permanent token

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


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

Creates a payment source for a [customer](/docs/api/customers) using a permanent token obtained from the [payment gateway](https://www.chargebee.com/docs/payments/2.0/payment-gateways-and-configuration/gateway_settings).

Use this API to add a payment method that has already been vaulted in your gateway account. The permanent token enables Chargebee to securely link the payment method to the customer. This enables payment collection for future charges (both recurring and one-time) without requiring the customer to re-enter their payment details.

### Prerequisites & Constraints

-   The permanent token must belong to a gateway account configured in Chargebee.
-   The token should be a **permanent/vault token**, not a single-use token.
-   When multiple gateway accounts are configured in [Chargebee Billing](https://app.chargebee.com), you must pass the `gateway_account_id` parameter if:
    -   [Smart Routing](https://www.chargebee.com/docs/payments/2.0/payment-gateways-and-configuration/gateway_settings#smart-routing) is not configured for the payment method.
    -   Smart Routing is configured for the payment method, but the selected gateway account does not match the provided token.

### Impacts

**Customer**

Pass the [`replace_primary_payment_source`](/docs/api/payment_sources/create-using-permanent-token#replace_primary_payment_source) parameter as `true` to update the customer's [`primary_payment_source_id`](/docs/api/payment_sources/export-payment-source). Otherwise, the existing primary payment source will remain unchanged.

## Sample Request

#### cURL

```bash
curl  https://{site}.chargebee.com/api/v2/payment_sources/create_using_permanent_token \
     -u {site_api_key}:\
     -d customer_id="__test__XpbTXGTSRp4Q5TE9" \
     -d gateway_account_id="gw___test__5SK2lMpwSRp4Mx02v" \
     -d reference_id="cus_J7rVCB7oVNyDJF" \
     -d type="CARD"
```

#### .NET

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

ApiConfig.Configure("{site}","{site_api_key}");
EntityResult result = PaymentSource.CreateUsingPermanentToken()
		.CustomerId("__test__XpbTXGTSRp4Q5TE9")
		.GatewayAccountId("gw___test__5SK2lMpwSRp4Mx02v")
		.ReferenceId("cus_J7rVCB7oVNyDJF")
		.Type(TypeEnum.Card)
		.Request();

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

#### Go

```go
package main
import (
    "fmt"
    "github.com/chargebee/chargebee-go/v3"
    paymentsourceAction "github.com/chargebee/chargebee-go/v3/actions/paymentsource"
    "github.com/chargebee/chargebee-go/v3/models/paymentsource"
    enum "github.com/chargebee/chargebee-go/v3/enum"
)
func main() {
    chargebee.Configure("{site_api_key}","{site}");
    res,err := paymentsourceAction.CreateUsingPermanentToken(&paymentsource.CreateUsingPermanentTokenRequestParams{
        CustomerId : "__test__XpbTXGTSRp4Q5TE9",
        GatewayAccountId : "gw___test__5SK2lMpwSRp4Mx02v",
        ReferenceId : "cus_J7rVCB7oVNyDJF",
        Type : enum.TypeCard,
    }).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.PaymentSourceCreateUsingPermanentTokenRequest{
    CustomerId : "__test__XpbTXGTSRp4Q5TE9",
    GatewayAccountId : "gw___test__5SK2lMpwSRp4Mx02v",
    ReferenceId : "cus_J7rVCB7oVNyDJF",
    Type : chargebee.TypeCard,
}
  res, err := client.PaymentSource.CreateUsingPermanentToken(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 = PaymentSource.createUsingPermanentToken()
            .customerId("__test__XpbTXGTSRp4Q5TE9")
            .gatewayAccountId("gw___test__5SK2lMpwSRp4Mx02v")
            .referenceId("cus_J7rVCB7oVNyDJF")
            .type(Type.CARD)
            .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.paymentSource.PaymentSource;
import com.chargebee.v4.models.paymentSource.params.PaymentSourceCreateUsingPermanentTokenParams;
import com.chargebee.v4.models.paymentSource.responses.PaymentSourceCreateUsingPermanentTokenResponse;

public class PaymentSourceCreateUsingPermanentToken {

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

        PaymentSourceCreateUsingPermanentTokenParams params = PaymentSourceCreateUsingPermanentTokenParams.builder()
            .customerId("__test__XpbTXGTSRp4Q5TE9")
            .gatewayAccountId("gw___test__5SK2lMpwSRp4Mx02v")
            .referenceId("cus_J7rVCB7oVNyDJF")
            .type(PaymentSourceCreateUsingPermanentTokenParams.Type.CARD)
            .build();

        PaymentSourceCreateUsingPermanentTokenResponse response = client.paymentSources().createUsingPermanentToken(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.paymentSource.createUsingPermanentToken({
        customer_id: "__test__XpbTXGTSRp4Q5TE9",
        gateway_account_id: "gw___test__5SK2lMpwSRp4Mx02v",
        reference_id: "cus_J7rVCB7oVNyDJF",
        type: "card"
    });

    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->paymentSource()->createUsingPermanentToken([
    "customer_id" => "__test__XpbTXGTSRp4Q5TE9",
    "gateway_account_id" => "gw___test__5SK2lMpwSRp4Mx02v",
    "reference_id" => "cus_J7rVCB7oVNyDJF",
    "type" => "card"
]);
$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.PaymentSource.create_using_permanent_token(
    cb_client.PaymentSource.CreateUsingPermanentTokenParams(
        customer_id="__test__XpbTXGTSRp4Q5TE9",
        gateway_account_id="gw___test__5SK2lMpwSRp4Mx02v",
        reference_id="cus_J7rVCB7oVNyDJF",
        type=chargebee.Type.CARD
    )
)
customer = response.customer
payment_source = response.payment_source
```

#### Ruby

```ruby
require 'chargebee'

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

result = ChargeBee::PaymentSource.create_using_permanent_token({
  :customer_id => "__test__XpbTXGTSRp4Q5TE9",
  :gateway_account_id => "gw___test__5SK2lMpwSRp4Mx02v",
  :reference_id => "cus_J7rVCB7oVNyDJF",
  :type => "CARD"
})

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

## Sample Response

```json
{
  "customer": {
    "allow_direct_debit": false,
    "auto_collection": "on",
    "card_status": "valid",
    "created_at": 1517487229,
    "deleted": false,
    "excess_payments": 0,
    "first_name": "Mark",
    "id": "__test__XpbTXGTSRp4Q5TE9",
    "last_name": "Henry",
    "net_term_days": 0,
    "object": "customer",
    "payment_method": {
      "gateway": "stripe",
      "gateway_account_id": "gw___test__5SK2lMpwSRp4Mx02v",
      "object": "payment_method",
      "reference_id": "cus_J7rVCB7oVNyDJF/card_1IVbmUJv9j0DyntJninpvymH",
      "status": "valid",
      "type": "card"
    },
    "pii_cleared": "active",
    "preferred_currency_code": "USD",
    "primary_payment_source_id": "pm___test__XpbTXGTSRp4QTuEF",
    "promotional_credits": 0,
    "refundable_credits": 0,
    "resource_version": 1517487231068,
    "taxability": "taxable",
    "unbilled_charges": 0,
    "updated_at": 1517487231
  },
  "payment_source": {
    "card": {
      "brand": "visa",
      "expiry_month": 12,
      "expiry_year": 2022,
      "funding_type": "credit",
      "iin": "******",
      "last4": "1111",
      "masked_number": "************1111",
      "object": "card"
    },
    "created_at": 1517487231,
    "customer_id": "__test__XpbTXGTSRp4Q5TE9",
    "deleted": false,
    "gateway": "stripe",
    "gateway_account_id": "gw___test__5SK2lMpwSRp4Mx02v",
    "id": "pm___test__XpbTXGTSRp4QTuEF",
    "issuing_country": "US",
    "object": "payment_source",
    "reference_id": "cus_J7rVCB7oVNyDJF/card_1IVbmUJv9j0DyntJninpvymH",
    "resource_version": 1517487231066,
    "status": "valid",
    "type": "card",
    "updated_at": 1517487231
  }
}
```

## URL Format

**POST** https://[site].chargebee.com/api/v2/payment_sources/create_using_permanent_token

## Input Parameters

- `customer_id` (required, string, max chars=50)
  Identifier of the customer with whom this payment source is associated.

- `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.
    - `apple_pay`
      Payments made via Apple Pay.
    - `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 to which the payment source is associated.

- `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 a card, this will be the identifier provided by the gateway or card vault for the specific payment method resource.
  
  **Note:**
  
  -   This is not the one-time temporary token provided by gateways like Stripe.
      
  -   `reference_id` is an alternative for `payment_method_token`, `customer_profile_token`, `network_transaction_id`, or `mandate_id`.
      
  -   `payment_method_token`, `customer_profile_token`, `network_transaction_id`, or `mandate_id` cannot be used with `reference_id`.
      
  -   `reference_id` is a combination of multiple tokens available at the gateway. Learn more about the combination of each gateway from this [document](/docs/api/payment_parameters).

- `issuing_country` (optional, string, max chars=50)
  2-letter (alpha2) ISO country code. Indicates your customer's payment method country of issuance. Applicable for PayPal via Braintree.

- `replace_primary_payment_source` (optional, boolean, default=false)
  Indicates whether the primary payment source should be replaced with this payment source. In case of Create Subscription for Customer endpoint, the default value is True. Otherwise, the default value is False.

- `payment_method_token` (optional, string, max chars=100)
  An identifier provided by the gateway or card vault for the specific payment method resource.
  
  **Note:** `payment_method_token` is an alternative for reference\_id and cannot be used with `reference_id`.

- `customer_profile_token` (optional, string, max chars=100)
  A unique identifier associated with a customer\`s profile within a payment gateway.
  
  **Note:** `customer_profile_token` is an alternative for reference\_id and cannot be used with `reference_id`.

- `network_transaction_id` (optional, string, max chars=100)
  An identifier of the payment or authorization transaction at the gateway initiated using this payment method.
  
  **Note:** `network_transaction_id` is an alternative for reference\_id and cannot be used with `reference_id`.

- `mandate_id` (optional, string, max chars=100)
  An identifier of mandates which is an authorization given by the payer (usually a customer or account holder) to allow a third party such as a merchant or service provider to initiate payments from their account.
  
  **Note:** `mandate_id` is an alternative for reference\_id and cannot be used with `reference_id`.

- `skip_retrieval` (optional, boolean, default=false)
  By default, the value is `false` and payment method details will be retrieved from the selected payment gateway using `reference_id` or `payment_method_token` / `customer_profile_token` / `network_transaction_id` / `mandate_id`. Learn more about the multiple token combinations of each gateway from this [document](/docs/api/payment_parameters). Enter the value as `true` for the payment gateways that do not allow to retrieve the payment method details. Once passed, it will create payment method at Chargebee with the provided attributes in `payment_method_token`, `customer_profile_token`, `network_transaction_id`, `mandate_id`, `card`, and `billing_address`.
  
  **Note:** Currently, the `skip_retrieval` value as `true` is only supported for the Vantiv payment gateway.

- `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://docs.checkout.com/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 .

- `card` (optional, string)
  Parameters of tokenized card details
  - `last4` (optional, string, min chars=4, max chars=4)
    Last four digits of the card number
  - `iin` (optional, string, min chars=6, max chars=6)
    The Issuer Identification Number, i.e. the first six digits of the card number
  - `expiry_month` (optional, integer, min=1, max=12)
    Card expiry month.
  - `expiry_year` (optional, integer)
    Card expiry year.
  - `brand` (optional, enumerated string)
    Card brand
    Possible enum values:
      - `visa`
        A Visa card.
      - `mastercard`
        A MasterCard.
      - `american_express`
        An American Express card.
      - `discover`
        A Discover card.
      - `jcb`
        A JCB card.
      - `diners_club`
        A Diner's Club card.
      - `other`
        Card belonging to types other than those listed above.
      - `bancontact`
        A Bancontact card.
      - `cmr_falabella`
        A CMR Falabella card.
      - `tarjeta_naranja`
        A Tarjeta Naranja card.
      - `nativa`
        A Nativa card.
      - `cencosud`
        A Cencosud card.
      - `cabal`
        A Cabal card.
      - `argencard`
        An Argencard.
      - `elo`
        A Elo card.
      - `hipercard`
        An Hipercard.
      - `carnet`
        A Carnet card.
      - `rupay`
        A Rupay card.
      - `maestro`
        A Maestro card.
      - `dankort`
        A Dankort card.
      - `cartes_bancaires`
        A Cartes Bancaires card.
      - `mada`
        A Mada card.
  - `funding_type` (optional, enumerated string)
    Card Funding type
    Possible enum values:
      - `credit`
        A credit card.
      - `debit`
        A debit card.
      - `prepaid`
        A prepaid card.
      - `not_known`
        An unknown card.

- `billing_address` (optional, string)
  Parameters for billing\_address
  - `first_name` (optional, string, max chars=150)
    The first name of the billing contact.
  - `last_name` (optional, string, max chars=150)
    The last name of the billing contact.
  - `email` (optional, string, max chars=70)
    The email address.
  - `line1` (optional, string, max chars=150)
    Address line 1
  - `line2` (optional, string, max chars=150)
    Address line 2
  - `line3` (optional, string, max chars=150)
    Address line 3
  - `city` (optional, string, max chars=50)
    The name of the city.
  - `state_code` (optional, string, max chars=50)
    The [ISO 3166-2 state/province code](https://www.iso.org/obp/ui/#search/code) without the country prefix. Currently supported for USA, Canada, India and UAE. For instance, for Arizona (USA), set `state_code` as `AZ` (not `US-AZ` ). For Tamil Nadu (India), set as `TN` (not `IN-TN` ). For British Columbia (Canada), set as `BC` (not `CA-BC` ). For Dubai (UAE), set as `DU` (not `AE-DU` ).
  - `state` (optional, string, max chars=50)
    The state/province name. Is set by Chargebee automatically for US, Canada, India and UAE, if `state_code` is provided.
  - `zip` (optional, string, max chars=20)
    Zip or postal code. The number of characters is validated according to the rules [specified here](https://chromium-i18n.appspot.com/ssl-address) .
  - `country` (optional, string, max chars=50)
    The billing address country of the customer. Must be one of [ISO 3166 alpha-2 country code](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2#Officially_assigned_code_elements) .
    
    **Brexit**
    
    If you have enabled [EU VAT](https://www.chargebee.com/docs/eu-vat.html) in 2021 or later, or have [manually enable](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.

## Returns

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

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