Monday, May 20, 2024
HomePHPDatatrans Funds API for Safe Cost

Datatrans Funds API for Safe Cost


by Vincy. Final modified on September twenty eighth, 2022.

Datatrans is among the in style fee gateway methods in Europe for e-commerce web sites. It offers frictionless fee options.

The Datatrans Cost gateway is broadly in style in European nations. Certainly one of my shoppers from Germany required this fee gateway built-in into their on-line store.

On this tutorial, I share the data of integrating Datatrans in a PHP software. It would save the builders time to do analysis with the long-form documentation.

There are lots of integration choices offered by this fee gateway.

  1. Redirect and lightbox
  2. Safe fields
  3. Cellular SDK
  4. API endpoints

On this tutorial, we’ll see the primary integration choice to arrange the Datatrans fee gateway. We have now seen many fee gateway integration examples in PHP within the earlier articles.

A working instance follows helps to know issues simply. Earlier than seeing the instance, get the Datatrans service provider id and password. It is going to be helpful for authentication functions whereas accessing this fee API.

datatrans api payment

Get Datatrans service provider id and password

The next steps result in getting the service provider id and password of your Datatrans account.

    1. Open a Datatrans sandbox account and confirm it through e-mail.
    2. Arrange your account by choosing the username, group title(Login) and password.
    3. After Arrange it’s going to present the next particulars
      • Login credentials.
      • Sandbox URL of the admin dashboard.
      • Datatrans Service provider Id for Internet, Cellular SDK.
    4. Go to the sandbox URL and log in utilizing the credential received in step 3.
    5. Click on Change Service provider and Select service provider to see the dashboard.
    6. Go to UPP Administration -> Safety to repeat the (Marchant Id)Username and Password for API entry.

Once we see CCAvenue fee integration, it additionally listed a couple of steps to get the service provider id from the dashboard.

datatrans merchant account credentials

Utility configuration

This config file is created for this instance to have the API keys used throughout the code.

It configures the URL that must be known as by the DataTrans server after the fee.

Config.php (Configure Datatrans authentication particulars)

<?php
class Config {

    const WEB_ROOT = 'http://localhost/pp-article-code/data-trans/';

    const MERCHANT_ID = 'YOUR_MERCHANT_ID';

    const PASSWORD = 'YOUR_MERCHANT_DASHBOARD_PASSWORD';

    const SUCCESS_URL = Config::WEB_ROOT . 'return.php';

    const CANCEL_URL = Config::WEB_ROOT . 'return.php?standing=cancelled';

    const ERROR_URL = Config::WEB_ROOT . 'return.php?standing=error';
}
?>

Present the “Pay now” choice

First, a touchdown web page reveals a product tile with a fee choice. It would present a “Pay through DataTrans” button within the browser.

On clicking this button, it’s going to name the AJAX script to get the transaction id.

This web page contains the Datatrans JavaScript library to start out fee with the transaction id.

index.php (Product tile with pay button)

<HTML>
<HEAD>
<TITLE>Datatrans Funds API for Safe Cost</TITLE>
<hyperlink rel="stylesheet" kind="textual content/css" href="https://phppot.com/php/datatrans-api-payment/css/model.css">
<script src="https://code.jquery.com/jquery-3.6.0.min.js"
    integrity="sha256-/xUj+3OJU5yExlq6GSYGSHk7tPXikynS7ogEvDej/m4="
    crossorigin="nameless"></script>

</HEAD>
<BODY>

    <div class="container">
        <h1>Datatrans Funds API for Safe Cost</h1>
        <div class="outer-container">
            <img src="picture/digital camera.jpg" alt="digital camera picture">
            <div class="inner-container">

                <p class="text-style">A6900 MirrorLess Digital camera</p>


                <p class="price-color-align">
                    $289.61<enter kind="hidden" title="quantity"
                        id="quantity" worth="289.61" />
                </p>

                <enter kind="button" id="pay-now" class="pay-button"
                    worth="Pay through DataTrans" onClick="provoke()" />
            </div>
        </div>
    </div>
    <script
        src="https://pay.sandbox.datatrans.com/upp/fee/js/datatrans-2.0.0.js"></script>
</BODY>
</HTML>

Get transaction id and proceed with fee through API

The provoke() operate posts the quantity to the PHP file to provoke Datatrans fee.

Because the end result, the PHP will return the transaction id to course of the fee additional.

The proceedPayment() operate calls the Datatrans JavaScript API to start out the fee. It would present a Datatrans overlay with card choices to decide on fee strategies.

index.php (AJAX script to name Datatrans initiation)

operate provoke() {
	$.ajax({
		technique: "POST",
		url: "initialize-datatrans-ajax.php",
		dataType: "JSON",
		knowledge: { "quantity": $("#quantity").val() }
	})
		.carried out(operate(response) {
			if (response.responseType == 'success') {
				proceedPayment(response.transactionId);
			} else {
				alert(response.responseType + ": " + response.message);
			}
		});

};

operate proceedPayment(transactionId) {
	Datatrans.startPayment({
		transactionId: transactionId,
		'opened': operate() { console.log('payment-form opened'); },
		'loaded': operate() { console.log('payment-form loaded'); },
		'closed': operate() { console.log('payment-page closed'); },
		'error': operate() { console.log('error'); }
	});
}

 

Provoke fee transaction to get the Datatrans fee transaction id

This file is the PHP endpoint known as through AJAX script to get the Datatrans transaction id.

It invokes the DatatransPaymentService to put up the cURL request to the Datatrans API. It requested to provoke the fee and receives the transaction id from the Datatrans server.

This output shall be learn within the AJAX success callback to start out the fee through the JavaScript library.

initialize-datatrans-ajax.php

<?php
require_once 'DatatransPaymentService.php';
$dataTransPaymentService = new DatatransPaymentService();
$quantity = $_POST["amount"];
$orderId = rand();
$end result = $dataTransPaymentService->initializeTransaction($quantity, $orderId);
print $end result;
?>

Datatrans fee transaction service to name API through PHP cURL

This service name accommodates the initializeTransaction() technique which prepares the cURL request in PHP to the Datatrans API.

It handed the quantity, forex and extra particulars to the API endpoint to request the transaction id.

DatatransPaymentService.php

<?php

class DatatransPaymentService
{
    public operate initializeTransaction($quantity, $orderId)
    {
        $url="https://api.sandbox.datatrans.com/v1/transactions";

        require_once __DIR__ . '/Config.php';

        $quantity = $quantity * 100;

        $postFields = json_encode(array(
            'quantity' => $quantity,
            'forex' => "USD",
            'refno' => $orderId,
            'redirect' => [
                'successUrl' => Config::SUCCESS_URL,
                "cancelUrl" => Config::CANCEL_URL,
                "errorUrl" => Config::ERROR_URL
            ]
        ));

        $key = Config::MERCHANT_ID . ':' . Config::PASSWORD;
        $keyBase64 = base64_encode($key);

        $ch = curl_init();

        curl_setopt_array($ch, array(
            CURLOPT_URL => $url,
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_CUSTOMREQUEST => "POST",
            CURLOPT_POSTFIELDS => $postFields,
            CURLOPT_HTTPAUTH => CURLAUTH_BASIC,
            CURLOPT_HTTPHEADER => array(
                "Authorization: Fundamental " . $keyBase64,
                "Content material-Kind: software/json"
            )
        ));

        $curlResponse = curl_exec($ch);

        $curlJSONObject = json_decode($curlResponse);

        if (empty($curlResponse)) {
            $curlError = curl_error($ch);
        } else if (! empty($curlJSONObject->error)) {
            $curlError = $curlJSONObject->error->code . ": " . $curlJSONObject->error->message;
        }
        curl_close($ch);

        if (empty($curlJSONObject->transactionId)) {
            $end result = array(
                'responseType' => "Error",
                'message' => $curlError
            );
        } else {
            $end result = array(
                'responseType' => "success",
                'transactionId' => $curlJSONObject->transactionId
            );
        }

        $end result = json_encode($end result);

        return $end result;
    }
}
?>

Name software URL after fee

return.php

<HTML>
<HEAD>
<TITLE>Datatrans fee standing discover</TITLE>
</HEAD>
<BODY>
    <div class="text-center">
<?php
if (! empty($_GET["status"])) {
    ?>
    <h1>One thing incorrect with the fee course of!</h1>
        <p>Kindly contact admin with the reference of
	your transaction id <?php echo $_GET["datatransTrxId"]; ?></p>
<?php
} else {
    ?>
    <h1>Your order has been positioned</h1>
        <p>We'll contact you shortly.</p>
<?php
}
?>
</div>
</BODY>
</HTML>

Obtain

↑ Again to Prime

RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments