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

# Detokenize a card

> Retrieve the card number and expiration date of a vaulted card, encrypted to your own public key, for use in your PCI-compliant environment.

> [!NOTE]
>
> Detokenization is in early access and available to selected merchant accounts. To request access, contact your Gr4vy account manager.

Detokenization returns the card number and expiration date of a card stored in the Gr4vy vault. Gr4vy encrypts the card details to a public key that you provide. Only a system that holds the matching private key can read them.

Use detokenization when your own PCI-compliant systems need the card details of a stored card. If you only need to send card data to a third-party endpoint, use [Vault Forwarding](https://docs.gr4vy.com/guides/features/vault-forwarding/forward.md) instead. Vault Forwarding sends the card data to the endpoint directly, so it never reaches your systems.

## Prerequisites

Gr4vy enables detokenization for each merchant account. To get started, contact your Gr4vy account manager and provide the following:

* **Attestation of Compliance:** A current PCI DSS Attestation of Compliance (AoC) for the environment that decrypts the card data.
* **Public key:** An RSA public key in PEM format. The key must be at least 2048 bits, and 3072 bits is recommended. Elliptic curve (EC) keys aren't supported.

You and Gr4vy also agree on a key ID. Gr4vy sets it as the `kid` header of every encrypted payload, so you can select the matching private key.

Gr4vy records an expiry date for your AoC and for your public key. After either date passes, requests fail with a `403` error. Send Gr4vy a renewed AoC or a new public key before the current one expires. You can't upload or replace the public key through the API.

## Grant access to an API key

The endpoint requires the `payment-methods.detokenization.read` scope. Assign the **Detokenization** role to the API key that calls it. This role grants that scope and nothing else. For more information, see [The Detokenization role](https://docs.gr4vy.com/guides/api/api-keys.md#the-detokenization-role).

Only API keys can detokenize a card. Requests from a dashboard session are refused, even for an Administrator.

## Request

Send a `POST` request with no body. Set the `X-Gr4vy-Merchant-Account-Id` header to the merchant account that stores the payment method.

```http theme={"system"}
POST /payment-methods/{payment_method_id}/detokenization
```

```csharp C# theme={"system"}
using Gr4vy;

var sdk = new Gr4vySDK(
    id: "example",
    server: SDKConfig.Server.Sandbox,
    bearerAuthSource: Auth.WithToken(privateKey),
    merchantAccountId: "default"
);

var res = await sdk.PaymentMethods.DetokenizeAsync(
    paymentMethodId: "ef9496d8-53a5-4aad-8ca2-00eb68334389"
);

// handle response
```

```go Go theme={"system"}
package main

import (
	"context"
	"os"
	gr4vygo "github.com/gr4vy/gr4vy-go"
	"log"
)

func main() {
    ctx := context.Background()

    s := gr4vygo.New(
        gr4vygo.WithMerchantAccountID("default"),
        gr4vygo.WithSecurity(os.Getenv("GR4VY_BEARER_AUTH")),
    )

    res, err := s.PaymentMethods.Detokenize(ctx, "ef9496d8-53a5-4aad-8ca2-00eb68334389", nil)
    if err != nil {
        log.Fatal(err)
    }
    if res != nil {
        // handle response
    }
}
```

```java Java theme={"system"}
package hello.world;

import com.gr4vy.sdk.Gr4vy;
import com.gr4vy.sdk.models.operations.DetokenizePaymentMethodResponse;
import java.lang.Exception;

public class Application {

    public static void main(String[] args) throws Exception {

        Gr4vy sdk = Gr4vy.builder()
                .merchantAccountId("default")
                .bearerAuth(System.getenv().getOrDefault("BEARER_AUTH", ""))
            .build();

        DetokenizePaymentMethodResponse res = sdk.paymentMethods().detokenize()
                .paymentMethodId("ef9496d8-53a5-4aad-8ca2-00eb68334389")
                .call();

        if (res.detokenization().isPresent()) {
            System.out.println(res.detokenization().get());
        }
    }
}
```

```php PHP theme={"system"}
declare(strict_types=1);

require 'vendor/autoload.php';

use Gr4vy;
use Gr4vy\Auth;

$privateKey = file_get_contents('./private_key.pem');

$sdk = Gr4vy\SDK::builder()
    ->setId('example')
    ->setServer('sandbox')
    ->setSecuritySource(Auth::withToken($privateKey))
    ->setMerchantAccountId('default')
    ->build();

$response = $sdk->paymentMethods->detokenize(
    paymentMethodId: 'ef9496d8-53a5-4aad-8ca2-00eb68334389'
);

if ($response->detokenization !== null) {
    // handle response
}
```

```python Python theme={"system"}
from gr4vy import Gr4vy, auth

with Gr4vy(
    id="example",
    server="sandbox",
    merchant_account_id="default",
    bearer_auth=auth.with_token(open("./private_key.pem").read())
) as g_client:
    res = g_client.payment_methods.detokenize(
        payment_method_id="ef9496d8-53a5-4aad-8ca2-00eb68334389"
    )
    print(res)
```

```ts TypeScript theme={"system"}
import { Gr4vy, withToken } from "@gr4vy/sdk";
import fs from "fs";

const gr4vy = new Gr4vy({
    id: "example",
    server: "sandbox",
    merchantAccountId: "default",
    bearerAuth: withToken({
      privateKey: fs.readFileSync("private_key.pem", "utf8"),
    }),
});

const result = await gr4vy.paymentMethods.detokenize(
    "ef9496d8-53a5-4aad-8ca2-00eb68334389"
);

console.log(result);
```

The private key in these examples is the key of your Gr4vy API key pair, which signs the request. It isn't the private key that decrypts the payload.

## Response

A successful request returns the card details as an encrypted payload.

```json theme={"system"}
{
  "type": "payment-method-detokenization",
  "encrypted_payload": "eyJhbGciOiJSU0EtT0FFUC0yNTYiLCJlbmMiOi..."
}
```

| Field | Description |
| - | - |
| `type` | Always `payment-method-detokenization`. |
| `encrypted_payload` | The card details, encrypted to your public key as a compact JSON Web Encryption (JWE) string. |

## Decrypt the payload

The protected header of the JWE contains these values.

| Header | Value |
| - | - |
| `alg` | `RSA-OAEP-256`. |
| `enc` | `A256GCM`. |
| `kid` | The key ID that you agreed with Gr4vy. |
| `iat` | The time Gr4vy encrypted the payload, as a UNIX timestamp in seconds. |

Decrypt the payload with the private key that matches your public key. Accept only the `RSA-OAEP-256` and `A256GCM` algorithms. The `iat` header isn't a registered JWE header, so some libraries reject it unless you allow it.

```js Node theme={"system"}
// Uses the jose package: npm install jose
import { compactDecrypt, importPKCS8 } from "jose";
import fs from "fs";

const privateKey = await importPKCS8(
  fs.readFileSync("detokenization_private_key.pem", "utf8"),
  "RSA-OAEP-256",
);

const { plaintext, protectedHeader } = await compactDecrypt(
  result.encryptedPayload,
  privateKey,
  {
    keyManagementAlgorithms: ["RSA-OAEP-256"],
    contentEncryptionAlgorithms: ["A256GCM"],
  },
);

const payload = JSON.parse(new TextDecoder().decode(plaintext));
```

```python Python theme={"system"}
# Uses the jwcrypto package: pip install jwcrypto
import json

from jwcrypto import jwe, jwk

with open("detokenization_private_key.pem", "rb") as f:
    private_key = jwk.JWK.from_pem(f.read())

token = jwe.JWE(algs=["RSA-OAEP-256", "A256GCM"])
token.deserialize(res.encrypted_payload, key=private_key)

payload = json.loads(token.payload)
```

The decrypted payload is a JSON object.

```json theme={"system"}
{
  "merchant_account_id": "default",
  "payment_method_id": "ef9496d8-53a5-4aad-8ca2-00eb68334389",
  "method": "card",
  "card": {
    "number": "4111111111111111",
    "expiration_date": "12/30"
  }
}
```

| Field | Description |
| - | - |
| `merchant_account_id` | The merchant account that stores the payment method. |
| `payment_method_id` | The ID of the payment method. |
| `method` | Always `card`. |
| `card.number` | The full card number. |
| `card.expiration_date` | The expiration date of the card, in `MM/YY` format. |

Check that `merchant_account_id` and `payment_method_id` match the request before you use the card details.

## Errors

| Status | Cause |
| - | - |
| `400` | The payment method isn't a card, for example a PayPal payment method. Only card payment methods can be detokenized. |
| `401` | The API key's roles, or the scopes in the request token, don't grant `payment-methods.detokenization.read`. |
| `403` | Detokenization isn't enabled on your instance or isn't configured for the merchant account. This error also applies when your AoC or public key has expired, or when the request doesn't come from an API key. The `message` field gives the reason. |
| `404` | The payment method doesn't exist, has been deleted, has a `status` other than `succeeded`, or has no stored card details. |
| `429` | The merchant account has reached its rate limit. For more information, see [Rate limits](#rate-limits). |

## Rate limits

Gr4vy limits detokenization requests for each merchant account over a moving 60-second window. The default limit is 300 requests in each window. Gr4vy can set a different limit for your merchant account.

When you reach the limit, the API returns a `429` error with a `Retry-After` header of `60`. Wait that number of seconds before you retry.

Refused requests also count toward the limit, for example `400` and `404` errors. Requests that return a `429` error don't count.

## Security

* **One card for each request:** Each request returns one card. There is no bulk endpoint.
* **No security code:** The payload never contains the card security code (CVV).
* **No network tokens:** The payload contains the card number only, never a network token or cryptogram.
* **Keep the private key in your PCI environment:** Gr4vy only holds your public key. Store the private key in the environment that your AoC covers, and decrypt the payload only there.
* **Use a dedicated API key:** Give the Detokenization role to a key that only your PCI-compliant systems use. This lets you revoke card access without affecting your other integrations.

> [card] [API reference](https://docs.gr4vy.com/reference/payment-methods/detokenize-payment-method.md)
>
> Detokenize a payment method


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.