Sample Code | Direct Payment

DirectPayment

As described earlier for the Direct Payment, we are going to have a sample code to consume this endpoint to make a successful integration.

<?php

/* For simplicity check our PHP SDK library here https://myfatoorah.readme.io/php-library */

//PHP Notice:  To enable MyFatoorah auto-update, kindly give the write/read permissions to the library folder
//use zip file
include 'myfatoorah-library-2.2/MyfatoorahLoader.php';
include 'myfatoorah-library-2.2/MyfatoorahLibrary.php';

//use composer
//require 'vendor/autoload.php';
//use MyFatoorah\Library\MyFatoorah;
//use MyFatoorah\Library\API\Payment\MyFatoorahPayment;

/* --------------------------- Configurations ------------------------------- */
//Test
$mfConfig = [
    /**
     * API Token Key (string)
     * Accepted value:
     * Live Token: https://myfatoorah.readme.io/docs/live-token
     * Test Token: https://myfatoorah.readme.io/docs/test-token
     */
    'apiKey' => '',
    /*
     * Vendor Country ISO Code (string)
     * Accepted value: KWT, SAU, ARE, QAT, BHR, OMN, JOD, or EGY. Check https://docs.myfatoorah.com/docs/iso-lookups
     */
    'vcCode' => 'KWT',
    /**
     * Test Mode (boolean)
     * Accepted value: true for the test mode or false for the live mode
     */
    'isTest' => true,
];

/* --------------------------- InitiatePayment Endpoint --------------------- */
$invoiceValue       = 50;
$displayCurrencyIso = 'KWD';

//------------- Post Fields -------------------------
//Check https://docs.myfatoorah.com/docs/initiate-payment#request-model
//------------- Call the Endpoint -------------------------
try {
    $mfObj          = new MyFatoorahPayment($mfConfig);
    $paymentMethods = $mfObj->initiatePayment($invoiceValue, $displayCurrencyIso);
} catch (Exception $ex) {
    echo $ex->getMessage();
    die;
}


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

/* --------------------------- 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 suppliers array
/* $suppliers = [
  [
  'SupplierCode'  => 1,
  'InvoiceShare'  => '2',
  'ProposedShare' => null,
  ]
  ]; */

//Parse the phone string
$phone = MyFatoorah::getPhone('+965 123456789');

//------------- Post Fields -------------------------
//Check https://docs.myfatoorah.com/docs/execute-payment#request-model
$postFields = [
    //Fill required data
    'InvoiceValue'    => $invoiceValue,
    'PaymentMethodId' => $paymentMethodId,
        //Fill optional data
        //'CustomerName'       => 'fname lname',
        //'DisplayCurrencyIso' => $displayCurrencyIso,
        //'MobileCountryCode'  => $phone[0],
        //'CustomerMobile'     => $phone[1],
        //'CustomerEmail'      => '[email protected]',
        //'CallBackUrl'        => 'https://example.com/callback.php',
        //'ErrorUrl'           => 'https://example.com/callback.php', //or 'https://example.com/error.php' 
        //'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.
        //'CustomerAddress'    => $customerAddress,
        //'InvoiceItems'       => $invoiceItems,
        //'Suppliers'          => $suppliers,
];

//------------- Call the Endpoint -------------------------
try {
    $mfObj = new MyFatoorahPayment($mfConfig);
    $data  = $mfObj->executePayment($postFields);

    //You can save payment data in database as per your needs
    $invoiceId   = $data->InvoiceId;
    $paymentLink = $data->PaymentURL;
} catch (Exception $ex) {
    echo $ex->getMessage();
    die;
}

/* --------------------------- DirectPayment Endpoint ----------------------- */
//------------- Post Fields -------------------------
$cardInfo = [
    'PaymentType' => 'card',
    'Bypass3DS'   => false,
    'Card'        => [
        'Number'         => '5123450000000008',
        'ExpiryMonth'    => '05',
        'ExpiryYear'     => '21',
        'SecurityCode'   => '100',
        'CardHolderName' => 'fname lname'
    ]
];

//------------- Call the Endpoint -------------------------
try {
    $mfObj = new MyFatoorah($mfConfig);
    $json  = $mfObj->callAPI($paymentLink, $cardInfo);

    //You can save payment data in database as per your needs
    $paymentId = $json->Data->PaymentId;
    $otpLink   = $json->Data->PaymentURL;

    //Display the result to your customer
    //Redirect your customer to complete the payment process
    echo '<h3><u>Summary:</u></h3>';
    echo "To pay the invoice ID <b>$invoiceId</b> and with payment ID: <b>$paymentId</b>, click on:<br>";
    echo "<a href='$otpLink' target='_blank'>$otpLink</a><br><br>";

    echo '<h3><u>DirectPayment Response Object:</u></h3><pre>';
    print_r($json);
    echo '</pre>';

    echo '<h3><u>ExecutePayment Response Data:</u></h3><pre>';
    print_r($data);
    echo '</pre>';

    echo '<h3><u>InitiatePayment Response Data:</u></h3><pre>';
    print_r($paymentMethods);
    echo '</pre>';
} catch (Exception $ex) {
    echo $ex->getMessage();
    die;
}

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

namespace DirectPayment
{
    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 url from execute payment for payment method support direct payment
            // url will be like https://apitest.myfatoorah.com/v2/DirectPayment/0106266521736/48
			var executePaymentEndPoint = "ExecutePayment";
			var excutePaymentRequest = new
			{
				InvoiceValue = 10,
				PaymentMethodId = 20, //Put here payment method id
				// any additional fields
		 
			};		 
			var excutePaymentRequestJSON = JsonConvert.SerializeObject(excutePaymentRequest);
			var executePaymentResponse = await ExecutePayment(requestJSON: excutePaymentRequestJSON, endPoint: executePaymentEndPoint).ConfigureAwait(false);
			Console.WriteLine("ExecutePayment Response :");
			Console.WriteLine(executePaymentResponse);
			
            string paymentUrl = executePaymentResponse.Data.PaymentURL;
            var directPaymentResponse = await DirectPayment(paymentUrl).ConfigureAwait(false);
            Console.WriteLine("Direct Payment Response :");
            Console.WriteLine(directPaymentResponse);
          
            Console.ReadLine();
        }
        public static async Task<string> DirectPayment(string paymentUrl)
        {
            var directPaymentRequest = new
            {
                PaymentType = "Card",
                SaveToken = false,
                Card = new
                {
                    Number = "5123450000000008",
                    ExpiryMonth = "05",
                    ExpiryYear = "21",
                    SecurityCode = "100",
                    HolderName = "holder name"
                },
                Bypass3DS = false,

            };

            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;
        }		
    }   
   
}
# Direct Payment End Point

# 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


# 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)

    # Creating a simplified list for payment methods
    payment_method_list = []
    for item in range(len(payment_method)):
        if payment_method[item]["IsDirectPayment"] == True:
            y = [payment_method[item].get(key) for key in ["PaymentMethodEn", "PaymentMethodId"]]
            payment_method_list.append(y)
    print(payment_method_list)


    # Get the payment method key.
    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 payment method id")
        except:
            print("The input must be a number")

    # Based on the initiate payment response, we select the value of reference number to choose payment method

    # 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": "false",
                            "Token": "string",
                            "Card": {
                                "Number": "5123450000000008",
                                "ExpiryMonth": "05",
                                "ExpiryYear": "21",
                                "SecurityCode": "100",
                                "CardHolderName": "fname lname"
                            }
                    }

    direct_payment(directpay_request, invoice_url)
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",
#      }
#      }
####### Direct Payment ######
require 'net/http'
require 'uri'
require 'json'

uri = URI.parse("https://apitest.myfatoorah.com/v2/ExecutePayment")
token = 'mytokenvalue' #token value to be placed here
header = {'Authorization':token} 

body = {
  'PaymentMethodId': '2',
  'CustomerName': 'Ahmed',
  'DisplayCurrencyIso': 'KWD',
  'MobileCountryCode': '+965',
  'CustomerMobile': '12345678',
  'CustomerEmail': '[email protected]',
  'InvoiceValue': 100,
  'CallBackUrl': 'https://google.com',
  'ErrorUrl': 'https://yahoo.com',
  'Language': 'en',
  'CustomerReference': 'ref 1',
  'CustomerCivilId': 12345678,
  'UserDefinedField': 'Custom field',
  'ExpireDate': '',
  'CustomerAddress': {
    'Block': '',
    'Street': '',
    'HouseBuildingNo': '',
    'Address': '',
    'AddressInstructions': ''
  },
  'InvoiceItems': [
    {
      'ItemName': 'Product 01',
      'Quantity': 1,
      'UnitPrice': 100
    }
  ]
}

# Create the HTTP objects
http = Net::HTTP.new(uri.host, uri.port)
http.use_ssl = true

request = Net::HTTP::Post.new(uri.request_uri, header)
request["Content-Type"] = 'application/json'
request.body = body.to_json


# Send the request
response = http.request(request)
parsed = JSON.parse(response.body)

paymentURL = parsed['Data']['PaymentURL']

 #After getting the payment url call it as a post API and pass card info to it
 #If you have token saved before, send pass it as a token instead


uri = URI.parse(paymentURL)
token = 'mytokenvalue' #token value to be placed here
header = {'Authorization':token} 

body = {'paymentType': 'card','card': {'Number':'5123450000000008','expiryMonth':'05','expiryYear':'21','securityCode':'100'},'saveToken': false}

# Create the HTTP objects
http = Net::HTTP.new(uri.host, uri.port)
http.use_ssl = true

request = Net::HTTP::Post.new(uri.request_uri, header)
request["Content-Type"] = 'application/json'
request.body = body.to_json
# Send the request
response = http.request(request)
puts response.read_body
console.log('#################### Direct Payment ########################');
var request = require("request");
var token = 'mytokenvalue' //token value to be placed here;
var baseURL = 'https://apitest.myfatoorah.com';
var options = { method: 'POST',
  url: baseURL+'/v2/ExecutePayment',
  headers: 
   { Accept: 'application/json',
     Authorization: 'bearer '+token,
     'Content-Type': 'application/json' },
  body: 
   { PaymentMethodId: '2',
     CustomerName: 'Ahmed',
     DisplayCurrencyIso: 'KWD',
     MobileCountryCode: '+965',
     CustomerMobile: '12345678',
     CustomerEmail: '[email protected]',
     InvoiceValue: 100,
     CallBackUrl: 'https://google.com',
     ErrorUrl: 'https://google.com',
     Language: 'en',
     CustomerReference: 'ref 1',
     CustomerCivilId: 12345678,
     UserDefinedField: 'Custom field',
     ExpireDate: '',
     CustomerAddress: 
      { Block: '',
        Street: '',
        HouseBuildingNo: '',
        Address: '',
        AddressInstructions: '' },
     InvoiceItems: [ { ItemName: 'Product 01', Quantity: 1, UnitPrice: 100 } ] },
  json: true };

request(options, function (error, response, body) {
  if (error) throw new Error(error);
  console.log(body);
  var paymentURL = body['Data']['PaymentURL'] ;
  console.log(paymentURL);
  payInvoice(paymentURL);

});

function payInvoice(paymentURL) {
    var options = { method: 'POST',
    url: paymentURL,
    headers: 
     { Accept: 'application/json',
       Authorization: 'bearer '+token,
       'Content-Type': 'application/json' },
    body: 
    {paymentType: 'card',card: {Number:'5123450000000008',expiryMonth:'05',expiryYear:'21',securityCode:'100'},saveToken: false},
    json: true };
  
  request(options, function (error, response, body) {
    if (error) throw new Error(error);
    console.log(body);
  
  });
 }