Card Encryption (JWE)
Encrypt card data client-side using JSON Web Encryption for maximum security
Card Encryption (JWE)
Use JSON Web Encryption (JWE) to encrypt sensitive card data on the client before sending it to your server. This approach minimizes your PCI DSS scope by ensuring raw card numbers never touch your infrastructure.
How JWE Encryption Works
Fetch Plexy's RSA public key from the API. This key is rotated regularly.
Use the public key to encrypt card details into a JWE token on the client.
Send the JWE token to your server, then forward it to Plexy's API.
Plexy decrypts the JWE token server-side and processes the payment.
JWE encryption is recommended for merchants who need to collect card details directly but want to minimize PCI scope. For most integrations, using Plexy Drop-in or Components is simpler and provides the same security benefits.
Retrieving the Public Key
Fetch the current encryption key before each payment session.
curl -X GET https://api.plexypay.com/v2/encryption/public-key \
-H "x-api-key: YOUR_API_KEY" \
-H "Content-Type: application/json"Response:
{
"key_id": "key_2026_03",
"public_key": "-----BEGIN PUBLIC KEY-----\nMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA0Z3VS...\n-----END PUBLIC KEY-----",
"algorithm": "RSA-OAEP-256",
"content_encryption": "A256GCM",
"expires_at": "2026-04-30T23:59:59Z"
}Client-Side Encryption
Browser Implementation
Use the Web Crypto API to encrypt card data in the browser.
class PlexyCardEncryptor {
constructor(publicKeyPem, keyId) {
this.publicKeyPem = publicKeyPem;
this.keyId = keyId;
}
async importPublicKey() {
// Convert PEM to ArrayBuffer
const pemContents = this.publicKeyPem
.replace('-----BEGIN PUBLIC KEY-----', '')
.replace('-----END PUBLIC KEY-----', '')
.replace(/\s/g, '');
const binaryDer = Uint8Array.from(atob(pemContents), (c) =>
c.charCodeAt(0),
);
return await crypto.subtle.importKey(
'spki',
binaryDer.buffer,
{
name: 'RSA-OAEP',
hash: 'SHA-256',
},
false,
['encrypt'],
);
}
async encrypt(cardData) {
const publicKey = await this.importPublicKey();
// Create the payload
const payload = JSON.stringify({
number: cardData.number.replace(/\s/g, ''),
expiry_month: cardData.expiryMonth,
expiry_year: cardData.expiryYear,
cvc: cardData.cvc,
holder_name: cardData.holderName,
encrypted_at: new Date().toISOString(),
});
// Generate a random AES key for content encryption
const aesKey = await crypto.subtle.generateKey(
{ name: 'AES-GCM', length: 256 },
true,
['encrypt'],
);
// Generate IV
const iv = crypto.getRandomValues(new Uint8Array(12));
// Encrypt the payload with AES-GCM
const encoder = new TextEncoder();
const encryptedContent = await crypto.subtle.encrypt(
{ name: 'AES-GCM', iv: iv },
aesKey,
encoder.encode(payload),
);
// Export and encrypt the AES key with RSA
const rawAesKey = await crypto.subtle.exportKey('raw', aesKey);
const encryptedKey = await crypto.subtle.encrypt(
{ name: 'RSA-OAEP' },
publicKey,
rawAesKey,
);
// Build JWE compact serialization
const header = {
alg: 'RSA-OAEP-256',
enc: 'A256GCM',
kid: this.keyId,
};
const jwe = [
this.base64url(JSON.stringify(header)),
this.base64url(encryptedKey),
this.base64url(iv),
this.base64url(encryptedContent.slice(0, -16)), // Ciphertext
this.base64url(encryptedContent.slice(-16)), // Auth tag
].join('.');
return jwe;
}
base64url(data) {
let base64;
if (typeof data === 'string') {
base64 = btoa(data);
} else if (data instanceof ArrayBuffer) {
base64 = btoa(String.fromCharCode(...new Uint8Array(data)));
} else {
base64 = btoa(String.fromCharCode(...data));
}
return base64.replace(/\+/g, '-').replace(/\//g, '_').replace(/=/g, '');
}
}
// Usage
async function encryptCardData(cardDetails, encryptionKey) {
const encryptor = new PlexyCardEncryptor(
encryptionKey.publicKey,
encryptionKey.keyId,
);
const jweToken = await encryptor.encrypt({
number: cardDetails.cardNumber,
expiryMonth: cardDetails.expiryMonth,
expiryYear: cardDetails.expiryYear,
cvc: cardDetails.cvc,
holderName: cardDetails.holderName,
});
return jweToken;
}Using the Plexy Encryption Library
For convenience, use the official encryption library.
import { PlexyEncryption } from '@plexy/plexy-web/browser';
async function encryptAndPay(cardDetails, encryptionKey) {
const encryption = new PlexyEncryption({
publicKey: encryptionKey.publicKey,
keyId: encryptionKey.keyId
});
// Encrypt card data
const encryptedCard = await encryption.encryptCard({
number: cardDetails.cardNumber,
expiryMonth: cardDetails.expiryMonth,
expiryYear: cardDetails.expiryYear,
cvc: cardDetails.cvc,
holderName: cardDetails.holderName
});
// Send to your backend
const response = await fetch('/api/payments', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
encryptedCard: encryptedCard.token,
keyId: encryptedCard.keyId,
amount: 15000,
currency: 'KZT',
reference: 'order_12345'
})
});
return response.json();
}Creating Payments with Encrypted Data
Send the encrypted card data to the Plexy API.
curl -X POST https://api.plexypay.com/v2/payments \
-H "x-api-key: YOUR_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"amount": {
"value": 15000,
"currency": "KZT"
},
"payment_method": {
"type": "card",
"encrypted_card": "eyJhbGciOiJSU0EtT0FFUC0yNTYiLCJlbmMiOiJBMjU2R0NNIiwia2lkIjoia2V5XzIwMjZfMDMifQ...",
"key_id": "key_2026_03"
},
"reference": "order_12345",
"merchant_id": "merchant_abc123",
"return_url": "https://your-site.com/checkout/complete"
}'Response:
{
"payment_id": "pay_abc123xyz",
"status": "authorized",
"amount": {
"value": 15000,
"currency": "KZT"
},
"payment_method": {
"type": "card",
"brand": "visa",
"last_four": "4242",
"expiry_month": "03",
"expiry_year": "2028"
},
"reference": "order_12345"
}Tokenizing Encrypted Cards
Save encrypted cards for future use by creating a token.
curl -X POST https://api.plexypay.com/v2/tokens \
-H "x-api-key: YOUR_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"encrypted_card": "eyJhbGciOiJSU0EtT0FFUC0yNTYiLCJlbmMiOiJBMjU2R0NNIiwia2lkIjoia2V5XzIwMjZfMDMifQ...",
"key_id": "key_2026_03",
"customer_id": "cust_12345",
"merchant_id": "merchant_abc123"
}'Response:
{
"token_id": "tok_abc123xyz",
"customer_id": "cust_12345",
"payment_method": {
"type": "card",
"brand": "visa",
"last_four": "4242",
"expiry_month": "03",
"expiry_year": "2028"
},
"created_at": "2026-03-25T10:30:00Z"
}JWE Payload Structure
Encrypted Card Payload
The card data encrypted within the JWE token follows this structure:
{
"number": "4111111111111111",
"expiry_month": "03",
"expiry_year": "2028",
"cvc": "737",
"holder_name": "John Doe",
"encrypted_at": "2026-03-25T10:30:00Z"
}JWE Header
The protected header must include:
| Field | Value | Description |
|---|---|---|
alg | RSA-OAEP-256 | Key encryption algorithm |
enc | A256GCM | Content encryption algorithm |
kid | key_YYYY_MM | Key ID from the public key response |
{
"alg": "RSA-OAEP-256",
"enc": "A256GCM",
"kid": "key_2026_03"
}Key Rotation
Plexy rotates encryption keys monthly. Handle key rotation gracefully by refreshing the key on startup and on a daily schedule.
To fetch the current public key, call:
curl -X GET https://api.plexypay.com/v2/encryption/public-key \
-H "x-api-key: YOUR_API_KEY"Cache the returned key_id and public_key. Keep the previous key in memory during rotation so that in-flight requests (encrypted with the old key) can still be processed. Schedule a refresh every 24 hours, and also retry with a fresh key whenever you receive an ENCRYPTION_KEY_EXPIRED or KEY_NOT_FOUND error.
Error Handling
After encrypting the card client-side, submit the encrypted payload to POST /v2/payments:
curl -X POST https://api.plexypay.com/v2/payments \
-H "x-api-key: YOUR_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"amount": { "value": 15000, "currency": "KZT" },
"payment_method": {
"type": "card",
"encrypted_card": "<JWE_TOKEN>",
"key_id": "key_2026_03"
},
"reference": "order_12345",
"merchant_id": "merchant_abc123"
}'Handle these encryption-specific error codes returned in the response body:
| Error code | Action |
|---|---|
ENCRYPTION_KEY_EXPIRED | Refresh the public key from GET /v2/encryption/public-key and retry |
ENCRYPTION_INVALID | Encryption failed or payload was tampered — show a user-facing error |
KEY_NOT_FOUND | Key ID unrecognized — refresh key cache and retry |
Security Best Practices
Never log, store, or transmit raw card numbers on your servers. JWE encryption must happen entirely on the client side.
Card data must be encrypted in the browser or mobile app before reaching your servers. Never send raw card numbers to your backend.
Always use HTTPS for all communications, including fetching public keys and sending encrypted data.
Check key expiry before encrypting. Refresh keys if they're close to expiring.
Implement key caching with automatic refresh. Accept both current and previous key IDs during rotation periods.
Encrypt card data immediately after collection. Don't hold unencrypted data in memory longer than necessary.
Clear card input fields and any temporary variables after encryption.
CSP Configuration
If using Content Security Policy, allow the Web Crypto API:
<meta
http-equiv="Content-Security-Policy"
content="default-src 'self';
script-src 'self' https://js.plexy.money;
connect-src 'self' https://api.plexy.money;"
/>Testing
Test JWE encryption in test mode before going live.
# Get test encryption key
curl -X GET https://api.plexypay.com/v2/encryption/public-key \
-H "x-api-key: YOUR_API_KEY"
# Create payment with test encrypted card
curl -X POST https://api.plexypay.com/v2/payments \
-H "x-api-key: YOUR_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"amount": {
"value": 10000,
"currency": "KZT"
},
"payment_method": {
"type": "card",
"encrypted_card": "YOUR_TEST_JWE_TOKEN",
"key_id": "key_test_2026_03"
},
"reference": "test_jwe_payment",
"merchant_id": "merchant_abc123"
}'Test Cards for JWE
| Card Number | Behavior |
|---|---|
4111 1111 1111 1111 | Successful payment |
4000 0000 0000 0002 | Declined (insufficient funds) |
4000 0000 0000 0069 | Requires 3D Secure |
4000 0000 0000 3220 | Partial authorization |
PCI DSS Compliance
Using JWE encryption reduces your PCI DSS scope:
| Integration Type | PCI DSS Level | Description |
|---|---|---|
| Direct API (raw cards) | SAQ D | Full assessment required |
| JWE Encryption | SAQ A-EP | Reduced scope |
| Plexy Drop-in | SAQ A | Minimal scope |
While JWE encryption reduces PCI scope, you should still complete the appropriate SAQ and maintain security best practices. Contact your QSA for guidance on your specific situation.
Next Steps
- Tokenization - Save cards for recurring payments
- 3D Secure - Add authentication for encrypted card payments
- PCI DSS Compliance - Understand your compliance requirements