Sample Code

Tokenization

Overview

In this section, we provide sample codes for:


Tokenization

<?php

/* ------------------------ Configurations ---------------------------------- */
//Test
$apiURL = 'https://apitest.myfatoorah.com';
$apiKey = ''; //Test token value to be placed here: https://myfatoorah.readme.io/docs/test-token

//Live
//$apiURL = 'https://api.myfatoorah.com';
//$apiKey = ''; //Live token value to be placed here: https://myfatoorah.readme.io/docs/live-token


/* ------------------------ Call InitiatePayment Endpoint ------------------- */
//Fill POST fields array
$ipPostFields = ['InvoiceAmount' => 100, 'CurrencyIso' => 'KWD'];

//Call endpoint
$paymentMethods = initiatePayment($apiURL, $apiKey, $ipPostFields);

//You can save $paymentMethods information in database to be used later
$paymentMethodId = 20;
/*foreach ($paymentMethods as $pm) {
    if ($pm->PaymentMethodEn == 'Visa/Master Direct (Token/Recurring)' && $pm->IsDirectPayment) {
        $paymentMethodId = $pm->PaymentMethodId;
        break;
    }
}*/

/* ------------------------ Call ExecutePayment Endpoint -------------------- */
//Fill customer address array
/* $customerAddress = array(
  'Block'               => 'Blk #', //optional
  'Street'              => 'Str', //optional
  'HouseBuildingNo'     => 'Bldng #', //optional
  'Address'             => 'Addr', //optional
  'AddressInstructions' => 'More Address Instructions', //optional
  ); */

//Fill invoice item array
/* $invoiceItems[] = [
  'ItemName'  => 'Item Name', //ISBAN, or SKU
  'Quantity'  => '2', //Item's quantity
  'UnitPrice' => '25', //Price per item
  ]; */

//Fill POST fields array
$postFields = [
    //Fill required data
    'paymentMethodId' => $paymentMethodId,
    'InvoiceValue'    => '50',
    'CallBackUrl'     => 'https://example.com/callback.php',
    'ErrorUrl'        => 'https://example.com/callback.php', //or 'https://example.com/error.php'    
        //Fill optional data
        //'CustomerName'       => 'fname lname',
        //'DisplayCurrencyIso' => 'KWD',
        //'MobileCountryCode'  => '+965',
        //'CustomerMobile'     => '1234567890',
        //'CustomerEmail'      => '[email protected]',
        //'Language'           => 'en', //or 'ar'
        //'CustomerReference'  => 'orderId',
        //'CustomerCivilId'    => 'CivilId',
        //'UserDefinedField'   => 'This could be string, number, or array',
        //'ExpiryDate'         => '', //The Invoice expires after 3 days by default. Use 'Y-m-d\TH:i:s' format in the 'Asia/Kuwait' time zone.
        //'SourceInfo'         => 'Pure PHP', //For example: (Laravel/Yii API Ver2.0 integration)
        //'CustomerAddress'    => $customerAddress,
        //'InvoiceItems'       => $invoiceItems,
];

//Call endpoint
$data = executePayment($apiURL, $apiKey, $postFields);

//You can save payment data in database as per your needs
$invoiceId  = $data->InvoiceId;
$paymentURL = $data->PaymentURL;


/* ------------------------ Get Tokenization ID ----------------------------- */
session_start();
if (empty($_SESSION['TKN_ID'])) {

    //Fill POST fields array
    $tokenizationInfo = [
        'PaymentType' => 'card',
        'Bypass3DS'   => true,
        'SaveToken'   => true,
        'Card'        => [
            'Number'         => '5453010000095539',
            'ExpiryMonth'    => '12',
            'ExpiryYear'     => '25',
            'SecurityCode'   => '212',
            'CardHolderName' => 'fname lname'
    ]];

    //Call endpoint
    $tokenizationData = directPayment($paymentURL, $apiKey, $tokenizationInfo);

    //You can save payment data in database as per your needs
    $paymentId      = $tokenizationData->PaymentId;
    $tokenizationId = $tokenizationData->Token;

    //Save the tokenization ID in a SECURE place to do payments with the same card information later
    //For test purpose, it will be saved in session (Not SECURE)
    $_SESSION['TKN_ID'] = $tokenizationId;

    //Display the payment result to your customer
    echo "Your Payment is done successfully with payment ID: $paymentId, and invoice ID: $invoiceId.";
    die;
}


/* ------------------------ Call DirectPayment Endpoint --------------------- */
//Fill POST fields array
$cardInfo = [
    'PaymentType' => 'token',
    'token'       => $_SESSION['TKN_ID'],
    'Card'        => [
        'SecurityCode' => '212',
    ]
];

//Call endpoint
$directData = directPayment($paymentURL, $apiKey, $cardInfo);

//You can save payment data in database as per your needs
$paymentId = $directData->PaymentId;

//Display the payment result to your customer
echo "Your Payment with tokenization is done successfully with payment ID: $paymentId, and invoice ID: $invoiceId.";
die;


/* ------------------------ Functions --------------------------------------- */
/*
 * Initiate Payment Endpoint Function 
 */

function initiatePayment($apiURL, $apiKey, $postFields) {

    $json = callAPI("$apiURL/v2/InitiatePayment", $apiKey, $postFields);
    return $json->Data->PaymentMethods;
}

//------------------------------------------------------------------------------
/*
 * Execute Payment Endpoint Function 
 */

function executePayment($apiURL, $apiKey, $postFields) {

    $json = callAPI("$apiURL/v2/ExecutePayment", $apiKey, $postFields);
    return $json->Data;
}

//------------------------------------------------------------------------------
/*
 * Direct Payment Endpoint Function 
 */

function directPayment($paymentURL, $apiKey, $postFields) {

    $json = callAPI($paymentURL, $apiKey, $postFields);
    return $json->Data;
}

//------------------------------------------------------------------------------
/*
 * Call API Endpoint Function
 */

function callAPI($endpointURL, $apiKey, $postFields) {

    $curl = curl_init($endpointURL);
    curl_setopt_array($curl, array(
        CURLOPT_CUSTOMREQUEST  => "POST",
        CURLOPT_POSTFIELDS     => json_encode($postFields),
        CURLOPT_HTTPHEADER     => array("Authorization: Bearer $apiKey", 'Content-Type: application/json'),
        CURLOPT_RETURNTRANSFER => true,
    ));

    $response = curl_exec($curl);
    $curlErr  = curl_error($curl);

    curl_close($curl);

    if ($curlErr) {
        //Curl is not working in your server
        die("Curl Error: $curlErr");
    }

    $error = handleError($response);
    if ($error) {
        die("Error: $error");
    }

    return json_decode($response);
}

//------------------------------------------------------------------------------
/*
 * Handle Endpoint Errors Function 
 */

function handleError($response) {

    $json = json_decode($response);
    if (isset($json->IsSuccess) && $json->IsSuccess == true) {
        return null;
    }

    //Check for the errors
    if (isset($json->ValidationErrors) || isset($json->FieldsErrors)) {
        $errorsObj = isset($json->ValidationErrors) ? $json->ValidationErrors : $json->FieldsErrors;
        $blogDatas = array_column($errorsObj, 'Error', 'Name');

        $error = implode(', ', array_map(function ($k, $v) {
                    return "$k: $v";
                }, array_keys($blogDatas), array_values($blogDatas)));
    } else if (isset($json->Data->ErrorMessage)) {
        $error = $json->Data->ErrorMessage;
    }

    if (empty($error)) {
        $error = (isset($json->Message)) ? $json->Message : (!empty($response) ? $response : 'API key or API URL is not correct');
    }

    return $error;
}

/* -------------------------------------------------------------------------- */
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Threading.Tasks;

namespace Tokenization
{
    class Program
    {
        // You can get test token from this page  https://myfatoorah.readme.io/docs/test-token
        static string token = "";
        static string baseURL = "https://apitest.myfatoorah.com";

        static async Task Main(string[] args)
        {
            // get token from direct payment api
            // use the token in the second Payment
            string token = "{token}";
            //get direct payment url from execute payment for payment method support direct payment
            // url will be like https://apitest.myfatoorah.com/v2/DirectPayment/0106266521736/48
            string directPaymentUrl = "{directpaymenturl}";
            var payWithTokenResponse = await DirectPaymentByToken(directPaymentUrl, token).ConfigureAwait(false);
            Console.WriteLine("Direct Payment by token Response :");
            Console.WriteLine(payWithTokenResponse);
          
            Console.ReadLine();
        }
        public static async Task<string> DirectPaymentByToken(string paymentUrl,string token)
        {
            var directPaymentRequest = new
            {
                PaymentType = "token",
                Token = token,
                Card = new
                {
                    SecurityCode = "100",
                },
            };

            var directPaymentRequestJSON = JsonConvert.SerializeObject(directPaymentRequest);
            return await PerformRequest(directPaymentRequestJSON, url: paymentUrl).ConfigureAwait(false);
        }

        public static async Task<string> PerformRequest(string requestJSON, string url = "", string endPoint = "")
        {
            if (string.IsNullOrEmpty(url))
                url = baseURL + $"/v2/{endPoint}";

            HttpClient client = new HttpClient();
            client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
            client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token);
            var httpContent = new StringContent(requestJSON, System.Text.Encoding.UTF8, "application/json");
            var responseMessage = await client.PostAsync(url, httpContent).ConfigureAwait(false);
            string response = string.Empty;
            if (!responseMessage.IsSuccessStatusCode)
            {
                response = JsonConvert.SerializeObject(new
                {
                    IsSuccess = false,
                    Message = responseMessage.StatusCode.ToString()
                });
            }
            else
            {
                response = await responseMessage.Content.ReadAsStringAsync();
            }

            return response;
        }
    }
}
# Tokenization

# Import required libraries (make sure it is installed!)
import requests
import json
import sys

# Define Functions

def check_data(key, response_data):
    if key in response_data.keys() and response_data[key] is not None:
        return True
    else:
        return False


# Error Handle Function
def handle_response(response):
    if response.text == "":  # In case of empty response
        raise Exception("API key is not correct")

    response_data = response.json()
    response_keys = response_data.keys()

    if "IsSuccess" in response_keys and response_data["IsSuccess"] is True:
        return  # Successful
    elif check_data("ValidationErrors", response_data):
        error = []
        for i in range(len(response.json()["ValidationErrors"])):
            v_error = [response_data["ValidationErrors"][i].get(key) for key in ["Name", "Error"]]
            error.append(v_error)
    elif check_data("ErrorMessage", response_data):
        error = response_data["ErrorMessage"]
    elif check_data("Message", response_data):
        error = response_data["Message"]
    elif check_data("ErrorMessage", response_data["Data"]):
        error = response_data["Data"]["ErrorMessage"]
    else:
        error = "An Error has occurred. API response: " + response.text
    raise Exception(error)


# Call API Function
def call_api(api_url, api_key, request_data, request_type="POST"):
    request_data = json.dumps(request_data)
    headers = {"Content-Type": "application/json", "Authorization": "Bearer " + api_key}
    response = requests.request(request_type, api_url, data=request_data, headers=headers)
    handle_response(response)
    return response



# Initiate Payment endpoint Function
def initiate_payment(initiatepay_request):
    api_url = base_url + "/v2/InitiatePayment"
    initiatepay_response = call_api(api_url, api_key, initiatepay_request).json()
    payment_methods = initiatepay_response["Data"]["PaymentMethods"]
    # Initiate Payment output if successful
    #print("Payment Methods: ", payment_methods)
    return payment_methods


# Execute Payment endpoint Function
def execute_payment(executepay_request):
    api_url = base_url + "/v2/ExecutePayment"
    executepay_response = call_api(api_url, api_key, executepay_request).json()
    invoice_id = executepay_response["Data"]["InvoiceId"]
    invoice_url = executepay_response["Data"]["PaymentURL"]
    # Execute Payment output if successful
    #print("InvoiceId: ", invoice_id,
    #      "\nInvoiceURL: ", invoice_url)
    return invoice_id, invoice_url


# Direct Payment endpoint Function
# The payment link from execute payment is used as the API for direct payment
def direct_payment(directpay_request, invoice_url):
    directpay_response = call_api(invoice_url, api_key, directpay_request).json()
    directpay_status = directpay_response["Data"]
    # Direct Payment output if successful
    print("Direct Payment Status: ", directpay_status)
    return directpay_status


# Cancel Token
def cancel_token(token):
    api_url = base_url + "/v2/CancelToken?token=" + token
    cancel_token_response = call_api(api_url, api_key, initiatepay_request).json()
    print(cancel_token_response)
    return cancel_token_response


# Test Environment
base_url = "https://apitest.myfatoorah.com"
api_key = "mytokenvalue"  # Test token value to be placed here: https:#myfatoorah.readme.io/docs/test-token

# Live Environment
# base_url = "https:#api.myfatoorah.com"
# api_key = "mytokenvalue" #Live token value to be placed here: https:#myfatoorah.readme.io/docs/live-token



# Initaite Payment request data
initiatepay_request = {
                      "InvoiceAmount": 100,
                      "CurrencyIso": "KWD"
                    }

try:
    # Getting the value of payment Method Id
    payment_method = initiate_payment(initiatepay_request)

    payment_method_list = []
    for item in range(len(payment_method)):
        if payment_method[item]["IsDirectPayment"] == True:
            y = [payment_method[item]["PaymentMethodEn"], payment_method[item]["PaymentMethodId"]]
            payment_method_list.append(y)
    print(payment_method_list)
    while True:
        payment_method_id = input("Kindly enter the number equivalent to the required payment method: ")
        try:
            if int(payment_method_id) in [el[1] for el in payment_method_list]:
                break
            else:
                print("Kindly enter a correct direct payment method id")
        except:
            print("The input must be a number")



    # Execute Payment Request
    executepay_request = {
                         "paymentMethodId" : payment_method_id,
                         "InvoiceValue"    : 50,
                         "CallBackUrl"     : "https://example.com/callback.php",
                         "ErrorUrl"        : "https://example.com/callback.php",
                    # Fill optional data
                         # "CustomerName"       : "fname lname",
                         # "DisplayCurrencyIso" : "KWD",
                         # "MobileCountryCode"  : "+965",
                         # "CustomerMobile"     : "1234567890",
                         # "CustomerEmail"      : "[email protected]",
                         # "Language"           : "en", #or "ar"
                         # "CustomerReference"  : "orderId",
                         # "CustomerCivilId"    : "CivilId",
                         # "UserDefinedField"   : "This could be string, number, or array",
                         # "ExpiryDate"         : "", # The Invoice expires after 3 days by default. Use "Y-m-d\TH:i:s" format in the "Asia/Kuwait" time zone.
                         # "SourceInfo"         : "Pure PHP", #For example: (Laravel/Yii API Ver2.0 integration)
                         # "CustomerAddress"    : $customerAddress,
                         # "InvoiceItems"       : $invoiceItems,
                         }

    # Execute payment t get Invoice Id and Invoice URL
    invoice_id, invoice_url = execute_payment(executepay_request)

    # Required Data for direct Payment
    directpay_request = {
                            "PaymentType": "card",
                            "Bypass3DS": False,
                            "SaveToken": True,
                            "Token": "string",
                            "Card": {
                                "Number": "5123450000000008",
                                "ExpiryMonth": "05",
                                "ExpiryYear": "21",
                                "SecurityCode": "100",
                                "CardHolderName": "fname lname"
                            }
                    }

    response_directpay = direct_payment(directpay_request, invoice_url)

    if directpay_request["SaveToken"] == True:
        saved_token = response_directpay["Token"]

        directpay_request2 = {
                            "PaymentType": "token",
                            "Bypass3DS": False,
                            "Token": saved_token,
                            "Card": {
                                "SecurityCode": "100",
                                #"CardHolderName": "fname lname"
                            }
                    }
        direct_payment(directpay_request2, invoice_url)
    #cancel_token(saved_token)
except:
    ex_type, ex_value, ex_traceback = sys.exc_info()
    print("Exception type : %s " % ex_type.__name__)
    print("Exception message : %s" % ex_value)




# Test Card Data for Visa/Master
# {
# "PaymentType": "card",
# "Bypass3DS": False,
# "SaveToken": False,
# "Card": {
#       "Number": "5453010000095539",
#       "ExpiryMonth": "12",
#       "ExpiryYear": "25",
#       "SecurityCode": "300",
#      }
#      }

Cancel Card Token

<?php

/* ------------------------ Configurations ---------------------------------- */
//Test
$apiURL = 'https://apitest.myfatoorah.com';
$apiKey = ''; //Test token value to be placed here: https://myfatoorah.readme.io/docs/test-token

//Live
//$apiURL = 'https://api.myfatoorah.com';
//$apiKey = ''; //Live token value to be placed here: https://myfatoorah.readme.io/docs/live-token


/* ------------------------ Call CancelToken Endpoint ------------ */
//Recurring ID should be saved previosly in a secure place to be used here in cancel request
$token = 'TOKEN2439';

$json = callAPI("$apiURL/v2/CancelToken?token=$token", $apiKey);
echo "<pre/>";
print_r($json);


/* ------------------------ Functions --------------------------------------- */
/*
 * Call API Endpoint Function
 */

function callAPI($endpointURL, $apiKey, $postFields = []) {

    $curl = curl_init($endpointURL);
    curl_setopt_array($curl, array(
        CURLOPT_CUSTOMREQUEST  => 'POST',
        CURLOPT_POSTFIELDS     => json_encode($postFields),
        CURLOPT_HTTPHEADER     => array("Authorization: Bearer $apiKey", 'Content-Type: application/json'),
        CURLOPT_RETURNTRANSFER => true,
    ));

    $response = curl_exec($curl);
    $curlErr  = curl_error($curl);

    curl_close($curl);

    if ($curlErr) {
        //Curl is not working in your server
        die("Curl Error: $curlErr");
    }

    $error = handleError($response);
    if ($error) {
        die("Error: $error");
    }

    return json_decode($response);
}

//------------------------------------------------------------------------------
/*
 * Handle Endpoint Errors Function 
 */

function handleError($response) {

    $json = json_decode($response);
    if (isset($json->IsSuccess) && $json->IsSuccess == true) {
        return null;
    }

    //Check for the errors
    if (isset($json->ValidationErrors) || isset($json->FieldsErrors)) {
        $errorsObj = isset($json->ValidationErrors) ? $json->ValidationErrors : $json->FieldsErrors;
        $blogDatas = array_column($errorsObj, 'Error', 'Name');

        $error = implode(', ', array_map(function ($k, $v) {
                    return "$k: $v";
                }, array_keys($blogDatas), array_values($blogDatas)));
    } else if (isset($json->Data->ErrorMessage)) {
        $error = $json->Data->ErrorMessage;
    }

    if (empty($error)) {
        $error = (isset($json->Message)) ? $json->Message : (!empty($response) ? $response : 'API key or API URL is not correct');
    }

    return $error;
}

/* -------------------------------------------------------------------------- */
using Newtonsoft.Json;
using System;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Threading.Tasks;

namespace CancelToken
{
    class Program
    {

        // You can get test token from this page  https://myfatoorah.readme.io/docs/test-token
        static string token = "";
        static string baseURL = "https://apitest.myfatoorah.com";
        static async Task Main(string[] args)
        {
            string paymentToken = "{token}";//replace with valid token like TOKEN2471
            Console.WriteLine($"Cancel  for Token : {paymentToken} ");
            
            var cancelTokenResponse = await CancelToken(paymentToken).ConfigureAwait(false);
            Console.WriteLine("Cancel Token Response :");
            Console.WriteLine(cancelTokenResponse);
           
            Console.ReadLine();
        }
        public static async Task<string> CancelToken(string paymentToken)
        {
            string url = baseURL + $"/v2/CancelToken?token={paymentToken}";

            HttpClient client = new HttpClient();
            client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
            client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token);
            var responseMessage = await client.PostAsync(url, null).ConfigureAwait(false);
            string response = string.Empty;
            if (!responseMessage.IsSuccessStatusCode)
            {
                response = JsonConvert.SerializeObject(new
                {
                    IsSuccess = false,
                    Message = responseMessage.StatusCode.ToString()
                });
            }
            else
            {
                response = await responseMessage.Content.ReadAsStringAsync();
            }

            return response;
        }
    }
}

Did this page help you?