Tokenizing a Credit Card
Tokenizing a Credit Card
As a developer, use Stax.js to tokenize a credit card (securely store the card and receive a payment method ID for future use) in your website's payment form.
Stax.js is Stax's browser-side JavaScript library. It sends sensitive bank and card information directly from your user's browser to Stax's servers. This supports your Payment Card Industry Data Security Standard (PCI DSS) compliance efforts; it does not guarantee compliance. Consult your legal and compliance teams about your specific requirements.
Accepting a payment with a card is similar to tokenizing a card, but it also processes a payment from the tokenized card. You can also include additional details within the call to take advantage of Level 2 processing.
Sensitive data never touches your servers
Cards are tokenized and stored securely for future use
Support for additional payment details
Add Stax.js to your site
Add the script shown below to the <head> of your HTML file. Copy the rendered script, not this page's documentation markup.
<script src="https://staxjs.staxpayments.com/staxjs-captcha.js"></script>Run the examples together on the same HTML page. Create the payment form from the Implementation tab before running the initialization JavaScript. Then load the card fields, register the validation handlers, define extraDetails, and register the tokenization handler, in that order. Run your JavaScript after the form's HTML so its containers and button exist.
Initialize Stax.js
Getting Your Web Payments Token
In Stax Pay, open Apps > API Keys and copy your Web Payments Token (public key). Use that value when the initialization example prompts you for it; do not enter a private API key.
Initialize your Stax.js instance with the StaxJs class using your Web Payments Token. This example prompts for your account's actual public token instead of using an invented token value:
Note: Passing the number and CVV into the Stax.js instance generates a secure iframe around these two fields, keeping sensitive card information from touching your servers.
// Copy the public token from Stax Pay > Apps > API Keys.
const webPaymentsToken = window.prompt("Enter your Web Payments Token (public key):");
if (!webPaymentsToken || !webPaymentsToken.trim()) {
throw new Error("A Web Payments Token is required to initialize Stax.js.");
}
var staxjs = new StaxJs(webPaymentsToken.trim(), {
number: {
id: "card-number", // The ID of the container for the card-number field.
placeholder: "0000 0000 0000 0000",
style: "height: 30px; width: 100%; font-size: 15px;",
type: "text",
format: "prettyFormat" // Use prettyFormat, plainFormat, or maskedFormat.
},
cvv: {
id: "card-cvv", // The ID of the container for the CVV field.
placeholder: "CVV",
style: "height: 30px; width: 100%; font-size: 15px;",
type: "text"
}
});Create a payment form
Create a payment form to capture the card number and CVV (the card's security code). Keep the Tokenize button disabled until the form validation handler confirms that the input is complete and valid. Tokenizing stores the card; it does not charge it.
<form onsubmit="return false;">
<div id="card-number" style="width:200px; height:30px;"></div>
<div id="card-cvv" style="width:50px; height:30px;"></div>
<button id="tokenizebutton" type="button" disabled>
Tokenize
</button>
</form>Load the Data fields
Now that we've initialized our instance of StaxJs and made the elements that will contain the credit card fields, we can tell StaxJs to load in those credit card fields. The showCardForm function returns a Promise, which lets us handle the completion of the credit card fields loading in.
staxjs
.showCardForm()
.then((handler) => {
console.log("form was loaded");
// for quick testing, you can set a test number and test cvv here
// handler.setTestPan("4111111111111111");
// handler.setTestCvv("123");
})
.catch((err) => {
console.log("there was an error loading the form: ", err);
});Handling Form Completion
Form Validation Events
Stax.js has handlers available to check for field input validity.
Handling Invalid Input:
staxjs.on("card_form_uncomplete", (message) => {
// the customer hasn't quite finished filling in the fields
// or the input in the fields are invalid
console.log(message);
// deactivate pay button
var tokenizeButton = document.querySelector("#tokenizebutton");
tokenizeButton.disabled = true;
});Handling Valid Input:
staxjs.on("card_form_complete", (message) => {
// the customer has finished filling in the fields, and they're valid!
console.log(message);
// activate pay button
var tokenizeButton = document.querySelector("#tokenizebutton");
tokenizeButton.disabled = false;
});Form Details & Tokenization
Required Extra Details
We have implemented the credit card fields and are ready to send the payment, but we need a few additional fields in the request to tokenize. An object called extraDetails includes, at a minimum, the required fields for creating a tokenized credit card with Stax.js
| Field Name | Description | Required |
|---|---|---|
| customer_id | It must be a string matching a valid customer_id in your merchant account. If supplied, we will not create or match a new customer based on values. Instead, the supplied ID will be assigned to this new payment method and transaction. If a customer_id is supplied, certain customer fields, such as firstname, lastname, phone, all address fields, etc., will be ignored. | No |
| firstname | max of 50 characters | Yes |
| lastname | max of 50 characters | Yes |
| phone | must be at least ten characters | No |
must be a valid email. Receipts will be sent here automatically if the send_receipt flag is set to true. | No | |
| adddress_1 | Max 255 characters. This field is required for AVS if the account is configured to perform an AVS check on the street address. Required if customer_id is not passed into details | No* |
| address_2 | Max of 255 characters | No |
| address_city | Required if customer_id is not passed into details, max of 255 characters | No* |
| address_state | Required if customer_id is not passed into details, max of 2 characters (e.g. FL) | No* |
| address_country | Character country code (e.g. USA) | No |
| address_zip | Not required unless AVS or surcharging is enabled. | No* |
| company | String | No |
| method | “card” or “bank” | Yes |
| month | A string representing the 2-digit month when the card expires(“05”) | Yes* |
| year | A string representing the 4-digit year when the card expires (“2020”) | Yes* |
| match_customer | Boolean. This determines whether Stax.js matches the customer to an existing customer based on some combination of the same data sent in the JS request. See the Best Practices: Customer matching section for more details. | No |
| validate | Determines whether or not Stax.js does client-side validation. | No |
Example of extraDetails:
const extraDetails = {
firstname: "John",
lastname: "Doe",
method: "card",
month: "10",
year: "2030",
phone: "5555555555",
address_1: "100 S Orange Ave",
address_2: "Suite 400",
address_city: "Orlando",
address_state: "FL",
address_zip: "32811",
address_country: "USA",
match_customer: false
};Use a test card with an unexpired date when testing. The example no longer explicitly disables validation.
Call the tokenize() method
document.querySelector("#tokenizebutton").onclick = () => {
staxjs
.tokenize(extraDetails)
.then((response) => {
console.log("payment method object:", response);
console.log("customer object:", response.customer);
})
.catch((err) => {
console.log("unsuccessful tokenization:", err);
});
};Response
A successful staxjs.tokenize() call creates a tokenized payment method tied to a new or existing customer. Your console logs payment method object: with the returned payment method and customer object: with its customer. Save the returned id for future charges and customer_id to associate the customer with your application's records; these IDs come from the response, not from values you invent.
If tokenization fails, your console logs unsuccessful tokenization: with the error. Review the error and correct the supplied details before trying again. The JSON below illustrates a successful response; its IDs and historical timestamps are sample data, not credentials or values to reuse in requests.
Example Response Structure
Payment Method Object:
{
"address_1": "100 S Orange Ave",
"address_2": null,
"address_city": "Orlando",
"address_country": "USA",
"address_state": "FL",
"address_zip": "32811",
"bank_holder_type": null,
"bank_name": null,
"bank_type": null,
"card_exp": "112020",
"card_exp_datetime": "2020-11-30 23:59:59",
"card_last_four": "1111",
"card_type": "visa",
"created_at": "2020-07-06 16:22:16",
"customer": {
"address_1": "100 S Orange Ave",
"address_2": "",
"address_city": "Orlando",
"address_country": "USA",
"address_state": "FL",
"address_zip": "32811",
"allow_invoice_credit_card_payments": true,
"cc_emails": null,
"cc_sms": null,
"company": "",
"created_at": "2020-07-06 16:22:16",
"deleted_at": null,
"email": "",
"firstname": "Jon",
"gravatar": false,
"id": "cd10fbd4-199c-4753-8db8-66c4e2c2b4e8",
"lastname": "Doe",
"notes": null,
"options": null,
"phone": "111111111111111",
"reference": "",
"updated_at": "2020-07-06 16:22:16"
},
"customer_id": "cd10fbd4-199c-4753-8db8-66c4e2c2b4e8",
"has_cvv": true,
"id": "2e34394f-5f1d-4ec0-a56d-f669509a5b13",
"is_default": 0,
"is_usable_in_vt": true,
"method": "card",
"nickname": "VISA: Jon Doe (ending in: 1111)",
"person_name": "Jon Doe",
"updated_at": "2020-07-06 16:22:16"
}id: Payment method ID for future transactionscustomer_id: Customer ID for record keepingcard_last_four: Last four digits for displaycard_type: Card brand (visa, mastercard, etc.)
Use the payment method ID for future charges or store the customer ID to associate with your user records.
Updated 5 days ago
