Collecting Payment Methods
Learn how to securely collect card payment methods using BT AI’s SDK with JWT-based authentication. This guide covers JWT creation, SDK initialization, and card component integration for both JavaScript and React.
Overview
BT AI uses a secure JWT-based authentication system for payment method collection. Your backend creates and signs JWTs containing entity information, which are then used by the frontend SDK to securely collect and tokenize payment data without exposing sensitive information to your servers.
Prerequisites
Before proceeding, ensure you have completed the Setup and have received from support:
- Project ID and RSA Key Pair for JWT signing
SDK Installation
Install the React SDK in your frontend application:
npm install @basis-theory-ai/react@beta --saveJWT Creation and Signing
JWT Creation Examples
A JWT will be created in your backend systems and passed into your frontend to enable a secure handshake for authentication.
For collecting payment methods, create a JWT with a public role and entity information:
const jwt = require('jsonwebtoken');
const fs = require('fs');
// Load your private key (from setup process)
const privateKey = fs.readFileSync('/path/to/your/private-key.pem');
// Create JWT payload
const payload = {
sub: 'user-12345', // Subject: unique user identifier
iss: 'your-project-id', // Issuer: your project ID
roles: ['public'], // Public role for payment method collection
iat: Math.floor(Date.now() / 1000),
exp: Math.floor(Date.now() / 1000) + (60 * 60) // 1 hour expiration
};
// Sign JWT with RSA private key
const token = jwt.sign(payload, privateKey, {
algorithm: 'RS256',
keyid: 'your-key-id' // Key ID from setup process
});
console.log('JWT token:', token);Security Note: JWT signing should always be done on your backend server, not in frontend code. The frontend examples above are for understanding only.
SDK Initialization
Set up the BasisTheory provider in your React app to enable SDK functionality:
import React, { useState, useEffect } from 'react';
import { BasisTheoryProvider } from '@basis-theory-ai/react';
function App() {
// Get JWT from your backend (example endpoint)
const [jwtToken, setJwtToken] = useState(null);
useEffect(() => {
// Fetch JWT from your backend
fetch('/api/auth/jwt', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ userId: 'user-12345' })
})
.then(res => res.json())
.then(data => setJwtToken(data.token));
}, []);
if (!jwtToken) {
return <div>Loading...</div>;
}
return (
<BasisTheoryProvider
apiKey={jwtToken} // Your JWT token from backend
environment="sandbox" // or "production"
>
<PaymentForm />
</BasisTheoryProvider>
);
}
Displaying the Card Component
This next step will add a capture form (or tap to add) compnent to securely capture a credit card and convert it into a Payment Method.
import React, { useRef, useState } from 'react';
import { useBasisTheory } from '@basis-theory-ai/react';
function PaymentForm() {
const cardRef = useRef(null);
const [isValid, setIsValid] = useState(false);
const handleCardChange = (event) => {
setIsValid(event.complete && !event.error);
};
const handleSubmit = async (e) => {
e.preventDefault();
if (!cardRef.current || !isValid) return;
try {
const paymentMethod = await cardRef.current.createPaymentMethod();
console.log('Payment method created:', paymentMethod);
} catch (error) {
console.error('Error creating payment method:', error);
}
};
return (
<form onSubmit={handleSubmit}>
<div className="form-group">
<label htmlFor="card">Card Information</label>
<Card
ref={cardRef}
onChange={handleCardChange}
styles={{
...
}}
/>
</div>
<button type="submit" disabled={!isValid}>
Create Payment Method
</button>
</form>
);
}Next Steps
Excellent! You’ve successfully implemented payment method collection. Your users can now securely enter and save their payment information. Now it’s time to use these payment methods to purchase goods!
Choose Your Checkout Flow
You have two main options for implementing checkout with your collected payment methods:
1. Browser Checkout (Recommended for Most Use Cases)
Browser Checkout - When the purchase will take place by driving a browser to coordinate the purchase on a websie.
Best for:
- E-commerce or Services with no API
2. API Checkout (Advanced Server-Side Processing)
API Checkout - Ideal for complex business scenarios requiring virtual card generation and server-side control.
Best for:
- E-commerce or Services with an API
Additional Resources
- Card Component Reference - Detailed component documentation
- Events Reference - Complete event handling guide
- API Reference - Payment method API documentation