Skip to main content

Comcarde PHP Server SDK

Server SDK for creating Payments via Comcarde REST API from a PHP Server.

Requirements#

Overview#

overview diagram

  1. Gather payment details from your client.
  2. Create a Payment using comcarde-php Server SDK.

Install#

Installing the SDK can be done using Composer Dependency Manager for PHP.

Initialize a Composer project (skip this step if you already have a composer.json):

composer init

Add comcarde-php as a private composer repository:

composer config repositories.comcarde-php vcs git@bitbucket.org:comcarde/comcarde-php.git

Add comcarde/comcarde-php as a requirement, for example:

composer require comcarde/comcarde-php:1.14.0

Getting Started#

Before you begin, you will need a Server API Key.

Note: Server API Keys MUST only be used in your secure back-end services, and must not be exposed to client applications.

Please follow the installation procedure and then run the following:

<?phprequire_once(__DIR__ . '/vendor/autoload.php');
/** * https://sandbox.comcarde.com for sandbox testing * https://secure.comcarde.com for production */$apiUrl = "<<API_URL>>";
/* * Your API Key provided by Comcarde, prefixed with "Bearer " * e.g. "Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9" */$authorization = "Bearer <<API_KEY>>";
$comcardeApi = new \Comcarde\ComcardeApi();$payment = new \Comcarde\Client\Model\Payment();$result = $comcardeApi->makePayment($apiUrl, $authorization, $payment);
?>

The Payment Object#

A payment request to be routed to an appropriate Payment Service Provider (PSP), which in turn connects you to the broader financial system.

$payment = new \Comcarde\Model\Payment();

Order Code#

A unique code for your customer’s order that this payment request relates to.

$payment->setCustomerOrderCode("...");

Order Description#

A description for what the payment is for

$payment->setOrderDescription("...");

Currency Code#

ISO 4217 currency code for the payment.

$payment->setCurrencyCode("GBP");

Amount#

The value of the amount of the payment to be made, specified by calling setAmount() on the Payment object, should be a whole number not more than fifteen digits representing the amount in the lowest denomination of the currency being used.

For example:

$payment->setCurrencyCode("GBP");$payment->setAmount(12500);

The above code snippet defines a Payment with an amount of 12,500 pence, or £125.00.

Customer Email Address#

The email address of your customer.

$payment->setCustomerEmail("example@email.com");

Payment Instrument#

The following types of payment instruments are supported:

$payment->setPaymentInstrument($paymentInstrument);

Tokenized Payment Instrument#

A payment instrument such as a card can be tokenized via one of our Client SDKs and used as a payment instrument as follows:

$paymentInstrument = new \Comcarde\Model\Tokenized();$paymentInstrument->setToken('abcd-1234-efgh-5678');$payment->setPaymentInstrument($paymentInstrument);

Card Payment Instrument#

To make a payment using a card, create a Card object and pass it as an argument to Payment's setPaymentInstrument() method:

$cardPaymentInstrument = new \Comcarde\Model\Card();$cardPaymentInstrument->setPan('4444333322221111');$cardPaymentInstrument->setExpiryDate('12-23');$cardPaymentInstrument->setNameOnCard('JOHN SMITH');$cardPaymentInstrument->setStartDate('10-18');$cardPaymentInstrument->setIssueNumber(1);$payment->setPaymentInstrument($cardPaymentInstrument);

ApplePay Payment Instrument#

Available from version 1.11.0. To make a payment using an ApplePay token, create an ApplePay object and pass it as an argument to Payment's setPaymentInstrument() method:

$applePayPaymentInstrument = new \Comcarde\Model\ApplePay();$applePayPaymentInstrument->setNonce('abcd-1234-efgh');$payment->setPaymentInstrument($applePayPaymentInstrument);

GooglePay Payment Instrument#

Available from version 1.11.0. To make a payment using an GooglePay token, create an GooglePay object and pass it as an argument to Payment's setPaymentInstrument() method:

$googlePayPaymentInstrument = new \Comcarde\Model\GooglePay();$googlePayPaymentInstrument->setNonce('abcd-1234-efgh');$payment->setPaymentInstrument($googlePayPaymentInstrument);

3D Secure Provider3DSecureNonce Payment Instrument#

Available from version 1.11.0. Described in the 3D Secure section of this document.

Payment Responses#

The response from calling 'ComcardeApi::makePayment' will be an object of type 'ComcardeResponse'. This object contains fields such as 'code' and 'message' which provide information about the outcome of the Payment request:

  • code representing the outcome of the Payment request
  • message a more descriptive message providing information about the outcome of the Payment request
  • id representing the interaction with Comcarde's system when making the payment request. This is required to contact Comcarde in case of any queries regarding the payment.
  • paymentId representing the payment in Comcarde's system.
  • token the tokenized version of the payment instrument, if the payment was made with a non-tokenized payment instrument such as a Card but the payment request indicated the Card should be tokenized as part of the payment.
  • validationErrors if the payment fails because of some invalid request data that cannot be caught by the PHP SDK, further details of the validation errors will be provided by this field.
  • threeDSecureAction in the case of 3D Secure payments, further action may need to be taken to complete the payment. See the section on 3D Secure later in this document. Available from version 1.11.0.

An example of accessing these fields in the ComcardeResponse object is given below:

$paymentResponse = $comcardeApi->makePayment($apiUrl, $authorization, $payment);$code = $response->getCode();$message = $response->getMessage();$id = $response->getId();$paymentId = $response->getPaymentId();print "Payment response code: ".$code."\n";print "Payment response message: ".$message."\n";print "Request trace ID: ".$id."\n";print "Payment ID: ".$paymentId."\n";

Payment Response Indicating Successful Payment#

A code of 1000 in the ComcardeResponse indicates that the payment was successful. In this case, the output from the above code snippet might be something like:

Payment response code: 1000Payment response message: ApprovedRequest trace ID: eb69d2573fe0a0bePayment ID: 38c30100-a58e-4690-a096-12e7ce745259

Payment Response Indicating Unsuccessful Payment#

A code of 4000+ in the ComcardeResponse indicates that the payment was unsuccessful. The exact code relates to the cause of the failure. A description of that failure cause is given by the message field. In such a situation, the output from the code snippet above might be something like:

Payment response code: 4202Payment response message: Transaction Error: Insufficient fundsRequest trace ID: eb69d2573fe0a0bePayment ID: 38c30100-a58e-4690-a096-12e7ce745259

See Comcarde Response Codes for documentation about all the possible response codes that could be returned in the response.

Validation Errors#

If a payment request was rejected by Comcarde because of a request validation error that could not be caught by the SDK, the details of the validation errors will be accessible through the ComcardeResponse's 'validationErrors' field. This is a map where the key is the name of the request field that was invalid, and the value is the list of validation errors for that request field. An example of inspecting the validationErrors field is given below:

$paymentResponse = $comcardeApi->makePayment($apiUrl, $authorization, $payment);$code = $response->getCode();$message = $response->getMessage();$validationErrors = $response->getValidationErrors();print "Payment response code: ".$code."\n";print "Payment response message: ".$message."\n";print "Validation error: ".$validationErrors['billingAddress'][0]."\n";

The above code snippet might produce output like:

Payment response code: 4000Payment response message: Request Error: The request is invalidValidation error: 4041302 - The value entered for Billing Address is incorrect. Total address length (address1,address2, address3,town) should be no more than 255 characters.

A list of the numeric codes together with their default descriptions can be found here: Validation Errors.

Exceptions Thrown By The SDK#

Functions in the SDK can throw an exception if an error occurs.

InvalidArgumentException#

An InvalidArgumentException is thrown if an invalid value is passed to one of the setter functions when constructing the Payment request. The SDK attempts to validate as many of the request fields as possible to give instant feedback if something is not correct (but some validation constraints can only be validated by Comcarde's back-end, see the section on Validation Errors in the Payment Response for more information).

The InvalidArgumentException contains two fields:

  • code: A unique numeric code representing the specific validation error that occurred on a specific field.
  • message: A human-readable description of the validation error.

An example of catching and inspecting an InvalidArgumentException is given below:

try {    $payment->setAmount(123.45); // an invalid amount    $response = $comcardeApi->makePayment($paymentsApiUrl, $authorization, $payment);} catch (InvalidArgumentException $e) {    print 'An InvalidArgumentException was thrown: Code: '.$e->getCode().' Message: '.$e->getMessage();}

The above code snippet would output the following:

An InvalidArgumentException was thrown: Code: 4040204 Message: The value entered for Amount is incorrect. Pleaseenter an amount that is a whole number.

The value of the 'message' field in the exception that describes the validation error acts as a sensible default. However it may be desirable to override this default and map the unique numeric code to a different description string.

A list of the numeric codes together with their default descriptions can be found here: Validation Errors.

Note: In version 1.0.0 the exception object only contains a message.

ApiException#

An ApiException is thrown when some other kind of error has occurred in the SDK during the processing of a request. An example of catching and inspecting an ApiException is given below:

try {    $response = $comcardeApi->makePayment('', $authorization, $payment);} catch (Comcarde\ApiException $e) {    print 'An ApiException was thrown: '.$e->getMessage();}

The above code snippet would output the following:

An ApiException was thrown: API URL must be supplied

3D Secure#

Available from version 1.11.0. By default, 3D Secure is applied to all Payment requests, which may result in a 2001: 3D Secure action required response. This indicates that the additional data has to be gathered from the client via one of our Client SDKs in order to complete the transaction.

$response = $comcardeApi->makePayment(...);if ($response->getCode() == '2001') {    // send content $response->getThreeDSecureAction() to your client}

Payment Object 3D Secure Required Flag#

You can opt-out on a per-payment basis via the setThreeDSecureRequired flag.

$payment->setThreeDSecureRequired(false);

Provider3DSecureNonce Payment Instrument#

In the event of the Comcarde REST API responding with 2001: 3D Secure action required, which indicates that the additional data has to be gathered from the client, our Client SDKs provide functionality to convert the action into a nonce which can be used to finalize the payment.

$paymentInstrument = new \Comcarde\Model\ProviderThreeDSecureNonce();$paymentInstrument->setNonce('BR#abcd-1234-...'); // nonce generated by a client SDK$payment->setPaymentId('e68f966a-9c3d-...'); // returned by the original payment request$payment->setPaymentInstrument($paymentInstrument);

The default behavior will be to fail the payment if 3D Secure authentication fails. However, you can opt-out of this via the setThreeDSecureRequired flag.

$payment->setThreeDSecureRequired(false);

WARNING: This should only be set to false if you are willing to accept liability for a payment that has failed a 3D Secure challenge.

We cannot guarantee that the PSP will allow processing of payments that have failed 3D Secure, but we will attempt to process this request where possible.

3D Secure Options#

Some PSPs allow you to pass parameters to indicate your preferences relating to 3DS.

Note: We cannot guarantee that downstream PSPs will honour your preferences, but we can ensure that your preferences are passed on wherever possible.

$threeDSecureOptions = new \Comcarde\Model\ThreeDSecureOptions();$threeDSecureOptions->setExemptionRequested(true);$threeDSecureOptions->setExemptionRequested(false);$payment->setThreeDSecureOptions($threeDSecureOptions);

3D Secure Option: Exception Requested#

$threeDSecureOptions->setExemptionRequested(true);

Indicates that you want the Payment Request to be exempted from 3D Secure.

3D Secure Option: Challenge Requested#

$threeDSecureOptions->setChallengeRequested(true);

Indicates that you want the Payment Request to not enter the 3DS Frictionless Flow.

Browser Data#

With some Payment Service Providers, you can increase the chance that your payment will enter the 3DS Frictionless Flow by including additional information about the card holders browser with initial the Payment request.

$browserData = new \Comcarde\Model\BrowserData();
/* * The following data should be collected from the Cardholders browser */
$browserData->setColorDepth('32');   // screen.colorDepth property$browserData->setJavaEnabled(true);  // navigator.javaEnabled() property$browserData->setLanguage('EN_en');  // navigator.language property$browserData->setScreenHeight(1024); // screen.height property$browserData->setScreenWidth(2048);  // screen.width property$browserData->setTimeZone(0);        // JavaScript getTimezoneOffset() Method
/* * The following data should be collected from the HTTP request made * from the cardholders browser to the merchant */
// Exact content of the HTTP accept headers$browserData->setAcceptHeader('application/json');// Exact content of the HTTP user-agent header$browserData->setUserAgent('Mozilla/5.0 (Windows NT 6.1; Win64; x64)');
$payment->setBrowserData($browserData);

Refunding a Payment#

Refund previously made payments, either partially or in full. The payment to be refunded is identified by the paymentId field in the ComcardeResponse object from the original payment request

If the Refund object's amount field is given a value, only that partial amount of the original payment will be refunded. If this amount exceeds the amount of the original payment, an error will be returned. An example of a partial refund is given below:

$refund = new \Comcarde\Model\Refund();$refund->setAmount(80);$refundResponse = $comcardeApi->makeRefund($apiUrl, $authorization, $paymentId, $refund);

If the Refund object's amount field is not set, then the entire amount of the original payent will be refunded. An example of a full refund is given below:

$refund = new \Comcarde\Model\Refund();$refundResponse = $comcardeApi->makeRefund($apiUrl, $authorization, $paymentId, $refund);

Refund Responses#

The 'makeRefund' function will return an object of type ComcardeResponse, of the same form as returned by a Payment request. It too has fields such as code and message which can indicate the success or failure of the Refund request.

$refundResponse = $comcardeApi->makeRefund($apiUrl, $authorization, $paymentId, $refund);$code = $refundResponse->getCode();$message = $refundResponse->getMessage();$id = $refundResponse->getId();

If the code is 1000, then the refund was successful.

If the code is not 1000, then the refund was unsuccessful. This could be because the payment was previously refunded in full, or the amount set in the Refund object is too large, or some other reason. The message field will provide more information about the cause of the failure. A list of possible causes of refund failure can be found in the Comcarde Response Codes page.

Retrieving tokenized cards#

Available from version 1.11.0. It is possible to save and tokenize a payment instrument such as a card via one of our Client SDKs, and make payments with the resulting token in the future. Tokenized cards can be optionally linked to the id of the merchant's customer who owns the card.

It is possible to retrieve the details of saved tokenized cards using the PHP SDK. Tokenized cards can be retrieved by one of two methods:

  • by comma-separated list of tokens
  • by case-sensitive customer identifier

An example of retrieving tokenized cards by comma-separated list of tokens:

$comcardeApi = new \Comcarde\ComcardeApi();$result = $comcardeApi->getTokenizedCardsByTokens($tokenApiUrl, $authorization,        '98d52626-bf0c-4b4b-8df0-57fd16f93495,94759e61-ead8-4f55-864a-200b358e6920');

An example of retrieving tokenized cards by case-sensitive customer identifier:

$comcardeApi = new \Comcarde\ComcardeApi();$result = $comcardeApi->getTokenizedCardsByCustomerId($tokenApiUrl, $authorization, 'cust01234');

In both cases the $result object is of type ResponseMap_ObfuscatedSavedCard. This object contains a variable, $results, which is a map of ObfuscatedSavedCard objects keyed by token. You can use the getter functions in these classes to access the details:

$savedCards = $result->getResults();// $savedCards will be a standard PHP map keyed by the token so you can access the card details using the PHP [] notation$savedCard = $savedCards['98d52626-bf0c-4b4b-8df0-57fd16f93495'];$savedCardPan = $savedCard->getPan();$savedCardOwner = $savedCard->getNameOnCard();$savedCardType = $savedCard->getCardType();

Note that the retrieved card details will only hold the card PAN in obfuscated form, such as "** ** **** 1111".

Further Documentation#

Additional documentation on API endpoints and models can be found in the comcarde-php repository.

Test cards are available for use in our Sandbox environment on our Testing page.