Integrating with PHP

This guide demonstrates how to integrate the Trustist Ecommerce Payments API into your PHP application using Guzzle HTTP client and Hawk authentication.

1. Installation

Install Guzzle and the Hawk authentication library using Composer:

composer require guzzlehttp/guzzle
composer require shawm11/hawk-auth

2. Configuration

Create a Guzzle client and configure it with your API credentials and the desired environment (sandbox or production). We'll create helper functions to handle Hawk authentication for all requests.

<?php
use GuzzleHttp\\Client;
use Shawm11\\Hawk\\Client\\Client as HawkClient;
use Shawm11\\Hawk\\Client\\ClientException as HawkClientException;

$base_uri = 'https://api-sandbox.trustistecommerce.com';
$client = new Client([
    'base_uri' => $base_uri,
]);

function createHawkClient() {
    return new HawkClient();
}

function getCredentials() {
    return [
        'id' => 'your-client-id',
        'key' => 'your-client-key',
        'algorithm' => 'sha256',
    ];
}

function sendRequest($method, $url, $payload = null) {
    global $client, $base_uri;

    $hawkClient = createHawkClient();
    $options = [
        'credentials' => getCredentials(),
        'ext' => null,
    ];

    if ($payload !== null) {
        $options['contentType'] = 'application/json';
        $options['payload'] = json_encode($payload);
    }

    $result = $hawkClient->header($base_uri . $url, $method, $options);
    $header = $result['header'];

    $response = $client->request($method, $url, [
        'headers' => [
            'Authorization' => $header,
            'Content-Type' => 'application/json'
        ],
        'body' => $payload !== null ? json_encode($payload) : null
    ]);

    return json_decode($response->getBody(), true);
}
?>

3. Creating a Payment

To create a new payment, make a POST request to the /v1/payments endpoint with the payment details.

<?php
function createPayment($amount, $reference, $returnUrl) {
    $data = [
        'amount' => $amount,
        'reference' => $reference,
        'returnUrl' => $returnUrl
    ];

    $url = '/v1/payments';
    return sendRequest('POST', $url, $data);
}

// Usage example
$payment = createPayment(99.99, 'ORDER-12345', 'https://yoursite.com/payment/success');

echo "Payment ID: " . $payment['id'] . "\\n";
echo "Payment Link: " . $payment['payLink'] . "\\n";
?>

4. Retrieving a Payment

To retrieve the details of an existing payment, make a GET request to the /v1/payments/{paymentId} endpoint.

<?php
function getPayment($paymentId) {
    $url = "/v1/payments/{$paymentId}";
    return sendRequest('GET', $url);
}

// Usage example
$payment = getPayment('your-payment-id');

echo "Status: " . $payment['status'] . "\\n";
echo "Amount: " . $payment['amount'] . "\\n";
echo "Reference: " . $payment['sourceReference'] . "\\n";
?>

Example: Complete Integration

Here's a complete example showing a payment flow:

<?php
require 'vendor/autoload.php';

use GuzzleHttp\\Client;
use Shawm11\\Hawk\\Client\\Client as HawkClient;

class TrustistEcommerceClient
{
    private $client;
    private $baseUri;
    private $clientId;
    private $privateKey;

    public function __construct($clientId, $privateKey, $environment = 'sandbox')
    {
        $this->clientId = $clientId;
        $this->privateKey = $privateKey;
        $this->baseUri = $environment === 'sandbox'
            ? 'https://api-sandbox.trustistecommerce.com'
            : 'https://api.trustistecommerce.com';

        $this->client = new Client([
            'base_uri' => $this->baseUri,
        ]);
    }

    private function sendRequest($method, $url, $payload = null)
    {
        $hawkClient = new HawkClient();
        $options = [
            'credentials' => [
                'id' => $this->clientId,
                'key' => $this->privateKey,
                'algorithm' => 'sha256',
            ],
            'ext' => null,
        ];

        if ($payload !== null) {
            $options['contentType'] = 'application/json';
            $options['payload'] = json_encode($payload);
        }

        $result = $hawkClient->header($this->baseUri . $url, $method, $options);
        $header = $result['header'];

        $response = $this->client->request($method, $url, [
            'headers' => [
                'Authorization' => $header,
                'Content-Type' => 'application/json'
            ],
            'body' => $payload !== null ? json_encode($payload) : null
        ]);

        return json_decode($response->getBody(), true);
    }

    public function createPayment($amount, $reference, $returnUrl)
    {
        return $this->sendRequest('POST', '/v1/payments', [
            'amount' => $amount,
            'reference' => $reference,
            'returnUrl' => $returnUrl
        ]);
    }

    public function getPayment($paymentId)
    {
        return $this->sendRequest('GET', "/v1/payments/{$paymentId}");
    }

    public function createStandingOrder($amount, $reference, $startDate, $frequency, $numberOfPayments = 0)
    {
        return $this->sendRequest('POST', '/v1/standingorders', [
            'amount' => $amount,
            'reference' => $reference,
            'startDate' => $startDate, // yyyy-MM-dd
            'frequency' => $frequency, // Weekly, Monthly, Annually
            'numberOfPayments' => $numberOfPayments,
            'returnUrl' => 'https://yoursite.com/standing-order/success'
        ]);
    }

    public function getStandingOrder($standingOrderId)
    {
        return $this->sendRequest('GET', "/v1/standingorders/{$standingOrderId}");
    }
}

// Usage
$trustist = new TrustistEcommerceClient(
    'your-client-id',
    'your-private-key',
    'sandbox'
);

try {
    // Create a payment
    $payment = $trustist->createPayment(
        99.99,
        'ORDER-12345',
        'https://yoursite.com/payment/success'
    );

    echo "Redirect customer to: " . $payment['payLink'] . "\\n";

    // Later, verify payment status
    $status = $trustist->getPayment($payment['id']);
    if ($status['status'] === 'COMPLETE') {
        echo "Payment completed!\\n";
    }
} catch (Exception $e) {
    echo "Error: " . $e->getMessage() . "\\n";
}
?>

Laravel Integration

For Laravel applications, create a service provider:

<?php
namespace App\\Providers;

use Illuminate\\Support\\ServiceProvider;
use App\\Services\\TrustistEcommerceClient;

class TrustistServiceProvider extends ServiceProvider
{
    public function register()
    {
        $this->app->singleton(TrustistEcommerceClient::class, function ($app) {
            return new TrustistEcommerceClient(
                config('trustist.client_id'),
                config('trustist.private_key'),
                config('trustist.environment')
            );
        });
    }
}
?>

Add to config/trustist.php:

<?php
return [
    'client_id' => env('TRUSTIST_CLIENT_ID'),
    'private_key' => env('TRUSTIST_PRIVATE_KEY'),
    'environment' => env('TRUSTIST_ENV', 'sandbox'),
];
?>

Best Practices

  • Never expose API credentials in your code or version control
  • Use environment variables for sensitive configuration
  • Always verify payment status server-side before fulfilling orders
  • Implement error handling with try-catch blocks
  • Set up webhooks for real-time payment notifications
  • Log errors for debugging and monitoring

Error Handling

<?php
try {
    $payment = $trustist->createPayment(99.99, 'ORDER-12345', $returnUrl);
} catch (GuzzleHttp\\Exception\\ClientException $e) {
    // 4xx errors (bad request, unauthorized, etc.)
    $response = $e->getResponse();
    $body = json_decode($response->getBody(), true);
    error_log("Client error: " . $body['message']);
} catch (GuzzleHttp\\Exception\\ServerException $e) {
    // 5xx errors (server errors)
    error_log("Server error: " . $e->getMessage());
} catch (Exception $e) {
    // Other errors
    error_log("Unexpected error: " . $e->getMessage());
}
?>

Next Steps