Sample Code

Overview

In this section, we provide sample codes for:


Make Refund

<?php

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

//Test
$apiURL = 'https://apitest.myfatoorah.com';
$apiKey = 'rLtt6JWvbUHDDhsZnfpAhpYk4dxYDQkbcPTyGaKp2TYqQgG7FGZ5Th_WD53Oq8Ebz6A53njUoo1w3pjU1D4vs_ZMqFiz_j0urb_BH9Oq9VZoKFoJEDAbRZepGcQanImyYrry7Kt6MnMdgfG5jn4HngWoRdKduNNyP4kzcp3mRv7x00ahkm9LAK7ZRieg7k1PDAnBIOG3EyVSJ5kK4WLMvYr7sCwHbHcu4A5WwelxYK0GMJy37bNAarSJDFQsJ2ZvJjvMDmfWwDVFEVe_5tOomfVNt6bOg9mexbGjMrnHBnKnZR1vQbBtQieDlQepzTZMuQrSuKn-t5XZM7V6fCW7oP-uXGX-sMOajeX65JOf6XVpk29DP6ro8WTAflCDANC193yof8-f5_EYY-3hXhJj7RBXmizDpneEQDSaSz5sFk0sV5qPcARJ9zGG73vuGFyenjPPmtDtXtpx35A-BVcOSBYVIWe9kndG3nclfefjKEuZ3m4jL9Gg1h2JBvmXSMYiZtp9MR5I6pvbvylU_PP5xJFSjVTIz7IQSjcVGO41npnwIxRXNRxFOdIUHn0tjQ-7LwvEcTXyPsHXcMD8WtgBh-wxR8aKX7WPSsT1O8d8reb2aR7K3rkV3K82K_0OgawImEpwSvp9MNKynEAJQS6ZHe_J_l77652xwPNxMRTMASk1ZsJL';

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

//------------- Refund using paymentId -------------
$keyId      = "100202110305128442"; // paymentId should be returned in the callback
$KeyType    = 'paymentId';

//------------- Refund using invoiceId -------------
//$keyId   = "613842"; // invoiceId should be returned in the send /execute payment endpoit response
//$KeyType = 'invoiceId';

//------------- Post Fields -------------------------
$postFields = [
	// Fill required Data
		"KeyType" => $KeyType,
		"Key"     => $keyId,
		"Amount"  => 10, // should counvert amount to portal currency ( can be full / partial refund)
	//Fill optional Data
  	//"Comment" => "Test Refund",
  	//"RefundChargeOnCustomer"  => false,
		//"ServiceChargeOnCustomer" => false,
		//"AmountDeductedFromSupplier"=> 0
];

//Call endpoint
$json   = callAPI("$apiURL/v2/MakeRefund", $apiKey, $postFields);

//Display the payment result to your customer
echo 'Result: ' . $json->Message;

/* ------------------------ 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 Newtonsoft.Json.Linq;
using System;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Threading.Tasks;

namespace Refund
{

    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)
        {
            // MakeRefund
            var refundResponse = await MakeRefund().ConfigureAwait(false);
            Console.WriteLine("Make Refund Response :");
            Console.WriteLine(refundResponse);
           
            // MakeRefundWithSupplier
            var refundWithSupplierResponse = await MakeRefundWithSupplier().ConfigureAwait(false);
            Console.WriteLine("Make Refund WithSupplier Response :");
            Console.WriteLine(refundWithSupplierResponse);

            Console.ReadLine();
        }
        public static async Task<string> MakeRefund()
        {
            var makeRefundRequest = new
            {
                //required fields
                key = "665217",
                KeyType = "invoiceid",
                Amount = 1,
                Comment = "refund comment",
                //optional fields 
                RefundChargeOnCustomer = false,
                ServiceChargeOnCustomer = false,
                AmountDeductedFromSupplier = 0,
            };
            var executeRequestJSON = JsonConvert.SerializeObject(makeRefundRequest);
            return await PerformRequest(executeRequestJSON, endPoint: "MakeRefund").ConfigureAwait(false);
        }

        public static async Task<string> MakeRefundWithSupplier()
        {
            var makeRefundWithSupplier = new
            {
                key = "665217",
                KeyType = "invoiceid",
                VendorDeductAmount = 1,
                Comment = "refund comment",
                Suppliers = new[] {
                        new {
                          SupplierCode = 1,
                          SupplierDeductedAmount = 1
                        }
                 }
            };
            var executeRequestJSON = JsonConvert.SerializeObject(makeRefundWithSupplier);
            return await PerformRequest(executeRequestJSON, endPoint: "MakeSupplierRefund").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;
        }
    }

}
#Refund Payment API

# 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"]
    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


# Refund Function
def refund(refund_request):
    api_url = base_url + "/v2/MakeRefund"
    refund_response = call_api(api_url, api_key, refund_request).json()
    refund_data = refund_response["Data"]
    print("Successful Refund \nRefund Response: ", refund_data)
    return refund_data


# 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

refund_request = {
                 "KeyType": "invoiceid",
                 "Key": "962899",
                 "RefundChargeOnCustomer": False,
                 "ServiceChargeOnCustomer": False,
                 "Amount": 105.033,
                 "Comment": "Test Api",
                 "AmountDeductedFromSupplier": 0
                }

try:
    refund(refund_request)
except:
    ex_type, ex_value, ex_traceback = sys.exc_info()
    print("Exception type : %s " % ex_type.__name__)
    print("Exception message : %s" % ex_value)

Get Refund Status

<?php

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

//Test
$apiURL = 'https://apitest.myfatoorah.com';
$apiKey = 'rLtt6JWvbUHDDhsZnfpAhpYk4dxYDQkbcPTyGaKp2TYqQgG7FGZ5Th_WD53Oq8Ebz6A53njUoo1w3pjU1D4vs_ZMqFiz_j0urb_BH9Oq9VZoKFoJEDAbRZepGcQanImyYrry7Kt6MnMdgfG5jn4HngWoRdKduNNyP4kzcp3mRv7x00ahkm9LAK7ZRieg7k1PDAnBIOG3EyVSJ5kK4WLMvYr7sCwHbHcu4A5WwelxYK0GMJy37bNAarSJDFQsJ2ZvJjvMDmfWwDVFEVe_5tOomfVNt6bOg9mexbGjMrnHBnKnZR1vQbBtQieDlQepzTZMuQrSuKn-t5XZM7V6fCW7oP-uXGX-sMOajeX65JOf6XVpk29DP6ro8WTAflCDANC193yof8-f5_EYY-3hXhJj7RBXmizDpneEQDSaSz5sFk0sV5qPcARJ9zGG73vuGFyenjPPmtDtXtpx35A-BVcOSBYVIWe9kndG3nclfefjKEuZ3m4jL9Gg1h2JBvmXSMYiZtp9MR5I6pvbvylU_PP5xJFSjVTIz7IQSjcVGO41npnwIxRXNRxFOdIUHn0tjQ-7LwvEcTXyPsHXcMD8WtgBh-wxR8aKX7WPSsT1O8d8reb2aR7K3rkV3K82K_0OgawImEpwSvp9MNKynEAJQS6ZHe_J_l77652xwPNxMRTMASk1ZsJL';

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

//------------- Refund using paymentId -------------
//$keyId      = ""; // RefundId should be returned in the callback of MakeRefund endpoint
//$KeyType    = 'refundId';

//------------- Refund using invoiceId -------------
$keyId   = "613842"; // invoiceId should be returned in the send /execute payment endpoit response
$KeyType = 'invoiceId';

//------------- Post Fields -------------------------
$postFields = [
	// Fill required Data
		"KeyType" => $KeyType,
		"Key"     => $keyId
];

//Call GetRefundStatus endpoint
$json   = callAPI("$apiURL/v2/GetRefundStatus", $apiKey, $postFields);


//Display the payment result to your customer
echo('<pre>');
print_r($json->Data->RefundStatusResult);

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

/* -------------------------------------------------------------------------- */