Accepting a Credit Card Payment on your Website
Accepting a Credit Card Payment on your Website
As a developer, use Stax.js to accept a credit card payment on your website and check the payment result.
The payment flow tokenizes the card (securely stores its details and returns a payment method ID) and attempts to charge it. You can optionally provide additional payment details for Level 2 processing (processing that uses tax and purchase-order data to qualify eligible payments for specific processing rates).
Add Stax.js to your site
Add the script shown below to the <head> of your HTML file.
<script src="https://staxjs.staxpayments.com/staxjs-captcha.js"></script>Run these examples together on the same HTML page. Create the form from the Create Payment Form tab before running the initialization JavaScript, so the field containers exist. Then load the card fields, register the form event handlers, define extraDetails, and register the payment handler.
Initialize Stax.js
- In Stax Pay > Apps > API Keys, copy your Web Payments Token (public key). Do not use your private API key in browser code.
- Initialize your Stax.js instance with the
StaxJsclass. Enter your public token when the example prompts you.
Note: Passing the number and CVV into the instance of staxjs generates the secure iFrame around these two fields, keeping sensitive card information from touching your servers.
// Copy your 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 html id of the div you want to contain the credit card number field
placeholder: '0000 0000 0000 0000', // the placeholder the field should contain
style: 'height: 30px; width: 100%; font-size: 15px;', // the style to apply to the field
type: 'text', // the input type (optional)
format: 'prettyFormat' // the formatting of the CC number (prettyFormat || plainFormat || maskedFormat)
},
cvv: {
id: 'card-cvv', // the html id of the div you want to contain the cvv field
placeholder: 'CVV', // the placeholder the field should contain
style: 'height: 30px; width: 100%; font-size: 15px;', // the style to apply to the field
type: 'text' // the input type (optional)
}
});Payment Form
Create a payment form to capture the card number and CVV (the card's security code). Keep the Pay button disabled until the form event handler confirms that both fields are valid.
<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="paybutton" type="button" disabled>
Pay
</button>
</form>Insert the Field Data
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
Stax.js has handlers available to check for field input validity.
Handle Invalid Input
First, we will handle the card_form_uncomplete event, which means that the input within the fields is invalid.
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);
// Prevent submission while card details are incomplete or invalid.
var payButton = document.querySelector("#paybutton");
payButton.disabled = true;
});Handle Valid Input
Next, we'll handle the card_form_complete event, which means that the input within the fields is complete and valid.
staxjs.on("card_form_complete", (message) => {
// the customer has finished filling in the fields, and they're valid!
// Nice!
console.log(message);
// activate pay button
var payButton = document.querySelector("#paybutton");
payButton.disabled = false;
});Taking a Payment
When taking a payment on a site, you can include additional details in the meta data.
Payment Field Reference
| Field | Description | Required |
|---|---|---|
| total | Number. Required when you call pay(). | Yes |
| meta | Object containing optional payment details. | No |
| meta.tax | Float. Tax amount in dollars. To qualify for Level 2 processing rates (rates available to eligible payments that include additional tax and purchase-order data), the tax must be between 0.1% and 30% of the transaction total. | No |
| meta.shippingAmount | Number. Shipping amount for the transaction. | No |
| meta.poNumber | String. Customer code or purchase-order number used to qualify for Level 2 processing rates (rates available to eligible payments that include additional tax and purchase-order data). | No |
| meta.invoice_merchant_custom_fields | An array containing custom field objects. See the example below. These fields appear only if your account subscribes to the Advanced Customization add-on. Contact your Account Manager to enable it. | No |
| url | not required; this represents the hosted URL where this paid invoice can be viewed when the invoice's ID is appended to it. See here for an example of what a hosted paid invoice looks like. | no |
| send_receipt | not required, boolean, defaults to true. When set to true an email will be sent every time the pay() method is called from your application – even if the transaction is unsuccessful. If the transaction is unsuccessful (for whatever reason), an email will be sent, which will include a call to action to pay using the Stax-hosted payments solution. Alternatively, if you use the out-of-the-box Stax email solution but would like more control over when a receipt email is sent, you can use the Transactions resource to send the receipt via email or sms. | no |
| match_customer | Boolean. Determines whether or not Stax.js matches the customer to an existing customer based on some combination of the same data sent into the JS request. See Best Practices: Customer matching section for more details. | no |
Optional: Include Extra Payment Details
Use this JavaScript object with the payment handler below. Replace the sample customer details and expiration date with the cardholder's actual details; use an unexpired test card when testing. This is JavaScript, not a JSON request body.
const extraDetails = {
total: 26,
firstname: "John",
lastname: "Doe",
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",
send_receipt: false,
match_customer: false,
validate: true, // Validate submitted details before attempting payment.
meta: {
reference: "invoice-reference-num", // optional - will show up in emailed receipts
memo: "notes about this transaction", // optional - will show up in emailed receipts
otherField1: "other-value-1", // optional - we don't care
otherField2: "other-value-2", // optional - we don't care
subtotal: 20.0, // optional - will show up in emailed receipts
tax: 4.0, // Tax in dollars; eligible payments can qualify for rates based on additional tax and purchase-order data.
poNumber: "7649", // Sample purchase-order number; replace with your customer's purchase-order number.
shippingAmount: 2.0, // Include shipping to describe the transaction total.
lineItems: [
// optional - will show up in emailed receipts
{
id: "optional-fm-catalog-item-id",
item: "Demo Item",
details: "this is a regular demo item",
quantity: 20,
price: 1,
}
],
invoice_merchant_custom_fields: [
{
id: "dc4b-6c74-00dd-fab1-fe00", // Required, must be a unique string.
name: "External ID", // The name of the custom field that will be displayed to your customers and users; this will appear above the field as a label.
placeholder: "Ex. #123", // The placeholder for the field; this is the faint text that will appear in the entry box of your custom field to help guide your users before they enter in the value when creating an Invoice.
required: true, // Determines if this field is required to be filled by the user (not customer) when first creating an Invoice.
type: "text", // Input type. Only 'text' is supported.
value: "123456789", // The value that will appear when viewing the Invoice or Invoice Email. For the merchant, this will also appear when viewing the Invoice via the Invoices or Edit Invoice pages.
visible: true, // This determines if the field is visible when viewing the Invoice or Invoice Email. If false, will only appear in merchant-facing pages such as the Invoices or Edit Invoice pages.
},
],
},
};Accept Payment from Card
document.querySelector("#paybutton").onclick = () => {
staxjs
.pay(extraDetails)
.then((response) => {
if (!response || response.status !== "PAID") {
console.error("Payment was not completed:", response);
return;
}
console.log("invoice object:", response);
const transaction = response.child_transactions && response.child_transactions[0];
if (!transaction) {
console.warn("Invoice is PAID, but no child transaction was returned:", response);
return;
}
console.log("transaction object:", transaction);
})
.catch((err) => {
console.log("unsuccessful payment:", err);
});
};Check the payment result
The Stax.js pay() method stores a payment method tied to a new or existing customer, creates an invoice using extraDetails, and attempts payment. A resolved promise does not by itself confirm payment: treat an invoice with status: "PAID" as success, not one with status: "ATTEMPTED".
For the successful response below, expect status: "PAID", balance_due: 0, and total_paid: 26. The console logs the invoice and its first child transaction. If payment is unsuccessful, inspect the returned invoice or the error logged by the payment handler before deciding whether to retry.
The resulting response of the pay() method is the invoice object, which will include a reference to the customer, the payment method, and the transaction that was made.
To access transaction information, use response.child_transactions[0] since the response is the full invoice object.
Example Response (Invoice Object)
The top-level id is the invoice ID; child_transactions[0].id is the transaction ID. These response IDs are illustrative, not values to copy into requests.
{
"balance_due": 0,
"child_transactions": [
{
"auth_id": null,
"created_at": "2020-07-01 00:17:08",
"customer_id": "e8978baa-0278-47c2-9036-2849c6f522e1",
"id": "0a40f1a9-f308-4add-8613-91f717b52831",
"invoice_id": "101c4a15-5cdb-41e5-837c-f23470c7d670",
"is_manual": false,
"is_merchant_present": false,
"issuer_auth_code": null,
"last_four": "1111",
"message": null,
"meta": {"memo": "notes about this transaction", "otherField1": "other-value-1", "otherField2": "other-value-2"},
"method": "card",
"payment_method": {"id": "68ad2229-18ab-47d5-8713-2f4cf109af55", "customer": null},
"payment_method_id": "68ad2229-18ab-47d5-8713-2f4cf109af55",
"receipt_email_at": null,
"receipt_sms_at": null,
"reference_id": "",
"source": null,
"success": true,
"total": 26,
"type": "charge",
"updated_at": "2020-07-01 00:17:08"
}
],
"created_at": "2020-07-01 00:17:08",
"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-01 00:17:07",
"deleted_at": null,
"email": "",
"firstname": "Jon",
"gravatar": false,
"id": "e8978baa-0278-47c2-9036-2849c6f522e1",
"lastname": "Doe",
"notes": null,
"options": null,
"phone": "111111111111111",
"reference": "",
"updated_at": "2020-07-01 00:17:07"
},
"customer_id": "e8978baa-0278-47c2-9036-2849c6f522e1",
"deleted_at": null,
"due_at": null,
"id": "101c4a15-5cdb-41e5-837c-f23470c7d670",
"invoice_date_at": "2020-07-01 00:17:08",
"is_merchant_present": null,
"is_partial_payment_enabled": true,
"is_webpayment": true,
"meta": {
"lineItems": [
{
"details": "this is a regular, demo item",
"id": "optional-fm-catalog-item-id",
"item": "Demo Item",
"price": 1,
"quantity": 20
}
],
"memo": "notes about this transaction",
"otherField1": "other-value-1",
"otherField2": "other-value-2",
"reference": 1988,
"subtotal": 20,
"tax": 4,
"poNumber": "7649",
"shippingAmount": 2
},
"paid_at": "2020-07-01 00:17:10",
"payment_attempt_failed": false,
"payment_attempt_message": "",
"payment_method_id": "68ad2229-18ab-47d5-8713-2f4cf109af55",
"schedule_id": null,
"sent_at": null,
"status": "PAID",
"total": 26,
"total_paid": 26,
"updated_at": "2020-07-01 00:17:10",
"url": "https://app.staxpayments.com/#/bill/",
"viewed_at": null
}Updated 4 days ago
