Sample Code
SendPayment
As described earlier for the Invoice Link, we are going to have a sample code to consume this endpoint to make a successful integration.
<?php
/* For simplicity check our PHP SDK library here https://myfatoorah.readme.io/php-library */
/* ------------------------ 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 SendPayment 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,
]
]; */
//Fill POST fields array, check https://myfatoorah.readme.io/docs/send-payment#request-model
$postFields = [
//Fill required data
'NotificationOption' => 'Lnk', //'SMS', 'EML', or 'ALL'
'InvoiceValue' => '50',
'CustomerName' => 'fname lname',
//Fill optional data
//'DisplayCurrencyIso' => 'KWD',
//'MobileCountryCode' => '+965',
//'CustomerMobile' => '1234567890',
//'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.
//'SourceInfo' => 'Pure PHP', //For example: (Symfony, CodeIgniter, Zend Framework, Yii, CakePHP, etc)
//'CustomerAddress' => $customerAddress,
//'InvoiceItems' => $invoiceItems,
//Suppliers => $suppliers
];
//Call endpoint
$data = sendPayment($apiURL, $apiKey, $postFields);
//You can save payment data in database as per your needs
$invoiceId = $data->InvoiceId;
$paymentLink = $data->InvoiceURL;
//Redirect your customer to the invoice 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 --------------------------------------- */
/*
* Send Payment Endpoint Function
*/
function sendPayment($apiURL, $apiKey, $postFields) {
$json = callAPI("$apiURL/v2/SendPayment", $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 System;
using System.Collections.Generic;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Threading.Tasks;
namespace SendPayment
{
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 response = await SendPayment().ConfigureAwait(false);
Console.WriteLine("Send Payment Response :");
Console.WriteLine(response);
Console.ReadLine();
}
public static async Task<string> SendPayment()
{
var sendPaymentRequest = new
{
//required fields
CustomerName = "Customer Name",
NotificationOption = "LNK",
InvoiceValue = 100,
//optional fields
DisplayCurrencyIso = "KWD",
MobileCountryCode = "965",
CustomerMobile = "12345678",
CustomerEmail = "[email protected]",
CallBackUrl = "https://example.com/callback",
ErrorUrl = "https://example.com/error",
Language = "En",
CustomerReference = "",
CustomerCivilId = "",
UserDefinedField = "",
ExpiryDate = DateTime.Now.AddYears(1),
// add suppliers
Suppliers = new[] {
new {
SupplierCode = 1, InvoiceShare = 100, ProposedShare = 70
}
}
};
var sendPaymentRequestJSON = JsonConvert.SerializeObject(sendPaymentRequest);
return await PerformRequest(sendPaymentRequestJSON, "SendPayment").ConfigureAwait(false);
}
public static async Task<string> PerformRequest(string requestJSON, string endPoint)
{
string 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;
}
}
}
# Send 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"]
elif check_data("Data", response_data):
error = response_data["Data"]["ErrorMessage"]
elif check_data("ErrorMessage", response_data["Data"]):
error = response_data["Data"]["ErrorMessage"]
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
# Send Payment endpoint Function
def send_payment(sendpay_data):
api_url = base_url + "/v2/SendPayment"
sendpay_response = call_api(api_url, api_key, sendpay_data).json() # RReceiving the response of MyFatoorah
invoice_id = sendpay_response["Data"]["InvoiceId"]
invoice_url = sendpay_response["Data"]["InvoiceURL"]
# Send Payment output if successful
print("InvoiceId: ", invoice_id,
"\nInvoiceURL: ", invoice_url)
return invoice_id, invoice_url
# 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
# SendPayment Request
sendpay_data = {
"CustomerName": "name", # Mandatory Field ("string")
"NotificationOption": "LNK", # Mandatory Field ("LNK", "SMS", "EML", or "ALL")
"InvoiceValue": 100, # Mandatory Field (Number)
# Optional Fields
# "MobileCountryCode": "965",
# "CustomerMobile": "12345678", #Mandatory if the NotificationOption = SMS or ALL
# "CustomerEmail": "[email protected]", #Mandatory if the NotificationOption = EML or ALL
# "DisplayCurrencyIso": "kwd",
# "CallBackUrl": "https://yoursite.com/success",
# "ErrorUrl": "https://yoursite.com/error",
# "Language": "en",
# "CustomerReference": "noshipping-nosupplier",
# "CustomerAddress": {
# "Block": "string",
# "Street": "string",
# "HouseBuildingNo": "string",
# "Address": "address",
# "AddressInstructions": "string"
# },
# "InvoiceItems": [
# {
# "ItemName": "string",
# "Quantity": 20,
# "UnitPrice": 5
# }
# ]
}
try:
send_payment(sendpay_data)
except:
ex_type, ex_value, ex_traceback = sys.exc_info()
print("Exception type : %s " % ex_type.__name__)
print("Exception message : %s" % ex_value)
###########Send Payment###########
require 'net/http'
require 'uri'
require 'json'
uri = URI.parse("https://apitest.myfatoorah.com/v2/SendPayment")
token = 'mytokenvalue' #token value to be placed here
header = {'Authorization':token}
body = {
'CustomerName': 'Ahmed',
'NotificationOption': 'ALL',
'MobileCountryCode':'+965',
'CustomerMobile': '12345678',
'CustomerEmail': '[email protected]',
'InvoiceValue': 100,
'DisplayCurrencyIso': 'KWD',
'CallBackUrl': 'https://google.com',
'ErrorUrl': 'https://yahoo.com',
'Language': 'en',
'CustomerReference': 'ref 1',
'CustomerCivilId':12345678,
'UserDefinedField': 'Custom field',
'ExpireDate': '',
'CustomerAddress': {
'Block':'',
'Street':'',
'HouseBuildingNo':'',
'Address':'',
'AddressInstructions':''
},
'InvoiceItems': [
{
'ItemName': 'Product 01',
'Quantity': 1,
'UnitPrice': 100
}
]
}
# Create the HTTP objects
http = Net::HTTP.new(uri.host, uri.port)
http.use_ssl = true
request = Net::HTTP::Post.new(uri.request_uri, header)
request["Content-Type"] = 'application/json'
request.body = body.to_json
# Send the request
response = http.request(request)
puts response.read_body
parsed = JSON.parse(response.body)
invoiceURL = parsed['Data']['InvoiceURL']
puts invoiceURL
console.log('#################### Send Payment########################');
var request = require("request");
var token = 'mytokenvalue' //token value to be placed here;
var baseURL = 'https://apitest.myfatoorah.com';
var options = { method: 'POST',
url: baseURL+'/v2/SendPayment',
headers:
{ Accept: 'application/json',
Authorization: 'Bearer '+token,
'Content-Type': 'application/json' },
body:
{ NotificationOption: 'ALL',
CustomerName: 'Ahmed',
DisplayCurrencyIso: 'KWD',
MobileCountryCode: '+965',
CustomerMobile: '12345678',
CustomerEmail: '[email protected]',
InvoiceValue: 100,
CallBackUrl: 'https://google.com',
ErrorUrl: 'https://google.com',
Language: 'en',
CustomerReference: 'ref 1',
CustomerCivilId: 12345678,
UserDefinedField: 'Custom field',
ExpireDate: '',
CustomerAddress:
{ Block: '',
Street: '',
HouseBuildingNo: '',
Address: '',
AddressInstructions: '' },
InvoiceItems: [ { ItemName: 'Product 01', Quantity: 1, UnitPrice: 100 } ] },
json: true };
request(options, function (error, response, body) {
if (error) throw new Error(error);
console.log(body);
});
Updated 4 months ago