Direct Support Site

Results for

icon-search-large No search results yet
Enter your search query above

1. Introduction

To create payments, you need to link your server to our platform via one of our integration modes.
Our PHP SDK library is the ideal solution to connect to our platform if you prefer to do so with your own stand-alone system using PHP language.

Choosing the PHP SDK, you can:

To take full advantage of this SDK, make sure you meet these requirements:

  • PHP 5.4 or higher
  • Strongly recommended: Installation of the composer tool

You can download and install the latest version of the PHP SDK by:

  • Using the Git system available on GitHub
  • Installing the code provided by Composer
  • Installing our library manually on your system

Find more details on GitHub. Also, check out all available SDK objects and properties in our Full API Reference. Once you are all set, read the next chapters on how to prepare and use the SDK.

This guide provides a general overview on the SDK’s functionalities. To see how they precisely work for the different integration modes, see the dedicated guides explaining every step with full code samples:

Target most up-to-date API base URL

We encourage you to always target the most up-to-date API base URL when sending requests to our platform. Have a look at our dedicated guides for a full overview:

To allow you a smooth transition, previous API base URLs remain available until further notice.

2. Initialise SDK

To connect your system to our platform by using the SDK, you need to initialise it at first.

Initialising requires you to

  • Create a test/live account
  • Create an API Key and API Secret for the PSPID you wish to use for transaction processing
  • Initialise an instance of Client using the API Key/API Secret to set up the connection to our test/live platform

    Remember to pay attention to the environment you get the key set from. API Key and API Secret are different for test and live environments.

    The full path of the API endpoint for the test/live environment is

    • https://payment.preprod.direct.worldline-solutions.com/v2/
    • https://payment.direct.worldline-solutions.com/v2/


    As our SDKs always implement the latest version of our API, you can leave out "v2" in your code as shown in the example above

After initialisation, you can start processing transactions via your PSPID. Learn how this works in the dedicated chapter.

Have a look at the code sample covering the steps mentioned above:

Make sure to use the following classes:

  • DefaultConnection
  • CommunicatorConfiguration
  • Communicator
  • Client
  • ProxyConfiguration

$connection = new DefaultConnection();

// Your PSPID in either our test or live environment
$merchantId = "PSPID";

// Put the value of the API Key which you can find in the Merchant Portal
// https://secure.ogone.com/Ncol/Test/Backoffice/login/
$apiKey = 'API KEY'; 

// Put the value of the API Secret which you can find in the Merchant Portal
// https://secure.ogone.com/Ncol/Prod/BackOffice/login/
$apiSecret = 'API Secret';   
 
// This endpoint is pointing to the TEST server 
// Note: Use the endpoint without the /v2/ part here
$apiEndpoint = 'https://payment.preprod.direct.worldline-solutions.com';

// Additional settings to easily identify your company in our logs.
$integrator = 'YOUR COMPANY NAME';
 
$proxyConfiguration = null;
/* 
* To use proxy, you should uncomment the section below
* and replace proper settings with your settings of the proxy.
* (additionally, you can comment on the previous setting).
*/
/* 
$proxyConfiguration = new ProxyConfiguration(
    'proxyHost', 
    'proxyPort', 
    'proxyUserName', 
    'proxyPassword'
);
*/
$communicatorConfiguration = new CommunicatorConfiguration(
    $apiKey,
    $apiSecret,
    $apiEndpoint,
    $integrator,
    $proxyConfiguration
);
 
$communicator = new Communicator($connection, $communicatorConfiguration);

$client = new Client($communicator);

$merchantClient = $client->merchant($merchantId);

If you are ready to switch to the live environment, substitute the endpoint link apiEndpoint = 'https://payment.preprod.direct.worldline-solutions.com' for the live environment apiEndpoint = 'https://payment.direct.worldline-solutions.com/'

The following table provides an overview of the arguments accepted by the individual instances:

Properties
  • string $merchantId: Your PSPID in either our test environment/live environment. Make sure to use the correct apiKey / apiSecret together with the conjoining PSPID for your transactions request
  • string $apiKey: The API Key you have defined in your PSPID to which you will send the transactions to
  • string $apiSecret: The API Secret you have defined in your PSPID to which you will send the transactions to

    Check out our dedicated guide to learn all about $apiKey / $apiSecret

  • string $apiEndpoint: It contains a link to either our test or live environment where your transaction requests are sent to

    The full path of the of API endpoint for test/live environment is

    • https://payment.preprod.direct.worldline-solutions.com/v2/
    • https://payment.direct.worldline-solutions.com/v2/

    respectively. As our SDKs always implement the latest version of our API, you can leave out "v2" in your code as shown in the example above

  • string $integrator: Your (company) name or any unique identifier. We can use the value for debugging and tracking request you have sent to our platform. Therefore, we strongly suggest sending a value we can identify your requests easily in our logs
You can re-use a Client instance for different calls. You can use

  • The MerchantClient class object initialised in the example for all calls for that PSPID 
    By calling this line of the code, you will obtain the MerchantClient object:
    $client->merchant($merchantId)
    
  • The Client instance to create MerchantClients for different (or the same) PSPIDs


After you have initialised the SDK, you can send requests to our platform via your PSPID. Learn how to do this in the next chapter.

For transactions with no financial impact, use TEST-URL. The transactions will be sent to our test environment, thereby to your test account

For transactions with a financial impact, use the LIVE-URL. The transactions will be sent to our live environment, thereby to your live account

3. Use SDK

After the successful initialisation of the Client instance, you gain full access to our RESTful API. It enables you to:

  • Send requests for new transactions for any of our server integration modes
  • Get your transactions’ current status
  • Perform maintenance requests (i.e., captures, refunds) on existing transactions

Make sure that the payment method you would like to use is active in your test/live account. Check in the Back Office via Configuration > Payment methods 

Check out our test cases in GitHub, including full code samples, and our Full API Reference to learn what is possible.

Below you may find some of the most common actions you can perform.

Create new transactions

To create a new transaction, you can use either the Client or MerchantClient instance for any of our integration modes to create a new transaction. It can be done through: 

  • Routing the request to your PSPID on our platform (for Client)
  • Creating a request for the respective integration mode

The SDK instance only keeps track of the data used to initialise it. It does not track neither active sessions nor previous requests. Your system is responsible for managing Direct sessions and payments

Sessions and payments do not impact other sessions and payments

Below you can find code samples related to particular integration modes:

Hosted Checkout Page

To use this integration mode, you need to create a CreateHostedCheckoutRequest call. It must contain at least an Order object.

Make sure to use the following classes:
  • CreateHostedCheckoutRequests
  • Order
  • AmountOfMoney


/* *…. Initialisation.... */ $merchantClient = $client->merchant($merchantId); /* * The HostedCheckoutClient object based on the MerchantClient * object created during initialisation */ $hostedCheckoutClient = $merchantClient->hostedCheckout(); $createHostedCheckoutRequest = new CreateHostedCheckoutRequest(); $order = new Order(); // Example object of the AmountOfMoney $amountOfMoney = new AmountOfMoney(); $amountOfMoney->setCurrencyCode("EUR"); $amountOfMoney->setAmount(100); $order->setAmountOfMoney($amountOfMoney); $createHostedCheckoutRequest->setOrder($order); // Get the response for the HostedCheckoutClient $createHostedCheckoutResponse = $hostedCheckoutClient->createHostedCheckout( $createHostedCheckoutRequest );

You can specify an optional returnUrl, which will be used to redirect your customer back to your website

This call returns a CreateHostedCheckoutResponse response. Store the hostedCheckoutId and RETURNMAC it contains, as well as any other information relevant for you. You will need these for steps described in the following chapters.

This response also contains a partialRedirectURL.

You have to concatenate the base URL "https://payment." with partialRedirectURL according to the formula

https://payment. + partialRedirectURL

and perform a redirection of your customer to this URL. Once the customer visits the Hosted Checkout Page, the payment process continues there.

The newest version of our SDK also returns the full path in redirectURL, allowing you to skip concatenate the base URL "https://payment." with partialRedirectURL. Learn more more in our  Hosted Checkout Page guide. 

Hosted Tokenization Page

To use this integration method, you need to

Make sure to use the following classes:
  • CreateHostedTokenizationRequest

/* 
 *…. Initialisation....
 */

$merchantClient = $client->merchant($merchantId);

/*
 * The HostedTokenizationClient object based on the   
 * MerchantClient object created during initialisation 
 */
$hostedTokenizationClient = 
$merchantClient->hostedTokenization();

$createHostedTokenizationRequest = 
new CreateHostedTokenizationRequest();

// Set your template
$createHostedTokenizationRequest->setVariant(
"my-custom-template.html"
);

// Get the response for the HostedTokenizationClient
$createHostedTokenizationResponse = $hostedTokenizationClient
->createHostedTokenization(
$createHostedTokenizationRequest
);

From CreateHostedTokenizationResponse retrieve hostedTokenizationId as $hostedTokenizationId and partialRedirectUrl as $partialRedirectUrl. Use the  partialRedirectUrl for the iframe and the $hostedTokenizationId  or $tokenId (see infobox) to create the actual payment via Server-to-server integration mode.

You can send either the tokenID or the hostedTokenizationId in your CreatePayment request. Learn more about using either option in the dedicated chapters of our Hosted Tokenization Page guide:

$hostedTokenizationId = $createHostedCheckoutResponse->getHostedTokenizationId(); 
$partialRedirectUrl = $createHostedCheckoutResponse->getPartialRedirectUrl(); 
$createPaymentRequest = new CreatePaymentRequest(); 
 
$order = new Order(); 
 
$amountOfMoney = new AmountOfMoney(); 
$amountOfMoney->setCurrencyCode("EUR"); 
$amountOfMoney->setAmount(100); 
$order->setAmountOfMoney($amountOfMoney); 
 
$createPaymentRequest->setOrder($order);
$cardPaymentMethodSpecificInput = new CardPaymentMethodSpecificInput(); $cardPaymentMethodSpecificInput->setTokenize(true); $cardPaymentMethodSpecificInput->setToken($hostedTokenizationId); $createPaymentRequest->setCardPaymentMethodSpecificInput( $cardPaymentMethodSpecificInput ); // Get the response for the PaymentsClient $createPaymentResponse = $paymentsClient->createPayment($createPaymentRequest);

Server-to-server

A minimum paymentResponse requires you to set at least an Order object and a payment method:

Make sure to use the following classes:
  • CreatePaymentRequest
  • AmountOfMoney
  • Card
  • CardPaymentMethodSpecificInput
  • Order

/* 
 *…. Initialisation....
 */

$merchantClient = $client->merchant($merchantId);

/*
 * The PaymentsClient object based on the MerchantClient  
 * object created in initialisation 
 */
$paymentsClient = $merchantClient->payments();

$createPaymentRequest = new CreatePaymentRequest(); 

$order = new Order();

// Example object of the AmountOfMoney 
$amountOfMoney = new AmountOfMoney();
$amountOfMoney->setCurrencyCode("EUR");
$amountOfMoney->setAmount(100);
$order->setAmountOfMoney($amountOfMoney);

$createPaymentRequest->setOrder($order);
$cardPaymentMethodSpecificInput = new CardPaymentMethodSpecificInput(); // Example object of the Card $card = new Card(); $card->setCvv("123"); $card->setCardNumber("4111111111111111"); // // Find more test data here $card->setExpiryDate("1236"); $card->setCardholderName("Wile E. Coyote"); $cardPaymentMethodSpecificInput->setCard($card); $createPaymentRequest->setCardPaymentMethodSpecificInput( $cardPaymentMethodSpecificInput ); // Get the response for the PaymentsClient $createPaymentResponse = $paymentsClient->createPayment($createPaymentRequest);

We have dedicated guides for each of the aforementioned integration modes:

The documents contain all crucial details you need to profit from the integration modes’ full potential, including full transaction flows, code samples and other useful features

Get transaction status

Our RESTful API allows you to request a transaction’s status anytime by one of our GET calls:

A GetPayment request looks like this: 


$merchantClient = $client->merchant($merchantId);

// Get the response for the PaymentsClient
$createPaymentResponse = 
$paymentsClient->createPayment($createPaymentRequest);

// Here you get $paymentId that you can use in further code
$paymentID = $createPaymentResponse->getPayment()->getId();

// Get the PaymentResponse object with status information
// concerning payment of the given ID
$paymentResponse = $merchantClient
->payments()
->getPayment($paymentID);
Properties
string $paymentID: The 10-digit unique reference of your transaction on our platform. This reference can be retrieved from the CreatePaymentResponse or createHostedCheckoutResponse created in the previous section.

For more information about statuses visit the status documentation page.

Perform maintenance operation

To perform follow-up actions on existing transactions (i.e. captures or refunds), use our CapturePayment or RefundPayment API call respectively:

CapturePayment

Make sure to use the following classes:

  • CapturePaymentRequest

/* 
 *…. Initialisation....
 */

$merchantClient = $client->merchant($merchantId);

/*
 * . ...
 */

// Here you get $paymentId that you can use in further code
$paymentID = $createPaymentResponse->getPayment()->getId();

/*
 * . ...
 */

$capturePaymentRequest = new CapturePaymentRequest();
$capturePaymentRequest->setAmount(100);
$capturePaymentRequest->setIsFinal(true);

// Get CaptureResponse object
$captureResponse = $merchantClient
->payments()
->capturePayment(
$paymentID, 
$capturePaymentRequest
);

RefundPayment

Make sure to use the following classes:

  • RefundRequest
  • AmountOfMoney

/*  
 *…. Initialisation.... 
 */ 
 
$merchantClient = $client->merchant($merchantId); 

/* 
 * . ... 
 */ 

// Here you get $paymentId you can use in further code 
$paymentID = $createPaymentResponse->getPayment()->getId(); 

/* 
 * . ... 
 */ 

$refundRequest = new RefundRequest(); 

$amountOfMoney = new AmountOfMoney(); 
$amountOfMoney->setCurrencyCode("EUR"); 
$amountOfMoney->setAmount(100); 

$refundRequest->setAmountOfMoney($amountOfMoney); 


// Get RefundResponse object 
$refundResponse = $merchantClient 

	->payments() 
	->refundPayment( 
		$paymentID,  
		$refundRequest 
	); 
Properties
string $paymentID: The 10-digit unique reference of your transaction on our platform. This reference can be retrieved from the CreatePaymentResponse or createHostedCheckoutResponse created in the previous section.

4. Handle exceptions

If a transaction is rejected, our platform provides detailed information with an Exception instance. The affiliated HTTP status code also help you troubleshoot the error.

You can encounter two types of exceptions: transaction exceptions and HTTP exceptions.

Transaction exceptions

This kind of exception refers to transaction requests that are technically correct but were rejected by your customer’s issuer or your acquirer. If the transaction is returned in the exception then, it was created in our systems but not successfully processed.

The following code samples use implicit methods provided as an example. You are expected to provide your own implementation for these or replace them with similar logic

Exception type /
HTTP status code
Code Sample
Rejected transactions / 
Various(see PaymentResponse object)
/* * Initialization.... */

$paymentID = "";
$createPaymentRequest = new CreateRequest();

try {
     $createPaymentResponse =
         $paymentsClient->createPayment( $createPaymentRequest );
     $paymentID = $createPaymentResponse ->getPayment()->getId();
     }
catch (DeclinedPaymentException $e) {
     $paymentResult = $e->getPaymentResult();
     $payment = $paymentResult->getPayment();
     handleError($payment);
     return;
     }
$paymentResponse = $merchantClient
    ->payments()->getPayment($paymentID);

// Your code to check transaction status and // handle errors
if (isNotSuccessful($paymentResponse)) {
    handleError($paymentResponse);
}
Rejected Refund /
Various(see PaymentResponse object)
/* * Initialization.... */

$paymentID = $createPaymentResponse
   ->getPayment()->getId();

$refundID = "";

$refundRequest = new CreateRequest();

try {
     // Get the RefundResponse object
     $refundResponse = $merchantClient
        ->payments()
        ->refundPayment(
             $paymentID,
             $refundRequest
         );

      $refundID = $refundResponse->getId();
    }
catch (DeclinedRefundException $e) {
    $refundResult = $e->getRefundResult();
    handleError($refundResult);
    return;
}

$refundResponse = $merchantClient
    ->payments()
    ->refundPayment($paymentID, $refundRequest);

// Your code to check transaction status and
// handle errors
if (isNotSuccessful($refundResponse, $refundID)) {
   handleError($refundResponse);
}

HTTP exceptions

This kind of exception refers to various problems caused by technical errors in the API call or payment request.

You can combine any of the following code snippets with this standard CreatePayment request:

Make sure to use the following classes:
  • ApiException

/* 
 *…. Initialisation....
 */

$createPaymentRequest = new CreatePaymentRequest(); 

$order = new Order();

// The example object of the AmountOfMoney 
$amountOfMoney = new AmountOfMoney();
$amountOfMoney->setCurrencyCode("EUR");
$amountOfMoney->setAmount(100);
$order->setAmountOfMoney($amountOfMoney);
 
$createPaymentRequest->setOrder($order);
$cardPaymentMethodSpecificInput = new CardPaymentMethodSpecificInput(); // The example object of the Card – you can find test cards on // https://support.direct.ingenico.com/documentation/test-cases/ $card = new Card(); $card->setCvv("123"); $card->setCardNumber("4111111111111111"); $card->setExpiryDate("1236"); $card->setCardholderName("Wile E. Coyote"); $cardPaymentMethodSpecificInput->setCard($card); $createPaymentRequest->setCardPaymentMethodSpecificInput( $cardPaymentMethodSpecificInput ); try { // Get the response for the PaymentsClient $createPaymentResponse = $paymentsClient ->createPayment($createPaymentRequest); } catch (ApiException $e) { // refer to the list below to see how specific // implementations of ApiException can be handled. }

Exception type / 
HTTP status code
Code Sample
ValidationException
400
catch (ValidationException $e) {
    $message = 'Input validation error:' . PHP_EOL;
    foreach ($e->getErrors() as $error) {
        $message .= '- ';
        if (!empty($error->getPropertyName())) {
            $message .= $error->getPropertyName() . ': ';
        }
        $message .= $error->getMessage();
        $message .= '(' . $error->getCode() . ')' . PHP_EOL;
    }
    // Do something with $message
}
AuthorizationException / 
403
catch (AuthorizationException $e) {
    $message = 'Authorization error:' . PHP_EOL;
    foreach ($e->getErrors() as $error) {
       $message .= '- ' . $error->getMessage();
       $message .= '(' . $error->getCode() . ')' . PHP_EOL;
    }
    // Do something with $message
}
IdempotenceException
409
catch (IdempotenceException $exception) {
    $message = 'Idempotence error:' . PHP_EOL;
    foreach ($e->getErrors() as $error) {
       $message .= '- ' . $error->getMessage();
       $message .= '(' . $error->getCode() . ')' . PHP_EOL;
    }
    // Do something with $message
}
ReferenceException
404/409/410
catch (ReferenceException $e) {
    $message = 'Incorrect object reference:' . PHP_EOL;
    foreach ($e->getErrors() as $error) {
       $message .= '- ' . $error->getMessage();
       $message .= '(' . $error->getCode() . ')' . PHP_EOL;
    }
// Do something with $message }
DirectException
500/502/503
catch (DirectException $e) {
    $message = 'Error occurred at Direct or ';
    $message .= 'a downstream partner/acquirer:' . PHP_EOL;
    foreach ($e->getErrors() as $error) {
       $message .= '- ' . $error->getMessage();
       $message .= '(' . $error->getCode() . ')' . PHP_EOL;
    }
    // Do something with $message
}
ApiException /
Any other codes
catch (ApiException $e) {
    $message = 'Unexpected error:' . PHP_EOL;
    foreach ($e->getErrors() as $error) {
       $message .= '- ' . $error->getMessage();
       $message .= '(' . $error->getCode() . ')' . PHP_EOL;
    }
// Do something with $message
}

HTTP status codes 

All our exceptions are linked to one or more HTTP status codes, indicating the root cause for many possible errors.

Status code Description Exception type
200

Successful
Our platform processed your request correctly

-
201

Created
Our platform processed your request correctly and created a new resource. We return the URI of this resource in the Location header of the response

-
204

No content
Our platform processed your request correctly

-
Various
paymentResult key is in the response

Payment Rejected
Either our platform or one of our downstream partners/acquirers rejected your request

DeclinedPaymentException
Various
payoutResult key is in the response

Payout Rejected
Either our platform or one of our downstream partners/acquirers rejected your request

DeclinedPayoutException

Various
refundResult key is in the response

Refund Rejected
Either our platform or one of our downstream partners/acquirers rejected your request

DeclinedRefundException
400

Bad Request
Your request contains errors, thus our platform cannot process it

ValidationException
403

Not Authorised
You are trying to do something that is not allowed or that you are not authorised to do

AuthorizationException
404

Not Found
The object you were trying to access could not be found on the server

ReferenceException
409

Conflict
Your idempotent request resulted in a conflict because of either: 

  • The first request has not finished yet
  • Your request resulted in a conflict. Either you submitted a duplicate request, or you are trying to create something with a duplicate key

IdempotenceException
ReferenceException

410

Gone
The object that you are trying to reach has been removed.

ReferenceException
500

Internal Server Error
An error occurred on our platform

DirectException
502 Bad Gateway
Our platform was unable to process a message from a downstream partner/acquirer
DirectException
503 Service Unavailable
The service that you are trying to reach is temporarily unavailable. Please try again later
DirectException
Other Unexpected error
An unexpected error has occurred
ApiException

5. Use additional features

The SDK has a lot more to offer. Have a look at the following features, as they will help you build the perfect solution.

Get available payment methods

Before you initiate the actual payment process, you should send a GetPaymentProducts request to our platform. The response contains a list of available payment methods in your PSPID. Depending on your customers’ preferences, you can offer a selection on our Hosted Checkout Page or on your own webshop environment using subsequent CreatePayment requests.

Make sure to use the following classes:
  • GetPaymentProductsParams

/* 
 *…. Initialisation....
 */

$merchantClient = $client->merchant($merchantId);

// Prepare the request to get all active payment methods in your PSPID
$queryParams = new GetPaymentProductsParams();

// Example params
$queryParams->setCountryCode("BE");
$queryParams->setCurrencyCode("EUR");

// Send the request and get the response
$paymentProductsResponse = $merchantClient
    ->products()
    ->getPaymentProducts($queryParams);

Send idempotent requests

One of the main REST API features is its ability to detect and prevent sending requests (i.e. payment requests) accidentally twice. The SDK makes it very easy for you to ensure that you send only unique – idempotent – requests to our platform.

Use the additional argument CallContext and set its property named $idempotenceKey by call setIdempotenceKey() setter on the object previously created and call the CreatePayment API function. The SDK will send an X-GCS-Idempotence-Key header with the idempotence key as its value.

If you send requests this way to our platform, we will check the following

  • If you send subsequent request with the same idempotence key, the response contains an X-GCS-Idempotence-Request-Timestamp header. The SDK will set the $idempotenceRequestTimestamp property of the CallContext argument
  • If the first request is not finished yet, the RESTful Server API returns a  409 status code. Then the SDK throws an IdempotenceException with the original idempotence key and the idempotence request timestamp
Make sure to use the following classes:
  • CallContext
  • IdempotenceException

/* 
 *…. Initialisation....
 */

$merchantClient = $client->merchant($merchantId);

$createPaymentRequest = new CreatePaymentRequest();

$idempotenceKey = "YourKeyForThePayment";
 
$callContext = new CallContext();
$callContext->setIdempotenceKey($idempotenceKey);

try {
    $createPaymentResponse = $merchantClient
        ->payments()
        ->createPayment(
            $createPaymentRequest, 
            $callContext
        );
} catch (IdempotenceException $e) {
    // a request with the same $idempotenceKey is still in progress, try again after a short pause
    // $e->getIdempotenceRequestTimestamp() contains the value of the
    // X-GCS-Idempotence-Request-Timestamp header
} finally {
    $idempotenceRequestTimestamp = 
        $callContext->getIdempotenceRequestTimestamp();
    // $idempotenceRequestTimestamp contains the value of the
    // X-GCS-Idempotence-Request-Timestamp header
    // if $idempotenceRequestTimestamp is not empty, this was not the first request
}

If an idempotence key is sent for a call that does not support idempotence, the RESTful Server API will ignore the key and treat the request as a first request.


Use logging

The SDK supports logging of requests, responses, and exceptions. These can be helpful for troubleshooting or tracing individual steps in the payment flow.
The SDK offers two implementations of the logging feature:

  • SplFileObjectLogger (by use of SplFileObject)
  • ResourceLogger
Make sure to use the following classes:
  • ResourceLogger

You can enable/ disable the logging by calling:


/* 
 *…. Initialisation....
 */

$client = new Client($communicator);

// You can enter a file pointer of the file you 
// would like to save data to instead of STDOUT
$logger = new ResourceLogger(STDOUT); 
$client->enableLogging($logger); 
//... Do some calls 
$client->disableLogging();
The SDK obfuscates sensitive data in the logger

Connection pooling

You can manage your network resources by limiting the number of possible connections the SDK creates and maintains. The Client instances created as discussed in the Initialise SDK chapter will have their own connection pool. The Client instances created with the same Communicator object share a connection pool.

If you use multiple Client instances to share a single connection pool, make sure to follow these steps:

  1. Create a shared Communicator
  2. Create Client instances with that Communicator

/* 
 *…. Initialisation....
 */

// Create CommunicatorConfiguration instance 
// with proper settings
$sharedCommunicatorConfiguration = 
new CommunicatorConfiguration(
    $apiKey,
    $apiSecret,
    $apiEndpoint,
    $integrator,
    $proxyConfiguration
);
 
$connection = new DefaultConnection();

// Communicator instance
$communicator = new Communicator(
$connection, 
$sharedCommunicatorConfiguration
);
 
$client1 = new Client($communicator);
$client2 = new Client($communicator);

Customise communication

The Client instances use an Communicator instance to communicate with our platform. Whereas, Communicator uses Connection to perform the actual HTTP requests and a ConnectionResponse to hold the HTTP response.

Connection and ConnectionResponse are interfaces. The SDK provides a default implementation of those interfaces via the classes DefaultConnection and DefaultConnectionResponse.

  • DefaultConnection class uses cURL via the standard PHP/cURL bindings to implement the get(), delete(), post() and put() methods
  • DefaultConnectionResponse offers a straightforward implementation of the getHttpStatusCode(), getHeaders(), getHeaderValue() and getBody() methods, and is used by DefaultConnection

You can provide your own implementation of the interface of Connection to use in Communicator object as for example YourConnection class.


/* 
 *…. Initialisation....
 */

$communicatorConfiguration = 
new CommunicatorConfiguration(
    $apiKey,
    $apiSecret,
    $apiEndpoint,
    $integrator,
    $proxyConfiguration
);

// Use you own implementation of the Connection interface 
$connection = new YourConnection();

// Communicator instance
$communicator = new Communicator(
$connection, 
$communicatorConfiguration
);

Webhooks

The part of the SDK that handles the webhooks support is called the webhooks helper. It transparently handles both validation of signatures against the event bodies sent by the webhooks system (including finding the secret key for key IDs - not to be confused with the API Key and API Secret), and unmarshalling of these bodies to objects. This allows you to focus on the essentials, without going through all the additional information and extracting the desired ones by yourself. To learn more about webhooks, read our dedicated guide. 

Provide secret keys

Configure the "WebhooksKey" / "WebhooksKeySecret" and your server webhooks endpoints in the Merchant Portal:


$keyId = "WebhooksKey";
$secretKey = "WebhooksKeySecret";

Secret keys are provided using a function that takes two arguments:

  • The key ID to return the secret key for
  • A callback function that either takes an error as its first argument, or the secret key for the given key ID as its second argument (in which case the first argument must be null)

The SDK provides one implementation for this function: InMemorySecretKeyStore::getSecretKey($keyId). This will retrieve secret keys from an in-memory key store for proper $keyId.

Keys can be added or removed using the following functions:

  • InMemorySecretKeyStore::storeSecretKey($keyId, $secretKey) to store a secret key for a key ID
  • InMemorySecretKeyStore::removeSecretKey($keyId) to remove the stored secret key for a key ID
  • InMemorySecretKeyStore::clear() to remove all stored secret keys

If more advanced storage is required, e.g. using a database or file system, we recommend writing your own implementation.

Initialise webhooks helper

Include and initialise the webhooks helper as follows:


$keyId = 'dummy-key-id';
$secretKey = 'dummy-secret-key’';
$secretKeys = array(
   $keyId => $secretKey
);
$secretKeyStore = new InMemorySecretKeyStore($secretKeys);
// At this moment $secretKeys are stored because they are given to constructor
// but you can set empty array of $secretKeys and after that you can 
// manage InMemorySecretKeyStore functions as mentioned above 
// or even you can extend InMemorySecretKeyStore class to 
// implement your own methods to manage $secretKeys
$helper = new WebhooksHelper($secretKeyStore);

Use webhooks helper

From an entry point that you have created on your own, call the unmarshal method of the webhooks helper. It takes the following arguments:

  • The body, as a string or Buffer. This should be the raw body as received from the webhooks system
  • An object containing the request headers as received from the webhooks system. The keys should be the header names

// Initialisation
$bodyOfRequest = 'JSON_Body_Of_The_Request';
$signatureHeader = 'X-GCS-Signature'; // This should be as it is
$keyIdHeader = 'X-GCS-KeyId'; // This should be as it is

$hash_hmac = hash_hmac("sha256", $bodyOfRequest, $secretKey, true);
$signature = base64_encode($hash_hmac);

$requestHeaders = array(
   $signatureHeader => $signature,
   $keyIdHeader => $keyId
);
try {
    $helper->unmarshal($bodyOfRequest, $requestHeaders);
} catch (SignatureValidationException $e) {
    // Do something with this exception
}