# API Basics
source: https://developer.mastercard.com/agent-suite-for-merchants/documentation/api-basics/index.md

## Client Authentication {#client-authentication}

Warning: **Credential lifecycle:** 👉 If your sandbox keys expire after a fixed period, document that behavior here and explain how developers should rotate or regenerate credentials.

👉 Let the user know what type of authentication your service uses. Keep only the tabs that apply to your service, or leave all three if this starter is meant to support multiple authentication patterns.  

|          Authentication Protocol           |                                                                                                  Details                                                                                                   |
|--------------------------------------------|------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
| [OAuth 1.0a](https://oauth.net/core/1.0a/) | Mastercard uses OAuth 1.0a with a body hash extension for authenticating API clients. OAuth 1.0a guarantees the integrity and authenticity of incoming API calls and supports non-repudiation of requests. |

OAuth requires every request that you send to Mastercard to be signed with an RSA private key. A private-public RSA key pair must be generated consisting of:  

1. A **private key** for signing OAuth API requests. Store the private key in a password-protected or hardware keystore. It encrypts the signature base string hash, which the server decrypts using the public key.  
2. A **public key** shared with Mastercard during project setup through a certificate signing request (CSR) or API key generator. Mastercard uses the public key to verify the OAuth signature on every API call.

* Requests with a body must be signed using the [Google Request Body Hash](https://datatracker.ietf.org/doc/id/draft-eaton-oauth-bodyhash-00.html) extension for OAuth.
* OAuth keys are created during project setup on Mastercard Developers, and additional keys can be added later from the project dashboard.

Tip: Do you want to learn more about the authentication scheme Mastercard uses? If so, read our [Using OAuth 1.0a to Access Mastercard APIs](https://developer.mastercard.com/platform/documentation/authentication/using-oauth-1a-to-access-mastercard-apis/) guide. 👉 Keep this template only if your service actually uses OAuth 2.0. Update it with your real token flow, scope requirements, DPoP expectations, and any service-specific client-registration or authorization-server details.

|      Authentication Protocol      |                                                                                                                                      Details                                                                                                                                      |
|-----------------------------------|-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
| [OAuth 2.0](https://oauth.net/2/) | Mastercard uses [OAuth 2.0 Authorization](https://datatracker.ietf.org/doc/html/rfc6749) with the [Client Credentials Grant](https://datatracker.ietf.org/doc/html/rfc6749#section-4.4), using the FAPI 2.0 security profile (strong client authentication + DPoP token binding). |

OAuth 2.0 (client credentials) requires your application to request an access token from the authorization server, and call APIs using that access token with DPoP token binding.

Your application needs two sets of key material:   

1. An **authentication private key** (from Mastercard Developers) used to sign the client assertion (`private_key_jwt`) for token requests.   
2. A **DPoP key pair** generated and stored by your application, used to sign DPoP proofs (per token request and per API call).

* Token requests include a signed client assertion (`private_key_jwt`) and a DPoP proof.
* API calls send `Authorization: DPoP <access_token>` and a fresh DPoP proof per request (including `htm/htu` and `ath`).
* Nonce handling: if you receive `use_dpop_nonce`, retry with the `DPoP-Nonce` value as the `nonce` claim in the next DPoP proof.

Tip: Do you want to learn more about the authentication scheme Mastercard uses? For implementation details and examples, read our [Using OAuth 2.0 to Access Mastercard APIs](https://developer.mastercard.com/platform/oauth2/documentation/authentication/using-oauth-2-to-access-mastercard-apis/) guide. 👉 Keep this template only if your service uses mutual TLS. Update the certificate lifecycle, environment URLs, onboarding instructions, and any trust-store or CSR requirements so they reflect your real implementation.

|                Authentication Protocol                |                                                                                                   Details                                                                                                   |
|-------------------------------------------------------|-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
| [mTLS](https://datatracker.ietf.org/doc/html/rfc5246) | Mastercard APIs using mTLS authentication require two-way TLS certificate exchange between the API Client and Mastercard Server. It uses digital certificates signed using PKI to authenticate API clients. |

mTLS is a mutual TLS handshake protocol used to establish a secure connection between client and server. In mTLS authentication, your client application sends a request for a protected resource to a Mastercard server. The Mastercard server then presents a server certificate, which the client verifies.
Your application then presents a corresponding client certificate back to Mastercard for verification. After key exchange and cipher negotiation complete, Mastercard returns the protected resource in response.

There are two different types of mTLS client certificates, depending on the stage of your project:

1. Sandbox or pre-production mTLS certificates, which give access to a non-production environment for validation and onboarding.   
2. Production mTLS certificates, which allow an application to access the live production environment.

\*Domain or server URL may vary depending on the API. Check the API reference section of the service documentation for the correct server URL.
Tip: Do you want to learn more about the mTLS authentication scheme Mastercard uses? For that, read our [Using mTLS to Access Mastercard APIs](https://developer.mastercard.com/platform/documentation/authentication/using-mtls-to-access-mastercard-apis/) guide.

## Transport Encryption {#transport-encryption}

All connections to Mastercard are secured using [TLS/SSL](https://en.wikipedia.org/wiki/Transport_Layer_Security). Data is protected by default when transmitted across networks. Mastercard services may additionally use end-to-end payload encryption for sensitive data such as personally identifiable information (PII).
Note: Visit [Securing Sensitive Data Using Payload Encryption](https://developer.mastercard.com/platform/documentation/security-and-authentication/securing-sensitive-data-using-payload-encryption/) to learn more about Mastercard encryption methods.

### Payload Encryption {#payload-encryption}

👉 Replace this section with the payload encryption pattern used by your service. If the service uses JWE, the template below is usually sufficient. If it uses field-level encryption or no payload encryption, update the explanation and examples accordingly.

|                         Encryption Protocol                          |                                                                                                                                         Details                                                                                                                                         |
|----------------------------------------------------------------------|-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
| [JSON Web Encryption](https://datatracker.ietf.org/doc/html/rfc7516) | JSON Web Encryption (JWE) represents encrypted content using JSON-based data structures and base64url encoding. Mastercard commonly uses JWE compact serialization for encrypting sensitive data and may support field-level or full-body payload encryption depending on the endpoint. |

* Use field-level encryption when only a subset of the payload contains sensitive data.
* Use full-body encryption when the entire request or response payload is sensitive.

Tip: Do you want to learn more about the encryption scheme Mastercard uses? If so, visit our [JWE Encryption Guide](https://developer.mastercard.com/platform/documentation/authentication/securing-sensitive-data-using-payload-encryption/#jwe-encryption).

## How to Consume the API? {#how-to-consume-the-api}

### Generating your own {Service Name} API client {#generating-your-own-service-name-api-client}

Create customizable API clients from the {Service Name} API specification and let Mastercard open-source client libraries handle the authentication for you. This approach offers more flexibility and is strongly recommended.

To learn how to generate your own client, please follow our guide: [Generating and Configuring a Mastercard API Client](https://developer.mastercard.com/platform/documentation/security-and-authentication/generating-and-configuring-a-mastercard-api-client/) using:

* The following {Service Name} OpenAPI specification file:
  [oauth-petstore.yaml](https://static.developer.mastercard.com/content/agent-suite-for-merchants/uploads/oauth-petstore.yaml) (68KB)   

* An API client library generated using [OpenAPI Generator](https://openapi-generator.tech/docs/installation) and the development framework of your choice (see also: [Generators List](https://openapi-generator.tech/docs/generators/)):

  * Sh

  ```sh
  openapi-generator-cli generate -g java -i petstore.yaml -o api_client
  ```

  <br />

* The following payload encryption code configurations are available.

  * Java
  * C#
  * JavaScript
  * Python
  * Go

  ```java
  // Used for adoption endpoints
  @Bean
  public EncryptionConfig encryptionConfigForAdoptions() throws EncryptionException, GeneralSecurityException, IOException {
    checkProperties();
    Certificate encryptionCertificate = EncryptionUtils.loadEncryptionCertificate(encryptionCertificateFilePath);
    PrivateKey decryptionKey = EncryptionUtils.loadDecryptionKey(decryptionKeyFilePath, decryptionKeyAlias, decryptionKeyPassword);

    return JweConfigBuilder.aJweEncryptionConfig()
      .withEncryptionCertificate(encryptionCertificate)
      .withDecryptionKey(decryptionKey)
      .withEncryptionPath("$.owner","$.encryptedOwner")
      .withDecryptionPath("$.encryptedOwner.encryptedData","$.owner")
      .withDecryptionPath("$.adoption.encryptedOwner.encryptedData","$.adoption.owner")
      .build();
  }

  // Used for employees and payment endpoints
  @Bean
  public EncryptionConfig fullBodyEncryptionConfig() throws EncryptionException, GeneralSecurityException, IOException {
    Certificate encryptionCertificate = EncryptionUtils.loadEncryptionCertificate(encryptionCertificateFilePath);
    PrivateKey decryptionKey = EncryptionUtils.loadDecryptionKey(decryptionKeyFilePath, decryptionKeyAlias, decryptionKeyPassword);

    return JweConfigBuilder.aJweEncryptionConfig()
      .withEncryptionCertificate(encryptionCertificate)
      .withEncryptionPath("$", "$")
      .withDecryptionPath("$", "$")
      .withDecryptionKey(decryptionKey)
      .build();
  }
  ```

  ```csharp
    // Used for adoption endpoints
    public JweConfig EncryptionConfigForAdoptions() 
    {
      var encryptionCertificate = EncryptionUtils.LoadEncryptionCertificate(encryptionCertificateFilePath);
      var decryptionKey = EncryptionUtils.LoadDecryptionKey(decryptionKeyFilePath, decryptionKeyPassword);

      return JweConfigBuilder.AJweEncryptionConfig()
        .WithEncryptionCertificate(encryptionCertificate)
        .WithDecryptionKey(decryptionKey)
        .WithEncryptionPath("$.owner", "$.encryptedOwner")
        .WithDecryptionPath("$.encryptedOwner.encryptedData", "$.owner")
        .WithDecryptionPath("$.adoption.encryptedOwner.encryptedData", "$.adoption.owner")
        .Build();
    }

    // Used for employees and payment endpoints
    public JweConfig FullBodyEncryptionConfig() 
    {
      var encryptionCertificate = EncryptionUtils.LoadEncryptionCertificate(encryptionCertificateFilePath);
      var decryptionKey = EncryptionUtils.LoadDecryptionKey(decryptionKeyFilePath, decryptionKeyPassword);

      return JweConfigBuilder.AJweEncryptionConfig()
        .WithEncryptionCertificate(encryptionCertificate)
        .WithDecryptionKey(decryptionKey)
        .WithEncryptionPath("$", "$")
        .WithDecryptionPath("$", "$")
        .Build();
    }
  ```

  ```javascript
    // Used for adoption endpoints
  function createEncryptionConfigForAdoptions() {
    return {
      paths: [
        {
          path: ".*",
          toEncrypt: [{ element: "owner", obj: "encryptedOwner" }],
          toDecrypt: [
            { element: "encryptedOwner.encryptedData", obj: "owner" },
            { element: "adoption.encryptedOwner.encryptedData", obj: "adoption.owner" }
          ]
        }
      ],
      mode: "JWE",
      encryptionCertificate: "./path/to/encryptionCertificate.pem",
      privateKey: "./path/to/decryptionKey.pem"
    };
  }

  // Used for employees and payment endpoints
  function createFullBodyEncryptionConfig() {
    return {
      paths: [
        {
          path: ".*",
          toEncrypt: [{ element: "$", obj: "$" }],
          toDecrypt: [{ element: "$", obj: "$" }]
        }
      ],
      mode: "JWE",
      encryptionCertificate: "./path/to/encryptionCertificate.pem",
      privateKey: "./path/to/decryptionKey.pem"
    };
  }

  const encryptionConfigForAdoptions = createEncryptionConfigForAdoptions();
  const fullBodyEncryptionConfig = createFullBodyEncryptionConfig();
  ```

  ```python
  from client_encryption.jwe_encryption_config import JweEncryptionConfig

  # Used for adoption endpoints
  def build_encryption_config_for_adoptions():
    return JweEncryptionConfig({
      "paths": {
        ".*": {
          "toEncrypt": {"owner": "encryptedOwner"},
          "toDecrypt": {
            "encryptedOwner.encryptedData": "owner",
            "adoption.encryptedOwner.encryptedData": "adoption.owner"
          }
        }
      },
      "encryptionCertificate": "./path/to/encryptionCertificate.pem",
      "decryptionKey": "./path/to/decryptionKey.pem"
    })

  # Used for employees and payment endpoints
  def build_full_body_encryption_config():
    return JweEncryptionConfig({
      "paths": {
        ".*": {
          "toEncrypt": {"$": "$"},
          "toDecrypt": {"$": "$"}
        }
      },
      "encryptionCertificate": "./path/to/encryptionCertificate.pem",
      "decryptionKey": "./path/to/decryptionKey.pem"
    })

  encryption_config_for_adoptions = build_encryption_config_for_adoptions()
  full_body_encryption_config = build_full_body_encryption_config()
  ```

  ```go
  import "github.com/mastercard/client-encryption-go/jwe"
  import "github.com/mastercard/client-encryption-go/utils"

  // Load certs and keys
  encryptionCertificate, _ := utils.LoadEncryptionCertificate("./path/to/encryptionCertificate.pem")
  decryptionKey, _ := utils.LoadDecryptionKey("./path/to/decryptionKey.pem", "password")

  // Used for adoption endpoints
  cbAdoptions := jwe.NewJWEConfigBuilder()
  encryptionConfigForAdoptions := cbAdoptions.WithDecryptionKey(decryptionKey).
    WithCertificate(encryptionCertificate).
    WithEncryptionPath("$.owner", "$.encryptedOwner").
    WithDecryptionPath("$.encryptedOwner.encryptedData", "$.owner").
    WithDecryptionPath("$.adoption.encryptedOwner.encryptedData", "$.adoption.owner").
    Build()

  // Used for employees and payment endpoints
  cbFullBody := jwe.NewJWEConfigBuilder()
  fullBodyEncryptionConfig := cbFullBody.WithDecryptionKey(decryptionKey).
    WithCertificate(encryptionCertificate).
    WithEncryptionPath("$", "$").
    WithDecryptionPath("$", "$").
    Build()
  ```

* Configure your client using our client libraries. These libraries are available in several languages, and we recommend that you utilize these libraries to encrypt the sensitive data used by this service.

|                      |                                                            ![Java](https://static.developer.mastercard.com/content/agent-suite-for-merchants/uploads/java.svg)                                                            |                                                    ![C#](https://static.developer.mastercard.com/content/agent-suite-for-merchants/uploads/csharp.svg)                                                    |                                      ![Python](https://static.developer.mastercard.com/content/agent-suite-for-merchants/uploads/python.svg)                                      |                                      ![Node.js](https://static.developer.mastercard.com/content/agent-suite-for-merchants/uploads/nodejs.svg)                                      |
|----------------------|---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
| **Download/install** | [![Java version](https://img.shields.io/maven-central/v/com.mastercard.developer/client-encryption.svg?style=flat&color=f99f1c&label=)](https://central.sonatype.com/artifact/com.mastercard.developer/client-encryption) | [![C# version](https://img.shields.io/nuget/v/Mastercard.Developer.ClientEncryption.Core.svg?style=flat&color=f99f1c&label=)](https://www.nuget.org/packages/Mastercard.Developer.ClientEncryption.Core/) | [![Python version](https://img.shields.io/pypi/v/mastercard-client-encryption.svg?style=flat&color=f99f1c&label=)](https://pypi.org/project/mastercard-client-encryption/)        | [![Node.js version](https://img.shields.io/npm/v/mastercard-client-encryption.svg?style=flat&color=f99f1c&label=)](https://www.npmjs.com/package/mastercard-client-encryption)     |
| **View on GitHub**   | [![Java GitHub stars](https://img.shields.io/github/stars/Mastercard/client-encryption-java.svg?label=&style=social)](https://github.com/Mastercard/client-encryption-java)                                               | [![C# GitHub stars](https://img.shields.io/github/stars/Mastercard/client-encryption-csharp.svg?label=&style=social)](https://github.com/Mastercard/client-encryption-csharp)                             | [![Python GitHub stars](https://img.shields.io/github/stars/Mastercard/client-encryption-python.svg?label=&style=social)](https://github.com/Mastercard/client-encryption-python) | [![Node.js GitHub stars](https://img.shields.io/github/stars/Mastercard/client-encryption-nodejs.svg?label=&style=social)](https://github.com/Mastercard/client-encryption-nodejs) |

To get started, add the package that matches your application development language to your project. You can also refer to the different README.md files for detailed how-to information.

## Environment Descriptions {#environment-descriptions}

The following table describes the three environments commonly documented for Mastercard services.

| Environment |                      Base URL                       |                                                                                                       Description                                                                                                       |
|-------------|-----------------------------------------------------|-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
| Sandbox     | `https://sandbox.api.mastercard.com/{your-service}` | The sandbox environment is an open, self-service environment where developers can validate request construction, authentication, encryption, and error handling without affecting live data.                            |
| MTF         | `https://mtf.api.mastercard.com/{your-service}`     | The MTF environment is a pre-production environment with additional onboarding requirements. Use it when your service needs more realistic testing, controlled datasets, or certification before production enablement. |
| Production  | `https://api.mastercard.com/{your-service}`         | The production environment is the live environment where the API interacts with real users and data. Production access is usually requested from the project dashboard after onboarding requirements are complete.      |

Note: **Environment-specific auth and encryption:** In most Mastercard integrations, authentication and payload encryption work the same way across Sandbox, MTF, and Production. The main difference is the base URL and the credential set assigned to each environment.

## Next Steps {#next-steps}

Now that you have an understanding of the service authentication and encryption model, proceed to the [Use Cases](https://developer.mastercard.com/agent-suite-for-merchants/documentation/use-cases/index.md) section to see how the sample lifecycle flows map to create, retrieve, query, update, and delete operations.
