JavaScript Integration

Integrate the Trustist Ecommerce API into your JavaScript applications using standard HTTP requests with Hawk authentication.

Approach: Use JavaScript to make authenticated API calls to the Trustist Ecommerce API endpoints. For web applications, make these calls from your server-side code to avoid exposing API credentials in the browser.

Client-Side Integration

To use the SDK, first include the SDK script in your HTML file. Replace {{client_id}} with your actual client ID.

For Sandbox Testing

<script src="https://sdk-sandbox.trustistecommerce.com/js/sdk.js?client-id={{client_id}}" async></script>

For Production

<script src="https://sdk.trustistecommerce.com/js/sdk.js?client-id={{client_id}}" async></script>

Creating Payments

Step 1: Add a Container Element

Create a <div> element in your HTML where the payment button will be rendered:

<div id="trustistEcommerce"></div>

Step 2: Initialize the SDK

Add the following JavaScript code, adjusting the createPayment and paymentComplete functions to interact with your server:

<script>
window.trustistReadyCallback = function () {
    trustist.ecommerce.Payment({
        createPayment: () => {
            // Call your local API to create a Trustist payment
            // Then return the payment URL to the SDK for use in the button
            return fetch("/api/payments", {
                method: "post",
                headers: {
                    'Accept': 'application/json',
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify({
                    orderId: "your_order_id",
                    returnUrl: "your_return_url"
                }),
            })
            .then((response) => response.json())
            .then((payment) => payment.payLink);
        },
        paymentComplete: (payment) => {
            // Called by the SDK on return from the Trustist payment process
            // Check with the API directly to get a verified result
            return fetch("/api/payments/" + payment["tr-payment-id"], {
                method: "get",
            })
            .then((response) => response.json())
            .then((payment) => {
                if (payment.status === "COMPLETE") {
                    window.location.href = "ThankYou";
                } else {
                    // Handle unsuccessful payment
                }
            });
        }
    }).render("#trustistEcommerce");
};
</script>
Security Note: Replace your_order_id and your_return_url with your actual values. The createPayment function should make a POST request to your server, which then communicates with the Trustist Ecommerce API securely.

Creating Standing Orders (Direct Debit)

The process for standing orders is very similar to payments:

<script>
window.trustistReadyCallback = function () {
    trustist.ecommerce.Payment({
        createStandingOrder: () => {
            // Call your local API to create a standing order
            return fetch("/api/standingorders", {
                method: "post",
                headers: {
                    'Accept': 'application/json',
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify({
                    orderId: "your_order_id",
                    returnUrl: "your_return_url"
                }),
            })
            .then((response) => response.json())
            .then((standingOrder) => standingOrder.payLink);
        },
        paymentComplete: (payment) => {
            // Check standing order status
            return fetch("/api/standingorders/" + payment["tr-payment-id"], {
                method: "get",
            })
            .then((response) => response.json())
            .then((standingOrder) => {
                if (standingOrder.status === "ACTIVE") {
                    window.location.href = "ThankYou";
                } else {
                    // Handle unsuccessful setup
                }
            });
        }
    }).render("#trustistEcommerce");
};
</script>
Note: Your merchant account must have standing orders enabled before you can create them. If not enabled, the API will return an error message.

Customizing Button Appearance

You can customize the payment button's appearance by passing options to the render function:

Customization Options

  • path (String): The CSS selector for the element where the button will be rendered (e.g., "#payment-button-container")
  • buttonText (String): The text displayed on the button (e.g., "Pay Now")
  • buttonColour (String): The background color of the button (e.g., "#28a745" for green)
  • textColour (String): The text color of the button (e.g., "#ffffff" for white)
  • buttonHoverColour (String): The background color when hovered (e.g., "#218838" for darker green)
  • textHoverColour (String): The text color when hovered (e.g., "#ffffff" for white)
  • loadingText (String): The text displayed when the button is clicked and loading (e.g., "Processing...")

Example with Custom Styling

<script>
trustist.ecommerce.Payment({
    createPayment: async function() {
        // Your logic to create a payment
    }
}).render({
    path: "#payment-button-container",
    buttonText: "Pay Now",
    buttonColour: "#28a745",
    textColour: "#ffffff",
    buttonHoverColour: "#218838",
    textHoverColour: "#ffffff",
    loadingText: "Processing..."
});
</script>

Complete Example

Here's a complete HTML page with a customized payment button:

<!DOCTYPE html>
<html>
<head>
    <title>Payment Example</title>
</head>
<body>
    <h1>Complete Your Payment</h1>
    <div id="payment-button-container"></div>

    <script src="https://sdk-sandbox.trustistecommerce.com/js/sdk.js?client-id=YOUR_CLIENT_ID" async></script>
    <script>
        window.trustistReadyCallback = function () {
            trustist.ecommerce.Payment({
                createPayment: () => {
                    return fetch("/api/payments", {
                        method: "post",
                        headers: {
                            'Accept': 'application/json',
                            'Content-Type': 'application/json'
                        },
                        body: JSON.stringify({
                            amount: 99.99,
                            reference: "ORDER-12345",
                            returnUrl: window.location.origin + "/payment/success"
                        }),
                    })
                    .then((response) => response.json())
                    .then((payment) => payment.payLink);
                },
                paymentComplete: (payment) => {
                    return fetch("/api/payments/" + payment["tr-payment-id"], {
                        method: "get",
                    })
                    .then((response) => response.json())
                    .then((payment) => {
                        if (payment.status === "COMPLETE") {
                            window.location.href = "/payment/success";
                        } else {
                            alert("Payment failed. Please try again.");
                        }
                    });
                }
            }).render({
                path: "#payment-button-container",
                buttonText: "Complete Payment",
                buttonColour: "#007bff",
                textColour: "#ffffff",
                buttonHoverColour: "#0056b3",
                textHoverColour: "#ffffff",
                loadingText: "Processing your payment..."
            });
        };
    </script>
</body>
</html>

Server-Side Integration

Your server needs to implement two endpoints to work with the SDK:

1. Create Payment Endpoint

This endpoint creates a payment via the Trustist API and returns the payment link:

// Example Node.js/Express endpoint
app.post('/api/payments', async (req, res) => {
    const { amount, reference, returnUrl } = req.body;
    
    // Call Trustist Ecommerce API with Hawk authentication
    const payment = await trustistClient.createPayment({
        amount,
        reference,
        returnUrl
    });
    
    res.json({
        id: payment.id,
        payLink: payment.payLink
    });
});

2. Get Payment Status Endpoint

This endpoint retrieves the payment status for verification:

// Example Node.js/Express endpoint
app.get('/api/payments/:id', async (req, res) => {
    const { id } = req.params;
    
    // Call Trustist Ecommerce API to get payment status
    const payment = await trustistClient.getPayment(id);
    
    res.json({
        id: payment.id,
        status: payment.status,
        amount: payment.amount,
        reference: payment.reference
    });
});
Security Best Practice: With this setup, your server handles all communication with the Trustist Ecommerce API securely, and your web application can update the user interface based on payment status without exposing sensitive information.

Next Steps