Sample Code

MakeRefund

<?php
/*
 * ********************************************************************************************************************
 * --------------------------------------------------------------------------------------------------------------------
 * -------------------------------------------- REFUND A 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 Refund a payment Endpoint ---------------------------------------
// ********************************************************************************************************************

//------------- 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"  => 1, // should counvert amount to portal currency ( can be full / partial refund)
        "Comment" => "Test Refund",
    //Fill optional Data
        //"RefundChargeOnCustomer"  => false,
        //"ServiceChargeOnCustomer" => false,
        //"AmountDeductedFromSupplier"=> 0
];

//------------- Call MakeRefund Endpoint ------------
$response   = callAPI($token, "$apiURL/v2/MakeRefund", $postFields);
$json       = json_decode($response);
echo 'Result: ' . $json->Message;
// ------------------------------------------- END MakeRefund Endpoint ------------------------------------------------


// ********************************************************************************************************************
// ------------------------------------------- Start FUNCTIONS --------------------------------------------------------
// ********************************************************************************************************************
// --------------------------------------------------------------------------------------------------------------------
/*
 * Call API endpoint
 */
function callAPI($token, $apiURL, $postFields) {
    $curl     = curl_init($apiURL);
    curl_setopt_array($curl, array(
        CURLOPT_CUSTOMREQUEST  => "POST",
        CURLOPT_POSTFIELDS     => json_encode($postFields),
        CURLOPT_HTTPHEADER     => array("Authorization: Bearer $token", 'Content-Type: application/json'),
        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;
    } else {
        return $response;
    }
}
// --------------------------------------------------------------------------------------------------------------------
/*
 * 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 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)