Sample Code

Recurring

Overview

In this section, we provide sample codes for:


Recurring Payment

<?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') {
        $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'
    'RecurringModel'  => [
        'RecurringType' => 'Custom',
        'IntervalDays'  => 180,
        'Iteration'     => 1
    ],
        //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;
$paymentLink = $data->PaymentURL;

//Redirect your customer to the payment page to complete the payment process
//Display the payment link to your customer
echo "Click on <a href='$paymentLink' target='_blank'>$paymentLink</a> to pay with invoiceID $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;
}

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

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

    $curl = curl_init($endpointURL);
    curl_setopt_array($curl, array(
        CURLOPT_CUSTOMREQUEST  => $requestType,
        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 RecurringPayment
{
    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)
        {
            // Execute Payment
            var executeResponse = await ExecutePaymentWithRecurring().ConfigureAwait(false);
            Console.WriteLine("Execute Payment with recurring Response :");
            Console.WriteLine(executeResponse);
        }
        public static async Task<string> ExecutePaymentWithRecurring()
        {
            var executePaymentRequest = new
            {
                //required fields
                PaymentMethodId = "20",// get this Id from IntiatePayment where isDirectPayment is true
                InvoiceValue = 100,
                CallBackUrl = "https://example.com/callback",
                ErrorUrl = "https://example.com/error",
                //optional fields 
                CustomerName = "Customer Name",
                DisplayCurrencyIso = "KWD",
                MobileCountryCode = "965",
                CustomerMobile = "12345678",
                CustomerEmail = "[email protected]",
                Language = "En",
                CustomerReference = "",
                CustomerCivilId = "",
                UserDefinedField = "",
                ExpiryDate = DateTime.Now.AddYears(1),
                // recurring details
                RecurringModel = new
                {
                    RecurringType = "Custom",
                    IntervalDays = 30,
                    Iteration = 2
                }

            };
            var executeRequestJSON = JsonConvert.SerializeObject(executePaymentRequest);
            return await PerformRequest(executeRequestJSON, endPoint: "ExecutePayment").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;
        }
    }
}

Cancel Recurring

<?php
/*
 * ********************************************************************************************************************
 * --------------------------------------------------------------------------------------------------------------------
 * -------------------------------------------- CANCEL RECURRING PAYMENT ----------------------------------------------
 * --------------------------------------------------------------------------------------------------------------------
 * ********************************************************************************************************************
 */


// ********************************************************************************************************************
// -------------------------------------------  START API KEY ---------------------------------------------------------
// ********************************************************************************************************************

//------------- TEST API KEY -------------
// Test Token https://myfatoorah.readme.io/docs/demo-information, Use regular Payment API Key
$token  = " rLtt6JWvbUHDDhsZnfpAhpYk4dxYDQkbcPTyGaKp2TYqQgG7FGZ5Th_WD53Oq8Ebz6A53njUoo1w3pjU1D4vs_ZMqFiz_j0urb_BH9Oq9VZoKFoJEDAbRZepGcQanImyYrry7Kt6MnMdgfG5jn4HngWoRdKduNNyP4kzcp3mRv7x00ahkm9LAK7ZRieg7k1PDAnBIOG3EyVSJ5kK4WLMvYr7sCwHbHcu4A5WwelxYK0GMJy37bNAarSJDFQsJ2ZvJjvMDmfWwDVFEVe_5tOomfVNt6bOg9mexbGjMrnHBnKnZR1vQbBtQieDlQepzTZMuQrSuKn-t5XZM7V6fCW7oP-uXGX-sMOajeX65JOf6XVpk29DP6ro8WTAflCDANC193yof8-f5_EYY-3hXhJj7RBXmizDpneEQDSaSz5sFk0sV5qPcARJ9zGG73vuGFyenjPPmtDtXtpx35A-BVcOSBYVIWe9kndG3nclfefjKEuZ3m4jL9Gg1h2JBvmXSMYiZtp9MR5I6pvbvylU_PP5xJFSjVTIz7IQSjcVGO41npnwIxRXNRxFOdIUHn0tjQ-7LwvEcTXyPsHXcMD8WtgBh-wxR8aKX7WPSsT1O8d8reb2aR7K3rkV3K82K_0OgawImEpwSvp9MNKynEAJQS6ZHe_J_l77652xwPNxMRTMASk1ZsJL";
// Test API URL
$apiURL = "https://apitest.myfatoorah.com";

//------------- Live API KEY -------------
// Live token  https://myfatoorah.readme.io/docs/live-token
// $token = " copy here the token generated in MyFatoorah vendor account";
// Live API URL 
// $apiURL ='https://api.myfatoorah.com';
// -------------------------------------------  END API KEY ----------------------------------------------------------- 


// ********************************************************************************************************************
// -------------------------------------------  Start Cancel Recurring Endpoint ----------------------------------------
// ********************************************************************************************************************
$recurringId = "RECUR2140"; // recurringId should be saved previosly in a secure place to be used here in cancel request
$json        = cancelRecurring($token, "$apiURL/v2/CancelRecurringPayment?recurringId=$recurringId");
echo "<pre/>";
print_r($json);
die;
// ------------------------------------------- END Cancel Recurring Endpoint ------------------------------------------


// ********************************************************************************************************************
// ------------------------------------------- Start FUNCTIONS --------------------------------------------------------
// ********************************************************************************************************************
/*
 * cancel Recurring function 
 */
function cancelRecurring($token, $apiURL) {
    $curl     = curl_init($apiURL);
    curl_setopt_array($curl, array(
        CURLOPT_CUSTOMREQUEST  => "POST",
        CURLOPT_HTTPHEADER     => array("Authorization: Bearer $token", 'Content-Type: application/json', 'Content-Length: 0'),
        CURLOPT_RETURNTRANSFER => true,
    ));
    $response = curl_exec($curl);
    $err      = curl_error($curl);
    curl_close($curl);
    if ($err) {
        // Curl is not working in your server
        echo 'ERROR: ' . $err;
        die;
    }
    $json = json_decode($response);
    // To display response  print_r($json);
    // $json->IsSuccess is not set or false, means that Myfatoorah API has error in its response
    if (!isset($json->IsSuccess) || $json->IsSuccess == null || $json->IsSuccess == false) {
        handleError($json);
    } else {
        return $json;
    }
}
// --------------------------------------------------------------------------------------------------------------------
/*
 * Handle Error function 
 */
function handleError($json) {
    //check for the error insde the object Please tell the exact postion and dont use else
    if (isset($json->ValidationErrors) || isset($json->FieldsErrors)) {
        $errorsObj = isset($json->ValidationErrors) ? $json->ValidationErrors : $json->FieldsErrors;
        $blogDatas = array_column($errorsObj, 'Error', 'Name');

        $err = implode(', ', array_map(function ($k, $v) {
                    return "$k: $v";
                }, array_keys($blogDatas), array_values($blogDatas)));
    } else if (isset($json->Data->ErrorMessage)) {
        $err = $json->Data->ErrorMessage;
    }
    if (empty($err)) {
        // It may return empty content due to invalid API key
        $err = (isset($json->Message)) ? $json->Message : (!empty($res) ? $res : 'API key Or API URL is not correct');
    }
    echo 'ERROR: ' . $err;
    die;
}
// ********************************************************************************************************************
// ------------------------------------------- END FUNCTIONS ----------------------------------------------------------
// ********************************************************************************************************************
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Threading.Tasks;

namespace CancelRecurringPayment
{
    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 recurringId = "{RecurringID";//replace with valid recurring Id like RECUR2188
            Console.WriteLine($"Cancel  For Recurring Id : {recurringId} ");

            var cancelRecurringResponse = await CancelRecurringPayment(recurringId).ConfigureAwait(false);
            Console.WriteLine("Cancel Recurring Response :");
            Console.WriteLine(cancelRecurringResponse);

            Console.ReadLine();
        }
        public static async Task<string> CancelRecurringPayment(string recurringId)
        {
            string url = baseURL + $"/v2/CancelRecurringPayment?recurringId={recurringId}";

            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;
        }
    }

}

Get Recurring Payments

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

namespace RecurringPayments
{
    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)
        {
            var GetRecurringPaymentsResponse = await GetRecurringPayments().ConfigureAwait(false);
            Console.WriteLine("GetRecurringPaymentsResponse :");
            Console.WriteLine(GetRecurringPaymentsResponse);
            Console.ReadLine();
        }
        public static async Task<string> GetRecurringPayments()
        {
            string url = baseURL + $"/v2/GetRecurringPayment";

            HttpClient client = new HttpClient();
            client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
            client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token);
            var responseMessage = await client.GetAsync(url).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?