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 */
//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\API\MyFatoorahRefund;
/* --------------------------- 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,
];
/* --------------------------- MakeRefund Endpoint -------------------------- */
//Inquiry using InvoiceId
//InvoiceId should be returned in the send/execute payment endpoit response
$keyId = '3110788';
$KeyType = 'InvoiceId';
//Inquiry using PaymentId
//PaymentId should be returned in the callback
$keyId = '07073110788180275773';
$KeyType = 'PaymentId';
//------------- Post Fields -------------------------
//Check https://docs.myfatoorah.com/docs/make-refund#request-model
$postFields = [
// Fill required Data
'KeyType' => $KeyType,
'Key' => $keyId,
'Amount' => 1, //can be full/partial refund
//Fill optional Data
//'CurrencyIso' => 'KWD',
//'Comment' => "Test Refund",
//'ServiceChargeOnCustomer' => false,
//'AmountDeductedFromSupplier' => 0
];
//------------- Call the Endpoint -------------------------
try {
$mfObj = new MyFatoorahRefund($mfConfig);
$data = $mfObj->makeRefund($postFields);
//Display the result to your customer
echo '<h3><u>Summary:</u></h3>';
echo "Refund Id is <b>$data->RefundId</b><br>";
echo "Refund Reference is <b>$data->RefundReference</b>";
echo '<h3><u>MyFatoorahRefund Response Data:</u></h3><pre>';
print_r($data);
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 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 */
//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,
];
/* --------------------------- GetRefundStatus Endpoint --------------------- */
//Inquiry using InvoiceId
//InvoiceId should be returned in the send/execute payment endpoit response
$keyId = '3110788';
$KeyType = 'InvoiceId';
//Inquiry using RefundReference
//RefundReference should be returned in the callback
$keyId = '2023000787';
$KeyType = 'RefundReference';
//Inquiry using RefundId
//RefundId should be returned in the callback of MakeRefund endpoint
$keyId = '85342';
$KeyType = 'RefundId';
//------------- Post Fields -------------------------
//Check https://docs.myfatoorah.com/docs/getrefundstatus#request-model
$postFields = [
// Fill required Data
'KeyType' => $KeyType,
'Key' => $keyId,
];
//------------- Call the Endpoint -------------------------
try {
$mfObj = new MyFatoorah($mfConfig);
$apiURL = $mfObj->getApiUrl();
$obj = $mfObj->callAPI("$apiURL/v2/GetRefundStatus", $postFields);
//Display the result to your customer
echo '<h3><u>Summary:</u></h3>';
echo 'Refund status is <b>' . $obj->Data->RefundStatusResult[0]->RefundStatus . '</b>';
echo '<h3><u>GetRefundStatus Response Data:</u></h3><pre>';
print_r($obj->Data);
echo '</pre>';
} catch (Exception $ex) {
echo $ex->getMessage();
die;
}
Updated 4 months ago