Sample Code

Recurring

Overview

In this section, we provide sample codes for:


Recurring Payment

<?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'      => '',
    /*
     * Country ISO Code (string)
     * Accepted value: KWT, SAU, ARE, QAT, BHR, OMN, JOD, or EGY. Check https://docs.myfatoorah.com/docs/iso-lookups
     */
    'countryCode' => '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,
    'RecurringModel'  => [
        'RecurringType' => 'Custom',
        'IntervalDays'  => 180,
        'Iteration'     => 1
    ],
        //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;

    $recurringId = $data->RecurringId;
} 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 'Recurring Id: <b>' . $recurringId . '</b>.<br>';
    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 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

/* 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;

/* --------------------------- 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'      => '',
    /*
     * Country ISO Code (string)
     * Accepted value: KWT, SAU, ARE, QAT, BHR, OMN, JOD, or EGY. Check https://docs.myfatoorah.com/docs/iso-lookups
     */
    'countryCode' => 'KWT',
    /**
     * Test Mode (boolean)
     * Accepted value: true for the test mode or false for the live mode
     */
    'isTest'      => true,
];

/* --------------------------- CancelRecurringPayment Endpoint -------------- */

//RecurringId should be saved previosly in a secure place to be used here in cancel request
$recurringId = 'RECUR27079';

//------------- Call the Endpoint -------------------------
try {
    $mfObj  = new MyFatoorah($mfConfig);
    $apiURL = $mfObj->getApiUrl();
    $obj    = $mfObj->callAPI("$apiURL/v2/CancelRecurringPayment?recurringId=$recurringId", '');

    //Display the result to your customer
    echo '<h3><u>CancelRecurringPayment Response Object:</u></h3><pre>';
    print_r($obj);
    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 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

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

/* --------------------------- 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'      => '',
    /*
     * Country ISO Code (string)
     * Accepted value: KWT, SAU, ARE, QAT, BHR, OMN, JOD, or EGY. Check https://docs.myfatoorah.com/docs/iso-lookups
     */
    'countryCode' => 'KWT',
    /**
     * Test Mode (boolean)
     * Accepted value: true for the test mode or false for the live mode
     */
    'isTest'      => true,
];

/* --------------------------- GetRecurringPayment Endpoint ----------------- */

//------------- Call the Endpoint -------------------------
try {
    $mfObj  = new MyFatoorah($mfConfig);
    $apiURL = $mfObj->getApiUrl();
    $obj    = $mfObj->callAPI("$apiURL/v2/GetRecurringPayment");

    //Display the result to your customer
    echo '<h3><u>GetRecurringPayment Response Object:</u></h3><pre>';
    print_r($obj);
    echo '</pre>';
} catch (Exception $ex) {
    echo $ex->getMessage();
    die;
}
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;
        }


    }
}