> ## Documentation Index
> Fetch the complete documentation index at: https://docs.mangopay.com/llms.txt
> Use this file to discover all available pages before exploring further.

# How to process a card payment

> Make a card payment to get funds into a Mangopay wallet

## Introduction

This how-to guide will take you through the steps to successfully simulate a payment by card in the Sandbox testing environment.

<Info>
  **Prerequisites**

  * A `ClientId` and an API key – if you don't have these, <a href="https://mangopay.com/contact" target="_blank">contact Sales</a> to get access to the <a href="https://hub.mangopay.com/" target="_blank">Mangopay Dashboard</a>
</Info>

<Note>
  **Note – Postman collection contains this flow**

  The public Mangopay API Postman collection contains a dedicated folder with the endpoints for this how-to guide.

  <a href="/postman" target="_blank">Get started →</a>
</Note>

## 1. Create a user

In this guide, we'll register a natural user to represent a private individual who just needs to make a payment on your platform.

Payers only need to provide a first name, last name, and email (see the <a href="/guides/users/categories" target="_blank">user categories</a> for more information).

> [**POST** /V2.01/\{ClientId}/users/natural](/api-reference/users/create-natural-user)

<CodeGroup>
  ```json REST - Payer theme={null}
  {
      "UserCategory": "PAYER",
      "TermsAndConditionsAccepted": false,
      "Address": {
          "AddressLine1": "3 rue de la Cité",
          "AddressLine2": "Appartement 7",
          "City": "Paris",
          "Region": "Île-de-France",
          "PostalCode": "75004",
          "Country": "FR"
      },
      "FirstName": "Alex",
      "LastName": "Smith",
      "Email": "alex.smith@example.com",
      "Tag": "Created using Mangopay API Postman collection"
  }
  ```

  ```php PHP theme={null}
  <?php 

  require_once 'vendor/autoload.php';

  use MangoPay\MangoPayApi;
  use MangoPay\Libraries\ResponseException as MGPResponseException;
  use MangoPay\Libraries\Exception as MGPException;

  $api = new MangoPayApi();

  $api->Config->ClientId = 'your-client-id';
  $api->Config->ClientPassword = 'your-api-key';
  $api->Config->TemporaryFolder = 'tmp/';

  try {
      $user = new \MangoPay\UserNatural();

      $user->FirstName = 'Alex';
      $user->LastName = 'Smith';
      $user->Email = "asmith@example.com";
      
      $user->Address = new \MangoPay\Address();
      $user->Address->AddressLine1 = 'Rue des plantes';
      $user->Address->AddressLine2 = 'Building A';
      $user->Address->City = 'Paris';
      $user->Address->Country = 'FR';
      $user->Address->PostalCode = '75000';
      $user->Address->Region = 'IDF';
      $user->Tag = 'Created using Mangopay PHP SDK';
      
      $user->TermsAndConditionsAccepted = true;
      $user->UserCategory = 'Payer';
      
      $response = $api->Users->Create($user);

      print_r($response);
  } catch(MGPResponseException $e) {
      print_r($e);
  } catch(MGPException $e) {
      print_r($e);
  }  
  ```

  ```javascript NodeJS   theme={null}
  const mangopayInstance = require('mangopay4-nodejs-sdk');
  const mangopay = new mangopayInstance({
      clientId: "your-client-id",
      clientApiKey: "your-api-key",
  })

  let naturalUser = {
    Address: {
      AddressLine1: '2795 Edgewood Road',
      AddressLine2: null,
      City: 'Little Rock',
      Region: 'Arkansas',
      PostalCode: '72212',
      Country: 'US',
    },
    FirstName: 'John',
    LastName: 'Doe',
    Birthday: 655772400,
    Nationality: 'FR',
    CountryOfResidence: 'US',
    Tag: 'My first user',
    Email: 'john.doe@mangopay.com',
    TermsAndConditionsAccepted: true,
    UserCategory: 'OWNER',
    PersonType: 'NATURAL',
    NaturalSca: false,
  }

  const createUser = async (userObject) => {
    return await mangopay.Users.create(userObject)
      .then((response) => {
        console.info(response)
        return response
      })
      .catch((err) => {
        console.log(err)
        return false
      })
  }

  createUser(naturalUser)
    
  ```

  ```ruby Ruby   theme={null}
  require 'mangopay'

  MangoPay.configure do |client|
      client.preproduction = true
      client.client_id = 'your-client-id'
      client.client_apiKey = 'your-api-key'
      client.log_file = File.join(Dir.pwd, 'mangopay.log')
  end

  def createNaturalUser(naturalUserObject)
      begin
          response = MangoPay::NaturalUser.create(naturalUserObject)
          puts response
          return response
      rescue MangoPay::ResponseError => error
          puts "Failed to create User: #{error.message}"
          puts "Error details: #{error.details}"
          return false
      end
  end

  myNaturalUser = {
      Tag: 'Created using Mangopay Ruby SDK',
      Email: 'john.ruby@test.com',
      FirstName: 'John',
      LastName: 'Doe',
      Address: {
          AddressLine1: '2795 Edgewood Road',
          City: 'Little Rock',
          Region: 'Arkansas',
          PostalCode: '72212',
          Country: 'US'
      },
      Birthday: 655772400,
      Nationality: 'FR',
      CountryOfResidence: 'US',
      TermsAndConditionsAccepted: true,
      UserCategory: 'OWNER'
  }

  createNaturalUser(myNaturalUser)  
  ```

  ```java Java   theme={null}
  import com.mangopay.MangoPayApi;
  import com.mangopay.core.Address;
  import com.mangopay.entities.User;
  import com.mangopay.entities.UserNatural;
  import com.mangopay.core.enumerations.UserCategory;
  import com.mangopay.core.enumerations.CountryIso;

  import java.lang.reflect.Field;

  public class CreateNaturalUser {
      public static void main(String[] args) throws Exception {
          MangoPayApi mangopay = new MangoPayApi();
          mangopay.getConfig().setClientId("your-client-id");
          mangopay.getConfig().setClientPassword("your-api-key");

          UserNatural user = new UserNatural();
          Address address = new Address();

          address.setAddressLine1("27 Rue de Rivoli");
          address.setCity("Paris");
          address.setRegion("Île-de-France");
          address.setPostalCode("75001");
          address.setCountry(CountryIso.FR);

          user.setFirstName("Alex");
          user.setLastName("Smith");
          user.setEmail("alex.smith@mgp.com");
          user.setAddress(address);
          user.setBirthday(655772400);
          user.setNationality(CountryIso.FR);
          user.setCountryOfResidence(CountryIso.FR);
          user.setTermsAndConditionsAccepted(true);
          user.setTag("Created using the Mangopay Java SDK");
          user.setUserCategory(UserCategory.PAYER);

          User createUser = mangopay.getUserApi().create(user);  
          
          System.out.println(String.format("id: %s", createUser.getId()));
          printObjectFields(createUser);
      }

      private static void printObjectFields(Object obj) {
          Class<?> objClass = obj.getClass();
          Field[] fields = objClass.getDeclaredFields();
          for (Field field : fields) {
              field.setAccessible(true);
              try {
                  Object value = field.get(obj);
                  if (value instanceof Address) {
                      System.out.println(field.getName() + ": ");
                      printObjectFields(value); 
                  } else {
                      System.out.println(field.getName() + ": " + value);
                  }
              } catch (IllegalAccessException e) {
                  e.printStackTrace();
              }
          }
      }
  }  
  ```

  ```python Python   theme={null}
  from pprint import pprint
  import mangopay

  mangopay.client_id = 'your-client-id'
  mangopay.apikey = 'your-api-key'

  from mangopay.api import APIRequest
  handler = APIRequest(sandbox=True)

  from mangopay.resources import NaturalUser
  from mangopay.utils import Address

  natural_user = NaturalUser(
      address = Address(
          address_line_1 = '42 Maple Road',
          city = 'London',
          postal_code = 'WC1X 0AA',
          country = 'GB'
      ),
      first_name = 'Olivia',
      last_name = 'Turner',
      birthday = 655772400,
      nationality = 'GB',
      country_of_residence = 'GB',
      person_type = 'NATURAL',
      tag = 'Created with Mangopay Python SDK',
      email = 'olivia.turner@test.com',
      terms_and_conditions_accepted = True, 
      user_category = 'OWNER' 
  )

  create_natural_user = natural_user.save()

  pprint(create_natural_user)

    
  ```
</CodeGroup>

In response, the API returns an `Id` for the user, which you'll need for the next step.

```json theme={null}
{
    "Id": "user_m_01J18HZSACR1EMYNY1TBS8KTJD"
}
```

## 2. Create a wallet for the user

All users need a wallet to which they can pay funds, even it it is immediately transferred to another wallet (for example, one owned by the user receiving the funds).

Use the `Id` of the user as the owner of the wallet:

> [**POST** /V2.01/\{ClientId}/wallets](/api-reference/wallets/create-wallet)

<CodeGroup>
  ```json REST   theme={null}
  {
      "Description": "Description of the user's wallet",
      "Owners": [
          "user_m_01J18HZSACR1EMYNY1TBS8KTJD"
      ],
      "Currency": "EUR",
      "Tag": "Created using Mangopay API Postman Collection",
  }  
  ```

  ```php PHP theme={null}
  <?php 

  require_once 'vendor/autoload.php';

  use MangoPay\MangoPayApi;
  use MangoPay\Libraries\ResponseException as MGPResponseException;
  use MangoPay\Libraries\Exception as MGPException;

  $api = new MangoPayApi();

  $api->Config->ClientId = 'your-client-id';
  $api->Config->ClientPassword = 'your-api-key';
  $api->Config->TemporaryFolder = 'tmp/';

  try {
      
      $wallet = new \MangoPay\Wallet();

      $wallet->Owners = ['198675238'];
      $wallet->Currency = 'EUR';
      $wallet->Description = 'EUR Wallet';
      $wallet->Tag = 'Created with Mangopay PHP SDK';

      $response = $api->Wallets->Create($wallet);

      print_r($response);
  } catch(MGPResponseException $e) {
      print_r($e);
  } catch(MGPException $e) {
      print_r($e);
  }  
  ```

  ```javascript NodeJS   theme={null}
  const mangopayInstance = require('mangopay4-nodejs-sdk')
  const mangopay = new mangopayInstance({
      clientId: 'your-client-id',
      clientApiKey: 'your-api-key'
  })

  let userId = '165863393'

  let wallet = {
      Owners: [userId],
      Currency: 'EUR',
      Description: 'Wallet in EUR',
      Tag: 'Created using Mangopay NodeJS SDK'
  }

  const createWallet = async (walletObject) => {
    return await mangopay.Wallets.create(wallet)
      .then((response) => {
        console.info(response)
        return response
      })
      .catch((err) => {
        console.log(err)
        return false
      })
  }

  createWallet(wallet)  
  ```

  ```ruby Ruby   theme={null}
  require 'mangopay'

  MangoPay.configure do |client|
      client.preproduction = true
      client.client_id = 'your-client-id'
      client.client_apiKey = 'your-api-key'
      client.log_file = File.join(Dir.pwd, 'mangopay.log')
  end

  def createWallet(walletObject)
      begin
          response = MangoPay::Wallet.create(walletObject)
          puts response
          return response
      rescue MangoPay::ResponseError => error
          puts "Failed to create wallet: #{error.message}"
          puts "Error details: #{error.details}"
          return false
      end
  end

  myUser = {
    Id: '146476890',
  }

  myWallet = {
      Owners: [myUser[:Id]],
      Currency: 'EUR',
      Description: 'Wallet in EUR',
      Tag: 'Created using Mangopay Ruby SDK'
  }

  createWallet(myWallet)  
  ```

  ```java Java   theme={null}
  import com.google.gson.Gson;
  import com.google.gson.GsonBuilder;
  import com.mangopay.MangoPayApi;
  import com.mangopay.core.Money;
  import com.mangopay.core.enumerations.CurrencyIso;
  import com.mangopay.entities.Wallet;

  public class CreateWallet {
          public static void main(String[] args) throws Exception {
          MangoPayApi mangopay = new MangoPayApi();
          mangopay.getConfig().setClientId("your-client-id");
          mangopay.getConfig().setClientPassword("your-api-key");

          ArrayList<String> owner = new ArrayList<String>();
          owner.add("user_m_01HSAVT2J0REPGV5ZRPNK079K9");
          Wallet wallet = new Wallet();

          wallet.setOwners(owner);
          wallet.setCurrency(CurrencyIso.EUR);
          wallet.setDescription("EUR Wallet");
          wallet.setTag("Created using the Mangopay Java SDK"); 

          Wallet createWallet = mangopay.getWalletApi().create(wallet);
          
          Gson prettyPrint = new GsonBuilder().setPrettyPrinting().create();
          String prettyJson = prettyPrint.toJson(updateUbo);

          System.out.println(createWallet);
      }
  }
  ```

  ```python Python   theme={null}
  from pprint import pprint
  import mangopay

  mangopay.client_id='your-client-id'
  mangopay.apikey='your-api-key'

  from mangopay.api import APIRequest
  handler = APIRequest(sandbox=True)

  from mangopay.resources import NaturalUser, Wallet

  natural_user = NaturalUser.get('213753890')

  user_wallet = Wallet(
      owners=[natural_user],
      description='Wallet of Rhoda Keeling',
      currency='EUR',
      tag="Created using the Mangopay Python SDK"
  )

  create_wallet = user_wallet.save()

  pprint(create_wallet)  
  ```
</CodeGroup>

In response, the API returns an `Id` for the wallet, which you'll need to request the payment.

```json theme={null}
{
    "Id": "wlt_m_01J18J1SQGG6KXNM3F8GD674TP"
}
```

## 3. Create a card registration

The tokenization process enables your platform to handle sensitive card details with Mangopay.

Create a Card Registration object to start this process, using the `Id` of the user as the `UserId`.

You also need to define the currency and type of the card at this stage.

> [**POST** /v2.01/\{ClientId}/cardregistrations](/api-reference/card-registrations/create-card-registration)

<CodeGroup>
  ```json REST   theme={null}
  {
      "Tag": null,
      "UserId": "user_m_01J7KACBPAV7XAF8AH9BDCJPRS",
      "CardType": "CB_VISA_MASTERCARD",
      "Currency": "EUR"
  }  
  ```

  ```php PHP theme={null}
  <?php 

  require_once 'vendor/autoload.php';

  use MangoPay\MangoPayApi;
  use MangoPay\Libraries\ResponseException as MGPResponseException;
  use MangoPay\Libraries\Exception as MGPException;

  $api = new MangoPayApi();

  $api->Config->ClientId = 'your-client-id';
  $api->Config->ClientPassword = 'your-api-key';
  $api->Config->TemporaryFolder = 'tmp/';

  try {
      $cardRegistration = new \MangoPay\CardRegistration();

      $cardRegistration->UserId = '195627761';
      $cardRegistration->CardType = 'CB_VISA_MASTERCARD';
      $cardRegistration->Currency = 'EUR';
      $cardRegistration->Tag = 'Created using Mangopay PHP SDK';

      $response = $api->CardRegistrations->Create($cardRegistration);

      print_r($response);
  } catch(MGPResponseException $e) {
      print_r($e);
  } catch(MGPException $e) {
      print_r($e);
  }  
  ```

  ```javascript NodeJS   theme={null}
  const mangopayInstance = require('mangopay4-nodejs-sdk');
  const mangopay = new mangopayInstance({
      clientId: "your-client-id",
      clientApiKey: "your-api-key",
  })

  let user = {
      Id: 'user_m_01HQK25M6KVHKDV0S36JY9NRKR',
    }

  let userCardRegistration = {
      UserId: user.Id,
      Currency: 'EUR',
      CardType: 'CB_VISA_MASTERCARD'
  }

  const createCardRegistration = async(cardRegistration) => {
      return await mangopay.CardRegistrations.create(cardRegistration)
      .then((response) => {
          console.info(response)
          return response
      })
      .catch((err) => {
          console.log(err)
          return false
      })
  }

  createCardRegistration(userCardRegistration)  
  ```

  ```ruby Ruby   theme={null}
  require 'mangopay'

  MangoPay.configure do |client|
      client.preproduction = true
      client.client_id = 'your-client-id'
      client.client_apiKey = 'your-api-key'
      client.log_file = File.join(Dir.pwd, 'mangopay.log')
  end

  def createCardRegistration(params)
      begin
          response = MangoPay::CardRegistration.create(params)
          puts response
          return response
      rescue MangoPay::ResponseError => error
          puts "Failed : #{error.message}"
          puts "Error details: #{error.details}"
          return false
      end
  end

  params = {
      "UserId": "user_m_01J2BGH2PGWC4NNWGADT75ATB6",
      "CardType": "CB_VISA_MASTERCARD",
      "Currency": "EUR"
  }

  createCardRegistration(params)
  ```

  ```python Python   theme={null}
  from pprint import pprint
  import mangopay

  mangopay.client_id='your-client-id'
  mangopay.apikey='your-api-key'

  from mangopay.api import APIRequest
  handler = APIRequest(sandbox=True)

  from mangopay.resources import NaturalUser, CardRegistration

  natural_user = NaturalUser.get('213600749')

  card_registration = CardRegistration(
      user_id = natural_user.id,
      currency = 'GBP',
      card_type =  'CB_VISA_MASTERCARD'
  )

  create_card_registration = card_registration.save()

  pprint(create_card_registration)  
  ```
</CodeGroup>

In response, the API returns the card registration object:

```json theme={null}
{
    "Id": "cardreg_m_01J18JJA7VH1Q38V3Z3F2C059D",
    "Tag": null,
    "CreationDate": 1719348570,
    "UserId": "user_m_01J18HZSACR1EMYNY1TBS8KTJD",
    "AccessKey": "1X0m87dmM2LiwFgxPLBJ",
    "PreregistrationData": "ObMObfSdwRfyE4QClGtUc1GGKTRAkntk_O93wafMNRiNkMGlbaUXBaLbPahxf7VD2ddFLVXdicolcUIkv_kKEA",
    "RegistrationData": null,
    "CardId": null,
    "CardType": "CB_VISA_MASTERCARD",
    "CardRegistrationURL": "https://pci.sandbox.mangopay.com/api/mangopay/vault/tokenize/eyJjbGllbnQiOiJjbGllbnRJZCIsInRva2VuIjoidW5xaXVlVG9rZW4ifQ==",
    "ResultCode": null,
    "ResultMessage": null,
    "Currency": "EUR",
    "Status": "CREATED"
}
```

From this response, you will need the following values for the next step:

* `AccessKey`
* `PreregistrationData`
* `CardRegistrationURL`

## 4. Send data to the tokenization server

The dedicated tokenization server allows your platform to process sensitive card data without exposing you or your end users to any security risk.

<Tip>
  **Best practice - Use Mangopay's card SDKs**

  Mangopay's <a href="/sdks/checkout">Checkout SDK</a> and <a href="/sdks/vault/web">Vault SDK</a> take care of the tokenization steps (Steps 2 & 3) for you, and generate a `CardId`.

  Simplify your integration on web, iOS, and Android.
</Tip>

Make a request to the `CardRegistrationURL` using the previously saved `AccessKey` and `PreregistrationData`:

* Use `AccessKey` data for the `accessKeyRef` parameter
* Use `PreregistrationData` data for the `data` parameter

You also need the end user’s card details entered on the payment page:

<table>
  <thead>
    <tr>
      <th class="header">Property</th>
      <th class="header">Type</th>
      <th class="header">Description</th>
    </tr>
  </thead>

  <tbody>
    <tr>
      <td class="table-content">`cardNumber `</td>
      <td class="table-content">string</td>
      <td class="table-content">The card number to be tokenized, without any separators.</td>
    </tr>

    <tr>
      <td class="table-content">`cardExpirationDate `</td>
      <td class="table-content">string (Format: “MMYY”)</td>
      <td class="table-content">The expiration date of the card.</td>
    </tr>

    <tr>
      <td class="table-content">`cardCvx `</td>
      <td class="table-content">string</td>
      <td class="table-content">The card verification code (on the back of the card, usually 3 digits).</td>
    </tr>
  </tbody>
</table>

<Warning>
  **Warning - Card details must never pass via your server**

  For security reasons, it is strictly forbidden to send the card details to your own server. You must rely on the dedicated PCI-DSS compliant tokenization server as described below.
</Warning>

The content-type for this call is "application/x-www-form-urlencoded".

> [**POST** \{CardRegistrationURL}](/api-reference/card-registrations/tokenize-card)

<CodeGroup>
  ```json REST theme={null}
  {
      "accessKey": "1X0m87dmM2LiwFgxPLBJ",
      "data": "ObMObfSdwRfyE4QClGtUc1GGKTRAkntk_O93wafMNRiNkMGlbaUXBaLbPahxf7VD2ddFLVXdicolcUIkv_kKEA",
      "cardNumber": "4970105181818183",
      "cardExpirationDate": "1229",
      "cardCvx": "123"
  }
  ```

  ```javascript NodeJS theme={null}
  const cardInfoObject = {
    cardNumber: '4970105181818183',
    cardExpirationDate: '1229',
    cardCvx: '123',
  };

  const preregistrationData = {
    id: createCardRegistrationResult.Id,
    cardRegistrationURL: createCardRegistrationResult.CardRegistrationURL,
    accessKeyRef: createCardRegistrationResult.AccessKey,
    data: createCardRegistrationResult.PreregistrationData,
  };
  ```

  ```kotlin theme={null}
  // Define the callback to receive tokenization result
  private fun tokenizeCallbacks() = object: Mangopay.TokenizeCardResultCallback{
          override fun success(result: CardRegistration?) {
              // You can use result.cardId to process payments from your backend
          }
          override fun error(exception: MangopayException) {
             // An error has occured
          }
  }
  // Invoke tokenizeCard method
  MangopayVaultSdk.tokenizeCard(card, cardRegistration, this, tokenizeCallbacks())
  ```

  ```swift theme={null}
  MangopayVault.tokenizeCard(
    card: card,
    cardRegistration: cardRegistration) { card, error in
        guard let _ = card else {
            self.showLoader(false)
            self.showAlert(with: error?.localizedDescription ?? "",title: "Failed ❌")
            return
        }
        self.showLoader(false)
        self.showAlert(with: "",title: "Successful 🎉")
    }
  ```
</CodeGroup>

In response, the API returns an encoded data string:

```json theme={null}
data=qc_ShKapgXF-A2t_OC72Ko0o568aiaCttReld3UFN6czA9d3uGhyoKRez0uSm5xbV52qH2pQE2MInBd_End2fZvHB1ZEXCpfiSAoeP1mpcuMSPVhQbki1iMJJFqJ1t8r0ftIYwFxOdfmDQ5GtM_cIg
```

You'll need this string for the next step.

## 5. Update the card registration with tokenization data

Update the Card Registration object by sending the data token returned by the tokenization server as the `RegistrationData`.

You should also provide the cardholder's name at this stage, which will be added to the Card object.

> [**PUT** /v2.01/\{ClientId}/cardregistrations/CardRegistrationId](/api-reference/card-registrations/update-card-registration)

<CodeGroup>
  ```json REST   theme={null}
  {
      "RegistrationData": "data=acIcnwwLleiAvlZUea5VxZlDBkf07H6B9-N7SrRv5Vv7oSLc1hhCdoFX4JxfZL2iUkLIQL3o9ehAOeaXCbc1KFWnr4ySDvkZ--mJxxdF-vw-gzLNe3lvG2loJvmwrDyRNx0xgKTVnyDj15oG8jR88g",
      "CardHolderName": "Alex Smith"
  }  
  ```

  ```php PHP theme={null}
  <?php 

  require_once 'vendor/autoload.php';

  use MangoPay\MangoPayApi;
  use MangoPay\Libraries\ResponseException as MGPResponseException;
  use MangoPay\Libraries\Exception as MGPException;

  $api = new MangoPayApi();

  $api->Config->ClientId = 'your-client-id';
  $api->Config->ClientPassword = 'your-api-key';
  $api->Config->TemporaryFolder = 'tmp/';

  try {
      $cardRegistration = new \MangoPay\CardRegistration();

      $cardRegistration->Id = '198660792';
      $cardRegistration->RegistrationData = 'data=EwQibNkLWbGepaBektTHQcnk7KxDDpQybRm3BWmKLu4DKdgmC-JI0b4bK9UW5C3u1L4A4AkhT3LJqC3_FAvbwYQXIPvj1ElxL2OIJfvlS3YXlJyOctdX1PGkkgCkgl3j0ftIYwFxOdfmDQ5GtM_cIg';

      $response = $api->CardRegistrations->Update($cardRegistration);

      print_r($response);
  } catch(MGPResponseException $e) {
      print_r($e);
  } catch(MGPException $e) {
      print_r($e);
  }  
  ```

  ```javascript NodeJS   theme={null}
  const mangopayInstance = require('mangopay4-nodejs-sdk');
  const mangopay = new mangopayInstance({
      clientId: "your-client-id",
      clientApiKey: "your-api-key",
  })

  let user = {
      Id: 'user_m_01HQK25M6KVHKDV0S36JY9NRKR',
    }

  let userCardRegistration = {
      Id: 'cardreg_m_01HRETW28RKJFC8RB9H625RVBD',
      UserId: user.Id,
      Currency: 'EUR',
      CardType: 'CB_VISA_MASTERCARD',
      RegistrationData: 'data=acIcnwwLleiAvlZUea5VxT5mw_fK696E0m-dvIdK-KnTCrftajOU7W3fTvYLnKiF68q7RUkmAEL86Wi8c0oX7wHD6vfA3lowMRD7SvlcCCl6Xl3Esy_DIyBzznraJzm70ftIYwFxOdfmDQ5GtM_cIg',
      CardHolderName: 'Alex Smith',
  }

  const updateCardRegistration = async(cardRegistration) => {
      return await mangopay.CardRegistrations.update(cardRegistration)
      .then((response) => {
          console.info(response)
          return response
      })
      .catch((err) => {
          console.log(err)
          return false
      })
  }

  updateCardRegistration(userCardRegistration)  
  ```

  ```ruby Ruby   theme={null}
  require 'mangopay'

  MangoPay.configure do |client|
      client.preproduction = true
      client.client_id = 'your-client-id'
      client.client_apiKey = 'your-api-key'
      client.log_file = File.join(Dir.pwd, 'mangopay.log')
  end

  def updateCardRegistration(card_registration_id, params)
      begin
          response = MangoPay::CardRegistration.update(card_registration_id, params)
          puts response
          return response
      rescue MangoPay::ResponseError => error
          puts "Failed : #{error.message}"
          puts "Error details: #{error.details}"
          return false
      end
  end

  params = {
      "RegistrationData": "data=acIcnwwLleiAvlZUea5VxW4I8X8iCT0M1Z4j5kgkKf4KQzh0G0UQLpozaVZwyqUOQJM3kYVZIDlCIp6vDysQ6F0qIb1486gpwf_EGW9fTllJlstGZZo5YuZ8RWz_814ONx0xgKTVnyDj15oG8jR88g",
      "CardHolderName": "ALEX SMITH"
  }

  updateCardRegistration("cardreg_m_01J2C8JM4YHV1Z57RKRBK97B0Y", params)
  ```

  ```python Python   theme={null}
  from pprint import pprint
  import mangopay

  mangopay.client_id='your-client-id'
  mangopay.apikey='your-api-key'

  from mangopay.api import APIRequest
  handler = APIRequest(sandbox=True)

  from mangopay.resources import CardRegistration

  user_card_registration = CardRegistration(
     id = '213600973',
     registration_data = 'data=R7hxMYui4h4rBkaNwbiH1DvQL35Y-goFSYQI384_jNsDngV32O95BVgk3Pg7vqU_mZIFFs4gFl24VlSBXNiuoi4Be_uieN3jEegz77g8ElaToz_b7S91YuROvHH0w6J40ftIYwFxOdfmDQ5GtM_cIg',
     card_holder_name = 'Alex Smith'
  )

  update_card_registration = user_card_registration.save()

  pprint(update_card_registration)  
  ```
</CodeGroup>

In response, the API returns the Card Registration object.

```json theme={null}
{
    "Id": "cardreg_m_01J18JJA7VH1Q38V3Z3F2C059D",
    "Tag": null,
    "CreationDate": 1719348570,
    "UserId": "user_m_01J18HZSACR1EMYNY1TBS8KTJD",
    "AccessKey": "1X0m87dmM2LiwFgxPLBJ",
    "PreregistrationData": "ObMObfSdwRfyE4QClGtUc1GGKTRAkntk_O93wafMNRiNkMGlbaUXBaLbPahxf7VD2ddFLVXdicolcUIkv_kKEA",
    "RegistrationData": "data=qc_ShKapgXF-A2t_OC72Ko0o568aiaCttReld3UFN6czA9d3uGhyoKRez0uSm5xbV52qH2pQE2MInBd_End2fZvHB1ZEXCpfiSAoeP1mpcuMSPVhQbki1iMJJFqJ1t8r0ftIYwFxOdfmDQ5GtM_cIg",
    "CardId": "card_m_01J18JJSZTKET9SX9V0W69M8H8",
    "CardType": "CB_VISA_MASTERCARD",
    "CardRegistrationURL": "https://pci.sandbox.mangopay.com/api/mangopay/vault/tokenize/eyJjbGllbnQiOiJjbGllbnRJZCIsInRva2VuIjoidW5xaXVlVG9rZW4ifQ==",
    "ResultCode": "000000",
    "ResultMessage": "Success",
    "Currency": "EUR",
    "Status": "VALIDATED"
}
```

The `CardId` is the tokenized version of the card that you can use in the next step to request the payment.

## 6. Get the end user's session data

In your integration, you'll also need to capture information from your end user’s browsing session to be able to request the payment.

In Sandbox, you can use dummy data.

### IP address

You need to send the end user’s IP address in IPV4 or IPV6 format. You can collect this when the user requests the payment, or else use an IP lookup service such as Cloudfare or ipify.

### Browser information

You also need to collect data about the end user’s browser.

* On a website, this data can be obtained from the browser.
* In a mobile app, you need to open a webview to fetch data from the browser (in the same way as for a website).

```javascript Browser information - JavaScript example theme={null}
let browserInfo = {
  acceptedHeader: navigator.languages,
  javaEnabled: navigator.javaEnabled(),
  language: navigator.language,
  colorDepth: window.screen.colorDepth,
  screenHeight: window.screen.height,
  screenWidth: window.screen.width,
  timeZoneOffset: new Date().getTimezoneOffset(),
  userAgent: navigator.userAgent,
  javascriptEnabled: true
}

console.log(browserInfo);
```

<Accordion title="See parameter details">
  <table>
    <thead>
      <tr>
        <th class="header">API child parameter</th>
        <th class="header">Type</th>
        <th class="header">Description</th>
        <th class="header">JavaScript example</th>
      </tr>
    </thead>

    <tbody>
      <tr>
        <td class="table-content">`AcceptHeader`</td>
        <td class="table-content">string</td>
        <td class="table-content">The exact content of the HTTP accept headers as sent to the platform from the end user’s browser.</td>
        <td class="table-content">None, collected server-side</td>
      </tr>

      <tr>
        <td class="table-content">`JavaEnabled`</td>
        <td class="table-content">boolean</td>
        <td class="table-content">Whether or not the end user’s browser has the ability to execute Java.</td>
        <td class="table-content">`navigator.javaEnabled()`</td>
      </tr>

      <tr>
        <td class="table-content">`Language`</td>
        <td class="table-content">string (Max. length: 6 characters)</td>
        <td class="table-content">The browser language, made up of the language code and the country (e.g., “en-US”).</td>
        <td class="table-content">`navigator.language` or `navigator.userLanguage`</td>
      </tr>

      <tr>
        <td class="table-content">`ColorDepth`</td>
        <td class="table-content">integer (Allowed values: 1, 4, 8, 15, 16, 24, 30, 32, 48)</td>
        <td class="table-content">The value representing the depth of the screen’s color palette for displaying images, in bits per pixel.</td>
        <td class="table-content">`window.screen.colorDepth`</td>
      </tr>

      <tr>
        <td class="table-content">`ScreenHeight`</td>
        <td class="table-content">integer (Max. length: 6 characters)</td>
        <td class="table-content">The height of the screen in pixels.</td>
        <td class="table-content">`window.screen.height`</td>
      </tr>

      <tr>
        <td class="table-content">`ScreenWidth`</td>
        <td class="table-content">integer (Max. length: 6 characters)</td>
        <td class="table-content">The width of the screen in pixels.</td>
        <td class="table-content">`window.screen.width`</td>
      </tr>

      <tr>
        <td class="table-content">`TimeZoneOffset`</td>
        <td class="table-content">integer</td>
        <td class="table-content">The difference in minutes between the browser’s timezone and UTC.</td>
        <td class="table-content">`new Date().getTimezoneOffset()`</td>
      </tr>

      <tr>
        <td class="table-content">`UserAgent`</td>
        <td class="table-content">string (Max. length: 255 characters)</td>
        <td class="table-content">The exact content of the HTTP User-Agent header. Max. length: 255 characters.</td>
        <td class="table-content">`navigator.userAgent`</td>
      </tr>

      <tr>
        <td class="table-content">`JavascriptEnabled`</td>
        <td class="table-content">boolean</td>
        <td class="table-content">Whether or not the end user’s browser has the ability to execute JavaScript.</td>
        <td class="table-content">`true`</td>
      </tr>
    </tbody>
  </table>
</Accordion>

## 7. Request the payment (Direct Card PayIn)

Now that you have a `CardId`, you can request the payment to the wallet using the <a href="/api-reference/direct-card-payins">Direct Card PayIn</a> object.

<Note>
  **Note - Recurring card payments and preauthorizations require other endpoints**

  The Direct Card PayIn object represents a one-time payment with a registered card.

  For subscriptions and other recurring card payments, use the <a href="/api-reference/recurring-card-payins">Recurring PayIn Registration</a> object.

  To reserve funds on a card for capture later, use the <a href="/api-reference/preauthorizations">Preauthorization</a> and <a href="/api-reference/deposit-preauthorizations">Deposit Preauthorization</a> objects.
</Note>

Create the pay-in request using:

* The `CardId`
* The IP address and browser information
* The `Id` of the User as the `AuthorId`
* The `Id` of the user’s Wallet as the `CreditedWalletId`

In your integration, when you make the payment request you also need to:

* Be ready to handle 3DS authentication (Step 6)
* Specify the page to which the user will be returned after payment (Step 7)

Read these steps before continuing with the payment request:

> [**POST** /v2.01/\{ClientId}/payins/card/direct](/api-reference/direct-card-payins/create-direct-card-payin)

<CodeGroup>
  ```json REST   theme={null}
  {
      "Tag": "Created using Mangopay API Postman Collection",
      "AuthorId": "user_m_01JHQRCND66XP99SVBXQRP54MF",
      "DebitedFunds": {
          "Currency": "EUR",
          "Amount": 57842
      },
      "Fees": {
          "Currency": "EUR",
          "Amount": 8877
      },
      "CreditedWalletId": "wlt_m_01JHQRD0WZ1QWKNAMQF93E5M15",
      "SecureMode": "DEFAULT",
      "CardId": "card_m_iWdaSvYItChPyoia",
      "SecureModeReturnURL": "http://example.com",
      "StatementDescriptor": "Mangopay",
      "BrowserInfo": {
          "AcceptHeader": "text/html, application/xhtml+xml, application/xml;q=0.9, /;q=0.8",
          "JavaEnabled": true,
          "Language": "en",
          "ColorDepth": 4,
          "ScreenHeight": 1800,
          "ScreenWidth": 400,
          "TimeZoneOffset": 60,
          "UserAgent": "Mozilla/5.0 (iPhone; CPU iPhone OS 13_6_1 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Mobile/15E148",
          "JavascriptEnabled": true
      },
      "IpAddress": "658e:1b88:7f7a:a60b:32af:0b7f:56e1:2e9a",
      "Billing": {
          "FirstName": "Alex",
          "LastName": "Smith",
          "Address": {
              "AddressLine1": "6 rue de la Cité",
              "AddressLine2": "Appartement 3",
              "City": "Paris",
              "Region": "Île-de-France",
              "PostalCode": "75001",
              "Country": "FR"
          }
      },
      "Shipping": {
          "FirstName": "Alex",
          "LastName": "Smith",
          "Address": {
              "AddressLine1": "6 rue de la Cité",
              "AddressLine2": "Appartement 3",
              "City": "Paris",
              "Region": "Île-de-France",
              "PostalCode": "75001",
              "Country": "FR"
          }
      }
  }  
  ```

  ```php PHP theme={null}
  <?php 

  require_once 'vendor/autoload.php';

  use MangoPay\MangoPayApi;
  use MangoPay\Libraries\ResponseException as MGPResponseException;
  use MangoPay\Libraries\Exception as MGPException;

  $api = new MangoPayApi();

  $api->Config->ClientId = 'your-client-id';
  $api->Config->ClientPassword = 'your-api-key';
  $api->Config->TemporaryFolder = 'tmp/';

  try {
      $payIn = new \MangoPay\PayIn();
      $payIn->Tag = "Created using Mangopay PHP SDK";
      $payIn->CreditedWalletId = "148968396";
      $payIn->PaymentType = "CARD";
      $payIn->AuthorId = "146476890";
      
      $payIn->DebitedFunds = new \MangoPay\Money();
      $payIn->DebitedFunds->Amount = 1000;
      $payIn->DebitedFunds->Currency = "EUR";
      
      $payIn->Fees = new \MangoPay\Money();
      $payIn->Fees->Amount = 10;
      $payIn->Fees->Currency = "EUR";
      
      $payIn->PaymentDetails = new \MangoPay\PayInPaymentDetailsCard();
      $payIn->PaymentDetails->CardId = "169687329";
      $payIn->PaymentDetails->StatementDescriptor = "Mangopay";
      $payIn->PaymentDetails->IpAddress = "2001:0620:0000:0000:0211:24FF:FE80:C12C";
      
      $payIn->PaymentDetails->BrowserInfo = new \MangoPay\BrowserInfo();
      $payIn->PaymentDetails->BrowserInfo->AcceptHeader = "text/html, application/xhtml+xml, application/xml;q=0.9, /;q=0.8";
      $payIn->PaymentDetails->BrowserInfo->JavaEnabled = true;
      $payIn->PaymentDetails->BrowserInfo->Language = "FR-FR";
      $payIn->PaymentDetails->BrowserInfo->ColorDepth = 4;
      $payIn->PaymentDetails->BrowserInfo->ScreenHeight = 1800;
      $payIn->PaymentDetails->BrowserInfo->ScreenWidth = 400;
      $payIn->PaymentDetails->BrowserInfo->TimeZoneOffset = 60;
      $payIn->PaymentDetails->BrowserInfo->UserAgent = "Mozilla/5.0 (iPhone; CPU iPhone OS 13_6_1 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Mobile/15E148";
      $payIn->PaymentDetails->BrowserInfo->JavascriptEnabled = true;
      
      $payIn->ExecutionDetails = new \MangoPay\PayInExecutionDetailsDirect();
      $payIn->ExecutionDetails->SecureModeReturnURL = "http://example.com";
      $payIn->ExecutionDetails->Culture = 'FR';
      
      $response = $api->PayIns->Create($payIn);

      print_r($response);
  } catch(MGPResponseException $e) {
      print_r($e);
  } catch(MGPException $e) {
      print_r($e);
  }  
  ```

  ```javascript NodeJS   theme={null}
  const mangopayInstance = require('mangopay4-nodejs-sdk')
  const mangopay = new mangopayInstance({
    clientId: 'your-client-id',
    clientApiKey: 'your-api-key',
  })

  let myDirectCardPayIn = {
    PaymentType: 'CARD',
    ExecutionType: 'DIRECT',
    AuthorId: '146476890',
    Tag: 'Created with Mangopay Node.js SDK',
    CreditedUserId: '146476890',
    DebitedFunds: {
      Currency: 'EUR',
      Amount: 1000,
    },
    Fees: {
      Currency: 'EUR',
      Amount: 100,
    },
    CreditedWalletId: '148968396',
    CardId: '169687329',
    CardType: 'CB_VISA_MASTERCARD',
    SecureMode: 'DEFAULT',
    SecureModeReturnURL: 'http://example.com',
    BrowserInfo: {
      AcceptHeader:
        'text/html, application/xhtml+xml, application/xml;q=0.9, /;q=0.8',
      JavaEnabled: true,
      Language: 'FR-FR',
      ColorDepth: 4,
      ScreenHeight: 1800,
      ScreenWidth: 400,
      TimeZoneOffset: 60,
      UserAgent:
        'Mozilla/5.0 (iPhone; CPU iPhone OS 13_6_1 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Mobile/15E148',
      JavascriptEnabled: true,
    },
    IpAddress: '2d1b:f91a:075a:7fc8:0cb7:b471:cd55:017e',
    Billing: {
      FirstName: 'Alex',
      LastName: 'Smith',
      Address: {
        AddressLine1: 'Rue des plantes',
        AddressLine2: 'The Oasis',
        City: 'Paris',
        Region: 'IDF',
        PostalCode: '75000',
        Country: 'FR',
      },
    },
    Shipping: {
      FirstName: 'Alex',
      LastName: 'Smith',
      Address: {
        AddressLine1: 'Rue des plantes',
        AddressLine2: 'The Oasis',
        City: 'Paris',
        Region: 'IDF',
        PostalCode: '75000',
        Country: 'FR',
      },
    },
    StatementDescriptor: 'Nov2023',
  }

  const createDirectCardPayIn = async (payin) => {
    return await mangopay.PayIns.create(payin)
      .then((response) => {
        console.info(response)
        return response
      })
      .catch((err) => {
        console.log(err)
        return false
      })
  }

  createDirectCardPayIn(myDirectCardPayIn)  
  ```

  ```ruby Ruby   theme={null}
  require 'mangopay'

  MangoPay.configure do |client|
      client.preproduction = true
      client.client_id = 'your-client-id'
      client.client_apiKey = 'your-api-key'
      client.log_file = File.join(Dir.pwd, 'mangopay.log')
  end

  def createDirectCardPayIn(payInObject)
      begin
          response = MangoPay::PayIn::Card::Direct.create(payInObject)
          puts response
          return response
      rescue MangoPay::ResponseError => error
          puts "Failed to create pay-in: #{error.message}"
          puts "Error details: #{error.details}"
          return false
      end
  end

  myPayIn = {
    AuthorId: '192822811',
    Tag: 'Created with Mangopay Ruby SDK',
    CreditedUserId: '192822811',
    DebitedFunds: {
      Currency: 'EUR',
      Amount: 1200,
    },
    Fees: {
      Currency: 'EUR',
      Amount: 100,
    },
    CreditedWalletId: '192822814',
    CardId: '192822826',
    CardType: 'CB_VISA_MASTERCARD',
    SecureMode: 'DEFAULT',
    SecureModeReturnURL: 'http://example.com',
    BrowserInfo: {
      AcceptHeader:
        'text/html, application/xhtml+xml, application/xml;q=0.9, /;q=0.8',
      JavaEnabled: true,
      Language: 'FR-FR',
      ColorDepth: 4,
      ScreenHeight: 1800,
      ScreenWidth: 400,
      TimeZoneOffset: 60,
      UserAgent:
        'Mozilla/5.0 (iPhone; CPU iPhone OS 13_6_1 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Mobile/15E148',
      JavascriptEnabled: true,
    },
    IpAddress: '2d1b:f91a:075a:7fc8:0cb7:b471:cd55:017e',
    Billing: {
      FirstName: 'Alex',
      LastName: 'Smith',
      Address: {
        AddressLine1: 'Rue des plantes',
        AddressLine2: 'The Oasis',
        City: 'Paris',
        Region: 'IDF',
        PostalCode: '75000',
        Country: 'FR',
      },
    },
    Shipping: {
      FirstName: 'Alex',
      LastName: 'Smith',
      Address: {
        AddressLine1: 'Rue des plantes',
        AddressLine2: 'The Oasis',
        City: 'Paris',
        Region: 'IDF',
        PostalCode: '75000',
        Country: 'FR',
      },
    },
    StatementDescriptor: 'Nov2023',
  }

  createDirectCardPayIn(myPayIn)  
  ```

  ```python Python   theme={null}
  from pprint import pprint
  import mangopay

  mangopay.client_id='your-client-id'
  mangopay.apikey='your-api-key'

  from mangopay.api import APIRequest
  handler = APIRequest(sandbox=True)

  from mangopay.resources import NaturalUser, LegalUser, Wallet, Card, DirectPayIn
  from mangopay.utils import Money, BrowserInfo

  legal_user = LegalUser.get('211918806')
  legal_user_wallet = Wallet.get('214564765')

  natural_user = NaturalUser.get('213753890')
  natural_user_card= Card.get('213944219')

  direct_payin = DirectPayIn(
      author = natural_user,
      debited_funds = Money(amount=1000, currency='EUR'),
      fees = Money(amount=1, currency='EUR'),
      credited_wallet_id = legal_user_wallet.id,
      card_id = natural_user_card,
      secure_mode = 'DEFAULT',
      secure_mode_return_url = "http://example.com",
      tag = 'Created with Mangopay Python SDK',
      browser_info = BrowserInfo(
          user_agent = 'Mozilla/5.0 (iPhone; CPU iPhone OS 13_6_1 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Mobile/15E148',
          screen_width = 375,
          screen_height = 667,
          color_depth = 32,
          language = 'EN',
          accept_header = 'application/json,text/javascript,*/*;q=0.01<',
          timezone_offset = '-120',
          java_enabled = True,
          javascript_enabled = True
      ),
      ip_address = '159.180.248.187',
  )

  create_direct_payin = direct_payin.save()

  pprint(create_direct_payin)  
  ```
</CodeGroup>

## 8. Redirect the user to 3DS protocol (if required)

Redirect the user to the `SecureModeRedirectURL` value to complete strong customer authentication with the <a href="/guides/payment-methods/card/3ds">3DS protocol</a>, unless it is `null`. If `SecureModeRedirectURL` is `null`, this means that 3DS is not required and no redirection is needed.

You can also use the `SecureModeNeeded` boolean to determine this redirection behavior.

In Sandbox, follow the link returned in the `SecureModeRedirectURL` to access the authentication simulator.

## 9. Return the user after payment

After the payment, whether it includes 3DS or not and whatever the outcome, the end user is returned to the `SecureModeReturnURL` which you defined.

The Mangopay API returns your `SecureModeReturnURL` with the `Id` of the pay-in transaction attached as a query parameter in the following format:

> https<span>://www</span>.example.com?transactionId=`Id`

Mangopay updates the `Status` of the pay-in to indicate a successful or failed payment depending on the outcome of the end user's authentication.

You should  set up [hook notifications](/webhooks) for the following [event types](/webhooks/event-types) to be notified of the outcome:

* PAYIN\_NORMAL\_SUCCEEDED
* PAYIN\_NORMAL\_FAILED

Once your system receives a webhook, call the <a href="/api-reference/direct-card-payins/view-payin-direct-card">GET View a PayIn</a> endpoint (using its `Id`) to confirm the result of the transaction. This allows you to customize the end user’s experience after the payment.

If the pay-in is successful, the card's `Validity` parameter is set to `Valid` and it can be used for other payments at a later stage.

## 10. Deactivate the card (if required)

<Warning>
  **Warning - End user's approval needed to save card details**

  Under no circumstances should card information be kept without the end user's approval.

  If you don’t have the end user’s approval, you need to deactivate the card systematically after use in your implementation.
</Warning>

Once the pay-in is successful, if the end user did not request to save their card for later, set the card’s `Active` parameter to false to deactivate the card. This action is irreversible.

<Note>
  **Note - The card can be registered multiple times**

  Deactivating the card will not prevent the end user from making a payment with the same card in future. You will need to go through the card registration process again.
</Note>

> [**PUT** /v2.01/\{ClientId}/cards/\{CardId}](/api-reference/cards/deactivate-edit-card)

<CodeGroup>
  ```json REST   theme={null}
  {
      "Active": false
  }  
  ```

  ```php PHP theme={null}
  <?php 

  require_once 'vendor/autoload.php';

  use MangoPay\MangoPayApi;
  use MangoPay\Libraries\ResponseException as MGPResponseException;
  use MangoPay\Libraries\Exception as MGPException;

  $api = new MangoPayApi();

  $api->Config->ClientId = 'your-client-id';
  $api->Config->ClientPassword = 'your-api-key';
  $api->Config->TemporaryFolder = 'tmp/';

  try {
      $card = new \MangoPay\Card();

      $card->Id = '198660883';
      $card->Active = false;

      $response = $api->Cards->Update($card);

      print_r($response);
  } catch(MGPResponseException $e) {
      print_r($e);
  } catch(MGPException $e) {
      print_r($e);
  }  
  ```

  ```javascript NodeJS   theme={null}
  const mangopayInstance = require('mangopay4-nodejs-sdk')
  const mangopay = new mangopayInstance({
      clientId: 'your-client-id',
      clientApiKey: 'your-api-key',
  })

  let myCard = {
    Id: '156285393',
    Active: false,
  }

  const deactivateCard = async (card) => {
    return await mangopay.Cards.update(card)
      .then((response) => {
        console.info(response)
        return response
      })
      .catch((err) => {
        console.log(err)
        return false
      })
  }

  deactivateCard(myCard)  
  ```

  ```ruby Ruby   theme={null}
  require 'mangopay'

  MangoPay.configure do |client|
      client.preproduction = true
      client.client_id = 'your-client-id'
      client.client_apiKey = 'your-api-key'
      client.log_file = File.join(Dir.pwd, 'mangopay.log')
  end

  def deactivateCard(cardId, cardObject)
      begin
          response = MangoPay::Card.update(cardId, cardObject)
          puts response
          return response
      rescue MangoPay::ResponseError => error
          puts "Failed to deactivate card: #{error.message}"
          puts "Error details: #{error.details}"
          return false
      end
  end

  myCard = {
      Id: '194579926',
      Active: false
  }

  deactivateCard(myCard[:Id], myCard)  
  ```

  ```python Python   theme={null}
  from pprint import pprint
  import mangopay

  mangopay.client_id='your-client-id'
  mangopay.apikey='your-api-key'

  from mangopay.api import APIRequest
  handler = APIRequest(sandbox=True)

  from mangopay.resources import Card

  user_card = Card(
      id = '213601128',
      active = False
  )

  deactive_card = user_card.save()

  pprint(deactive_card)
    
  ```
</CodeGroup>

## Related resources

<CardGroup col={2}>
  <Card title="Guide" href="/guides/payment-methods/card/3ds">Learn more about 3DS</Card>

  <Card title="Guide" href="/guides/payment-methods/card/recurring">Learn more about Recurring card payments</Card>

  <Card title="Guide" href="/guides/payment-methods/card/preauthorization">Learn more about Preauthorized card payments</Card>
</CardGroup>
