If this is your first time working with this payment gateway then you are in the right place. This post will show you how to implement the payment flows into your web application and all the parameters used in the curl and web samples will be described as follows.

Getting Started

Read the section below to learn about the various payment options available by Datatrans. Their payment flows is split into three categories: Customer-Initiated Payments, Vendor-Initiated Payments, After The Purchase. In this post we will explain every step and show how to use the API endpoints.

  • Integrations
  • Payment Methods
  • Create a test account
  • Customer Initiated Payments
  • Initialize a transaction
  • After the payment

Integrations

These are the options Datatrans offers to integrate their payment system. We will talk more about the fourth option and explain every single step. You must first create a transaction before using the Redirect or Lightbox integrations.

Redirect & Lightbox

Redirect to the payment page of Datatrans or display their lightbox as an overlay on a page.

Mobile SDK

Use native payment elements for your iOS or Android mobile application.

Secure Fields

More complicated way, but you can use your own design for your payment system.

API Endpoints

Use their API endpoints to process specific payment actions. For production, remove the .sandbox part.

Payment methods

They offer a big list of payment methods. Click here if you want to find test payment details and learn about the specifics of each payment method.

Credit & Debit Cards

They support all international card brands: MasterCard, Visa, American Express, UnionPay, Diners, Discover, JCB, Maestro, etc.

Apple Pay

Apple Pay only works with transactions done with Safari. Any Apple Pay transaction is processed as a card transaction. 

Twint

Twint is a Swiss direct debit payment method that is usually used as a prepaid wallet but it can be linked to a bank account as well.

Google Pay

Google Pay is the payment method of Google. and it works with any browser. Any Google Pay transaction is processed as a card transaction.

PayPal

PayPal is a payment service that allows users to deposit money in their account or connect it to a credit card or bank account.

Amazon Pay

Customers log in to their Amazon account and choose one of the payment options available.

Create a test account

As per usual, you are going to need a test account. You can create one here. Remember your details because to be able to log in again, you are going to need the Login, Username, and Password. For the sake of this tutorial, change the merchant at the top right corner to web. If you want to create a mobile application then change the merchant to mobile sdk. Under UPP Administration (Security) you will find your username (merchantId) and password. These are crucial because without them you won’t be able to initiate payments.

Customer Initiated Payments

They have three integrations available: Redirect, Lightbox, Secure Fields. For the first two, you need to send the request to initialize a transactionId to the init endpoint. For the Secure Fields integration, you need to send the request to initialize a transactionId to their secureFieldsInit endpoint.

  • Redirect
  • Lightbox
  • Secure Fields

For the Redirect integration you just need to redirect the user to this endpoint:

https://pay.sandbox.datatrans.com/v1/start/transactionId

For the Lightbox integration you need to include this JavaScript library (of course, in the footer):

<script src="https://pay.sandbox.datatrans.com/upp/payment/js/datatrans-2.0.0.js">

After the init request is made you will receive a transactionId, use it like this:

payButton.onclick = function() {
      Datatrans.startPayment({
          transactionId: "transactionId"
       });
};

For the Secure Fields integration, include this JavaScript library (of course in the footer):

<script src="https://pay.sandbox.datatrans.com/upp/payment/js/secure-fields-2.0.0.js">

Once you have the transactionId, it’s time to show our payment form. Use custom styles to design it your way.

// WordPress

jQuery(document).ready(function ( $ ) {
    let payment = $('#your-button');

    // let secureFields = new SecureFields();
    let styles = {
        // your style goes here
        // Specific Style for Each Element
        cardNumber: "border: 1px solid #eaeaea; height: 40px; padding: 10px; " +
            "font-size: 18px; color: #818a91; background: #fafafa;",
        cvv: "border: 1px solid #eaeaea; height: 40px; padding: 10px; " +
            "font-size: 18px; color: #818a91; background: #fafafa;",
    };

     secureFields.init(datatrans.transactionId, {
         cardNumber: "cardNumberPlaceholder",
         cvv: "cvvPlaceholder",
     }, {
         styles: styles
     });

     secureFields.on("validate", function (data) {
          // something bad happened
          if (true == data.hasErrors) {
              $('.pe-datatrans-error').html('Please enter valid card information.');
          }
     });

    secureFields.on("success", function (data) {
        if (data.transactionId) {
            submitFormWithCoupon('no', data.cardInfo.brand, data.cardInfo.country);
        } else {
            $('.pe-datatrans-error').html(data);
        }
    });
  
    payment.on('click', '#go', function () {
       secureFields.submit({
            amount: 3000, // ask for the amount in your form
            expm: 12, // ask for the expm in your form
            expy: 21, // ask for the expy in your form
            currency: "EUR",
            returnUrl: 'https://domain.com/thank-you'  // 3D process return URL
       });
    });
  
});

Initialize a transaction

We mentioned two ways to retrieve a transactionId. The first one is using the init endpoint, and the second one is using the secureFieldsInit

For the purpose of this post, we will create a class where all of the necessary endpoints are used and we will explain how to use them. Don’t forget to include the JavaScript libraries as well.

<?php

/**
 * Datatrans class for payments.
 *
 * https://docs.datatrans.ch/docs
 * https://admin.sandbox.datatrans.com/
 * https://testaccount.datatrans.com/testaccounts
 *
 * Class PE_Datatrans
 */
class PE_Datatrans {
    
	public function __construct() {
	      $this->merchantId =  'use-your-merchantId'; // get_option('_pe_dt_merchantId');
	      $this->password = 'use-your-password'; // get_option('_pe_dt_password');
	      $this->refno = rand(5, 10);
	}

	// Use this endpoint, if you want ot use the Redirect and the Lightbox integration
	public function initializeTransaction($amount) {

	      $url = 'https://api.sandbox.datatrans.com/v1/transactions';

	      $postFields = json_encode( array(
		  'amount' => $amount,
		  'currency'  => "CHF",
		  'refno' => $this->refno,
		  'redirect' => [
		    'successUrl' => 'once-the-user-pays-and-it-is-a-success',
		    "cancelUrl" => "canceled-payment",
		    "errorUrl" => "transaction-error"
		  ],
		  // if you have a registration form you can use these fields as well
		  'cusotmer' => [
		      'title' => 'Mr.' // string,
		      'firstName' => 'Projects' // string 
		      'lastName' => 'Engine', // string etc.
		  ],
	      ) );

	      $ch = curl_init();
	      curl_setopt($ch, CURLOPT_URL, $url);
	      curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
	      curl_setopt($ch, CURLOPT_POST, 1);
	      curl_setopt($ch, CURLOPT_POSTFIELDS, $postFields);
	      curl_setopt($ch, CURLOPT_USERPWD, $this->merchantId . ':' . $this->password);
	      curl_setopt($ch, CURLOPT_HTTPHEADER, ['Content-Type: application/json; charset=UTF-8']);

	      $data = json_decode(curl_exec($ch));
	      $result = $data->transactionId;

	      if (curl_errno($ch)) {
		$result = 'Error: ' . curl_error($ch);
	      }

	      curl_close($ch);

	      return $result;
	}

	// If you are using the SecureFields integration, use this endpoint to get the transactionId
	public function initializeTransactionWithSecureFields($amount) {
	      $url = 'https://api.sandbox.datatrans.com/v1/transactions/secureFields';

	      $postFields = json_encode( array(
		  'amount' => $amount,
		  'currency'  => "CHF",
		  'returnUrl' => '/datatrans-payment/',
	      ) );

	      $ch = curl_init();
	      curl_setopt($ch, CURLOPT_URL, $url);
	      curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
	      curl_setopt($ch, CURLOPT_POST, 1);
	      curl_setopt($ch, CURLOPT_POSTFIELDS, $postFields);
	      curl_setopt($ch, CURLOPT_USERPWD, $this->merchantId . ':' . $this->password);
	      curl_setopt($ch, CURLOPT_HTTPHEADER, ['Content-Type: application/json; charset=UTF-8']);

	      $data = json_decode(curl_exec($ch));
	      $result = $data->transactionId;

	      if (curl_errno($ch)) {
		$result = 'Error: ' . curl_error($ch);
	      }

	      curl_close($ch);

	      return $result;
	}

	// If you are using the SecureFields integrration you need to authorize the transaction
	// Use this API endpoint to do that
	// Use the same amount and refno
	// The amount should be decimal number without the comma
	// for example 60.00 should be 6000

	public function authorizeAuthenticatedTransaction($amount, $transactionId) {
	      $url = 'https://api.sandbox.datatrans.com/v1/transactions/' . $transactionId . '/authorize';

	      $postFields = json_encode( array(
		  'refno' => $this->refno,
		  'amount' => $amount,
		  'autoSettle' => true
	      ) );

	      $ch = curl_init();
	      curl_setopt($ch, CURLOPT_URL, $url);
	      curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
	      curl_setopt($ch, CURLOPT_POST, 1);
	      curl_setopt($ch, CURLOPT_USERPWD, $this->merchantId . ':' . $this->password);
	      curl_setopt($ch, CURLOPT_HTTPHEADER, ['Content-Type: application/json; charset=UTF-8']);
	      curl_setopt($ch, CURLOPT_POSTFIELDS, $postFields);

	      $data = json_decode(curl_exec($ch));
	      curl_close($ch);

	      return $data;
	}
	
	/**
	 * Check the status of the transaction.
	 *
	 * @param $transactionId
	 * @return mixed
	 */
   	 public function checkingTheStatusOfATransaction($transactionId) {
	    $ch = curl_init();
	    curl_setopt($ch, CURLOPT_URL, 'https://api.sandbox.datatrans.com/v1/transactions/' . $transactionId);
	    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
	    curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'GET');
	    curl_setopt($ch, CURLOPT_USERPWD, $this->merchantId . ':' . $this->password);

	    $result = curl_exec($ch);
	    $data = json_decode( $result );

	    if (curl_errno($ch)) {
		    echo 'Error:' . curl_error($ch);
	    }

	    curl_close($ch);

	    return $data;
	}
	
	// Remove the sandbox. once you are done with testing and your sure your code is good.
	
}

new PE_Datatrans;

After the payment

To check the status of a transaction and to settle, cancel, or refund it, use the transactionId. Remember, if you are done with coding and you want to receive payment, just remove the .sandbox from the endpoint. Create a base64 encoded value containing the merchantId and password and apply it with your requests in the authorization header.

Important links