> ## Documentation Index
> Fetch the complete documentation index at: https://integration.wpay.com.au/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 a paid feature. It isn't enabled by default, and is enabled manually for each merchant account. To request access and pricing, contact your account manager.

Detokenization returns the card number and expiration date of a card stored in the vault. The platform 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://integration.wpay.com.au/guides/features/vault-forwarding/forward.md) instead. Vault Forwarding sends the card data to the endpoint directly, so it never reaches your systems.

## Prerequisites

Detokenization is enabled manually for each merchant account. To get started, contact your account manager and provide the following:

* **Agreement:** A contract that includes the detokenization fee. Each successful detokenization request is charged.
* **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. See [Create a key pair](#create-a-key-pair).

You also agree on a key ID with your account manager. The platform sets it as the `kid` header of every encrypted payload, so you can select the matching private key.

The platform records an expiry date for your AoC and for your public key. After either date passes, requests fail with a `403` error. Send your account manager 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.

## Create a key pair

Create the key pair in the environment that your AoC covers. The private key must never leave that environment.

This key pair is separate from your API key pair. API keys use elliptic curve keys, but the detokenization key must be an RSA key.

Generate a 3072-bit RSA private key:

```bash theme={"theme":{"light":"github-light","dark":"github-dark-default"}}
openssl genpkey -algorithm RSA -pkeyopt rsa_keygen_bits:3072 -out detokenization_private_key.pem
```

Export the matching public key:

```bash theme={"theme":{"light":"github-light","dark":"github-dark-default"}}
openssl pkey -in detokenization_private_key.pem -pubout -out detokenization_public_key.pem
```

Check that the public key is an RSA key of at least 2048 bits:

```bash theme={"theme":{"light":"github-light","dark":"github-dark-default"}}
openssl rsa -pubin -in detokenization_public_key.pem -noout -text | head -1
```

The output must be `Public-Key: (3072 bit)`, or a size of 2048 bits or more. If the output is `Not an RSA key`, create a new RSA key pair.

You can also create the key pair in a hardware security module (HSM) or a key management service (KMS). The service must export the public key as an RSA public key in PEM format, and must decrypt with `RSA-OAEP-256`.

### Send the public key to your account manager

Send only the public key file to your account manager. Never send the private key. If you send a private key by mistake, create a new key pair.

Before the key is activated, its fingerprint is confirmed with a contact named on your AoC, on a different channel from the one that sent the key. To get the fingerprint, run:

```bash theme={"theme":{"light":"github-light","dark":"github-dark-default"}}
openssl pkey -pubin -in detokenization_public_key.pem -outform DER | openssl dgst -sha256
```

To replace a key, create a new key pair and agree a new key ID with your account manager. Keep the old private key until you decrypt every payload that uses it.

## 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://integration.wpay.com.au/guides/api/api-keys#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={"theme":{"light":"github-light","dark":"github-dark-default"}}
POST /payment-methods/{payment_method_id}/detokenization
```

```csharp C# theme={"theme":{"light":"github-light","dark":"github-dark-default"}}
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={"theme":{"light":"github-light","dark":"github-dark-default"}}
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={"theme":{"light":"github-light","dark":"github-dark-default"}}
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={"theme":{"light":"github-light","dark":"github-dark-default"}}
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={"theme":{"light":"github-light","dark":"github-dark-default"}}
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={"theme":{"light":"github-light","dark":"github-dark-default"}}
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 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={"theme":{"light":"github-light","dark":"github-dark-default"}}
{
  "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 your account manager. |

Decrypt the payload with the private key that matches your public key. Accept only the `RSA-OAEP-256` and `A256GCM` algorithms.

```js Node theme={"theme":{"light":"github-light","dark":"github-dark-default"}}
// 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={"theme":{"light":"github-light","dark":"github-dark-default"}}
# 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={"theme":{"light":"github-light","dark":"github-dark-default"}}
{
  "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

The platform limits detokenization requests for each merchant account over a moving 60-second window. The default limit is 300 requests in each window. A different limit can be set 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.
* **No caching:** Successful responses include a `Cache-Control: no-store` header.
* **Keep the private key in your PCI environment:** The platform 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.

## API reference

The following API endpoints relate to this guide.


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