Sample Code
Embedded Payment Sample Code
This sample code is a complete example of a payment page that uses the MyFatoorah embedded payment.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Embedded Payment</title>
<style>
</style>
</head>
<body style="background-color: white;" >
<script src="https://demo.myfatoorah.com/payment/v1/session.js"></script>
<div style="width:400px; margin: auto;">
<div id="unified-session"></div>
</div>
<!-- This is a div element can be used as a container for Apple Pay -->
<div style="width:400px; margin: auto;">
<div id="apple-pay"></div>
<!-- This is the custom button for Apple Pay. -->
<!-- <button onclick="startApplePay()" style="display: block; margin: 0 auto; width: 400px; height: 30px; cursor: pointer; background-color: #000000; border: none; color: white; font-size: 16px; border-radius: 8px">Apple Pay</button> -->
</div>
<!-- This is a div element can be used as a container for Google Pay -->
<div style="width: 400px; margin: 0; position: absolute; top: 0; left: 0;">
<div id="google-pay"></div>
</div>
<!-- This is your custom payment button -->
<!-- <button onclick="customSubmit()" -->
<!-- style="display: block; margin: 0 auto; width: 400px; height: 30px; cursor: pointer; background-color: #008CBA; border: none; color: white; font-size: 16px; border-radius: 8px">Pay -->
<!-- Now</button> -->
<script>
var sessionId = "193b7291-0b9b-4888-acdc-8c73f26febaf";
var countryCode = "KWT";
var currencyCode = "KWD";
var amount = "99";
var config = {
sessionId: sessionId,
countryCode: countryCode,
currencyCode: currencyCode,
amount: amount,
callback: payment,
containerId: "unified-session",
paymentOptions: ["ApplePay", "GooglePay", "Card"], //"GooglePay", "ApplePay", "Card"
supportedNetworks: ["visa", "masterCard", "mada", "amex"], //"visa", "masterCard", "mada", "amex"
language: "en", //ar en
settings: {
applePay: {
//supportedNetworks: "["visa", "masterCard", "mada"]",
//containerId: "apple-pay",
//callback: paymentAP,
//language: "ar",
style: {
frameHeight: "50px",
frameWidth: "100%",
button: {
height: "40px",
type: "pay", //["plain", "buy", "pay", "checkout", "continue", "book", "donate", "subscribe", "reload", "add", "topup", "order", "rent", "support", "contribute", "setup", "tip"]
borderRadius: "10px"
}
},
useCustomButton: false,
sessionStarted: sessionStarted,
sessionCanceled: sessionCanceled,
requiredShippingContactFields: ["postalAddress", "name", "phone", "email"],
requiredBillingContactFields: ["postalAddress", "name", "phone"]
},
googlePay: {
//supportedNetworks: ["visa", "masterCard"],
//containerId: "google-pay",
//callback: paymentGP,
style: {
frameHeight: "50px",
frameWidth: "100%",
button: {
height: "40px",
type: "pay", //Accepted texts ["book", "buy", "checkout", "donate", "order", "pay", "plain", "subscribe"]
borderRadius: "10px",
color: "black",
language: "en"
}
}
},
card: {
onCardBinChanged: handleCardBinChanged,
style: {
hideNetworkIcons: false,
cardHeight: "180px",
tokenHeight: "180px",
input: {
color: "black",
fontSize: "15px",
fontFamily: "Times",
inputHeight: "32px",
inputMargin: "-1px",
borderColor: "black",
//backgroundColor: "green",
borderWidth: "1px",
borderRadius: "30px",
outerRadius: "10px",
//boxShadow: "0 0 10px 5px purple, 0 0 15px 10px lightblue"
placeHolder: {
holderName: "Name On Card",
cardNumber: "Number",
expiryDate: "MM/YY",
securityCode: "CVV"
}
},
text: {
saveCard: "Save card info for future payments",
addCard: "Use another Card!",
deleteAlert: {
title: "Delete",
message: "Are you sure?",
confirm: "YES",
cancel: "NO"
}
},
label: {
display: false,
color: "black",
fontSize: "13px",
fontWeight: "bold",
fontFamily: "Times",
text: {
holderName: "Card Holder Name",
cardNumber: "Card Number",
expiryDate: "Expiry Date",
securityCode: "Security Code"
}
},
error: {
borderColor: "red",
//boxShadow: "0 0 10px 5px purple, 0 0 15px 10px lightblue",
borderRadius: "8px"
},
button: {
useCustomButton: false,
//onButtonClicked: submit,//You will have to implement this function and call myfatoorah.submitCardPayment()
textContent: "Pay",
fontSize: "16px",
fontFamily: "Times",
color: "white",
backgroundColor: "#4daee0",
height: "30px",
borderRadius: "8px",
width: "70%",
margin: "0 auto",
cursor: "pointer"
},
separator: {
useCustomSeparator: false,
textContent: "Enter your card",
fontSize: "20px",
color: "#4daee0",
fontFamily: "sans-serif",
textSpacing: "2px",
lineStyle: "dashed",
lineColor: "black",
lineThickness: "3px"
}
}
}
}
};
myfatoorah.init(config);
function payment(response) {
//Pass session id to your backend here
if (response.isSuccess) {
switch (response.paymentType) {
case "ApplePay":
console.log("response >> " + JSON.stringify(response));
break;
case "GooglePay":
console.log("response >> " + JSON.stringify(response));
break;
case "Card":
console.log("response >> " + JSON.stringify(response));
break;
default:
console.log("Unknown payment type");
break;
}
}
}
function sessionCanceled() {
console.log("Failed");
}
function sessionStarted() {
console.log("Start");
}
//This function enables you to update the amount displayed on Apple Pay and Google Pay after the initiation of the config.
function updateAmount(amount) {
myfatoorah.updateAmount(amount);
}
//You need to implement here the handling of the callback for Apple Pay
function paymentAP(response) {
//Here you need to pass session id to you backend here
var sessionId = response.sessionId;
var cardBrandAP = response.card.brand;
console.log("SessionID via AP >> ", sessionId);
console.log("cardBrand via AP >> ", cardBrandAP);
console.log("response via AP >> ", response);
}
//You need to implement here the handling of the callback for Google Pay
function paymentGP(response) {
//Here you need to pass session id to you backend here
var sessionId = response.sessionId;
var cardBrandGP = response.card.brand;
console.log("SessionID via GP >> ", sessionId);
console.log("cardBrand via GP >> ", cardBrandGP);
console.log("response via GP >> ", response);
}
//Here you implement the function of clicking on the payment button using your own function
function submit() {
console.log("Submit");
myfatoorah.submitCardPayment(); //It is mandatory to call this function
}
//Here you implement the function of clicking on your custom payment button
function customSubmit() {
console.log("Custom Submit");
myfatoorah.submitCardPayment(); //It is mandatory to call this function
}
function handleCardBinChanged(response) {
console.log(response);
}
//Here you specify the actions you need to do when customer clicks on your custom Apple Pay button
function startApplePay() {
console.log("using custom button");
myfatoorah.initApplePayPayment(); //It is mandatory to call this function
}
</script>
</body>
</html>
<?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
*/
'vcCode' => 'KWT',
/**
* Test Mode (boolean)
* Accepted value: true for the test mode or false for the live mode
*/
'isTest' => true,
];
/* --------------------------- InitiateSession Endpoint --------------------- */
//------------- Post Fields -------------------------
//Check https://docs.myfatoorah.com/docs/InitiateSession#request-model
$postFields = [
//Fill optional data
//'CustomerIdentifier' => 'string', //optional
//'SaveToken' => false, //optional
];
//------------- Call the Endpoint -------------------------
try {
$mfObj = new MyFatoorahPayment($mfConfig);
$data = $mfObj->InitiateSession($postFields);
$sessionId = $data->SessionId;
$link = 'https://docs.myfatoorah.com/docs/embedded-payment-sample-code';
//Display the result to your customer
echo '<h3><u>Summary:</u></h3>';
echo "You should draw the card view with session ID <b>$sessionId</b> as described in the link below then call the ExecutePayment Endpoint.<br>";
echo "<a href='$link' target='_blank'>$link</a><br><br>";
echo '<h3><u>InitiateSession Response Data:</u></h3><pre>';
print_r($data);
echo '</pre>';
} catch (Exception $ex) {
echo $ex->getMessage();
die;
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Unified Payment</title>
<style>
</style>
</head>
<body style="background-color: white;" >
<script src="https://demo.myfatoorah.com/payment/v1/session.js"></script>
<div style="width:400px; margin: auto;">
<div id="unified-session"></div>
</div>
<!-- This is a div element can be used as a container for Apple Pay -->
<div style="width:400px; margin: auto;">
<div id="apple-pay"></div>
<!-- This is the custom button for Apple Pay. -->
<!-- <button onclick="startApplePay()" style="display: block; margin: 0 auto; width: 400px; height: 30px; cursor: pointer; background-color: #000000; border: none; color: white; font-size: 16px; border-radius: 8px">Apple Pay</button> -->
</div>
<!-- This is a div element can be used as a container for Google Pay -->
<div style="width: 400px; margin: 0; position: absolute; top: 0; left: 0;">
<div id="google-pay"></div>
</div>
<!-- This is your custom payment button -->
<!-- <button onclick="customSubmit()" -->
<!-- style="display: block; margin: 0 auto; width: 400px; height: 30px; cursor: pointer; background-color: #008CBA; border: none; color: white; font-size: 16px; border-radius: 8px">Pay -->
<!-- Now</button> -->
<script>
var sessionId = "<?php echo $data->SessionId; ?>";
var countryCode = "<?php echo $data->CountryCode; ?>";
var currencyCode = "KWD";
var amount = "99";
var config = {
sessionId: sessionId,
countryCode: countryCode,
currencyCode: currencyCode,
amount: amount,
callback: payment,
containerId: "unified-session",
paymentOptions: ["ApplePay", "GooglePay", "Card"], //"GooglePay", "ApplePay", "Card"
supportedNetworks: ["visa", "masterCard", "mada", "amex"], //"visa", "masterCard", "mada", "amex"
language: "en", //ar en
settings: {
applePay: {
//supportedNetworks: "["visa", "masterCard", "mada"]",
//containerId: "apple-pay",
//callback: paymentAP,
style: {
frameHeight: "50px",
frameWidth: "100%",
button: {
height: "40px",
type: "pay", //["plain", "buy", "pay", "checkout", "continue", "book", "donate", "subscribe", "reload", "add", "topup", "order", "rent", "support", "contribute", "setup", "tip"]
borderRadius: "0px"
}
},
useCustomButton: false,
sessionStarted: sessionStarted,
sessionCanceled: sessionCanceled,
requiredShippingContactFields: ["postalAddress", "name", "phone", "email"],
requiredBillingContactFields: ["postalAddress", "name", "phone"]
},
googlePay: {
//supportedNetworks: ["visa", "masterCard"],
//containerId: "google-pay",
//callback: paymentGP,
style: {
frameHeight: "50px",
frameWidth: "100%",
button: {
height: "40px",
type: "pay", //Accepted texts ["book", "buy", "checkout", "donate", "order", "pay", "plain", "subscribe"]
borderRadius: "0px",
color: "black",
language: "en"
}
}
},
card: {
onCardBinChanged: handleCardBinChanged,
style: {
hideNetworkIcons: false,
cardHeight: "180px",
tokenHeight: "180px",
input: {
color: "black",
fontSize: "15px",
fontFamily: "Times",
inputHeight: "32px",
inputMargin: "-1px",
borderColor: "black",
borderWidth: "1px",
borderRadius: "30px",
outerRadius: "10px",
//boxShadow: "0 0 10px 5px purple, 0 0 15px 10px lightblue"
placeHolder: {
holderName: "Name On Card",
cardNumber: "Number",
expiryDate: "MM/YY",
securityCode: "CVV"
}
},
text: {
saveCard: "Save card info for future payments",
addCard: "Use another Card!",
deleteAlert: {
title: "Delete",
message: "Are you sure?",
confirm: "YES",
cancel: "NO"
}
},
label: {
display: false,
color: "black",
fontSize: "13px",
fontWeight: "bold",
fontFamily: "Times",
text: {
holderName: "Card Holder Name",
cardNumber: "Card Number",
expiryDate: "Expiry Date",
securityCode: "Security Code"
}
},
error: {
borderColor: "red",
//boxShadow: "0 0 10px 5px purple, 0 0 15px 10px lightblue",
borderRadius: "8px"
},
button: {
useCustomButton: false,
//onButtonClicked: submit,//You will have to implement this function and call myfatoorah.submitCardPayment()
textContent: "Pay",
fontSize: "16px",
fontFamily: "Times",
color: "white",
backgroundColor: "#4daee0",
height: "30px",
borderRadius: "8px",
width: "70%",
margin: "0 auto",
cursor: "pointer"
},
separator: {
useCustomSeparator: false,
textContent: "Enter your card",
fontSize: "20px",
color: "#4daee0",
fontFamily: "sans-serif",
textSpacing: "2px",
lineStyle: "dashed",
lineColor: "black",
lineThickness: "3px"
}
}
}
}
};
myfatoorah.init(config);
function payment(response) {
//Pass session id to your backend here
switch (response.paymentType) {
case "ApplePay":
console.log("response >> " + JSON.stringify(response));
break;
case "GooglePay":
console.log("response >> " + JSON.stringify(response));
break;
case "Card":
console.log("response >> " + JSON.stringify(response));
break;
default:
console.log("Unknown payment type");
break;
}
window.location = 'embedded-payment-sample-code-call-ExecutePayment.php?sessionId=' + sessionId;
}
function sessionCanceled() {
console.log("Failed");
}
function sessionStarted() {
console.log("Start");
}
//This function enables you to update the amount displayed on Apple Pay and Google Pay after the initiation of the config.
function updateAmount(amount) {
myfatoorah.updateAmount(amount);
}
//You need to implement here the handling of the callback for Apple Pay
function paymentAP(response) {
//Here you need to pass session id to you backend here
var sessionId = response.sessionId;
var cardBrandAP = response.card.brand;
console.log("SessionID via AP >> ", sessionId);
console.log("cardBrand via AP >> ", cardBrandAP);
console.log("response via AP >> ", response);
}
//You need to implement here the handling of the callback for Google Pay
function paymentGP(response) {
//Here you need to pass session id to you backend here
var sessionId = response.sessionId;
var cardBrandGP = response.card.brand;
console.log("SessionID via GP >> ", sessionId);
console.log("cardBrand via GP >> ", cardBrandGP);
console.log("response via GP >> ", response);
}
//Here you implement the function of clicking on the payment button using your own function
function submit() {
console.log("Submit");
myfatoorah.submitCardPayment(); //It is mandatory to call this function
}
//Here you implement the function of clicking on your custom payment button
function customSubmit() {
console.log("Custom Submit");
myfatoorah.submitCardPayment(); //It is mandatory to call this function
}
function handleCardBinChanged(response) {
console.log(response);
}
//Here you specify the actions you need to do when customer clicks on your custom Apple Pay button
function startApplePay() {
console.log("using custom button");
myfatoorah.initApplePayPayment(); //It is mandatory to call this function
}
</script>
</body>
</html>
Call ExecutePayment with SessionID
<?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
*/
'vcCode' => 'KWT',
/**
* Test Mode (boolean)
* Accepted value: true for the test mode or false for the live mode
*/
'isTest' => true,
];
/* --------------------------- ExecutePayment Endpoint --------------------- */
$invoiceValue = 50;
$displayCurrencyIso = 'KWD';
//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,
'SessionId' => $_GET['sessionId'],
//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;
//Display the result to your customer
//Redirect your customer to complete the payment process
echo '<h3><u>Summary:</u></h3>';
echo "To pay the invoice ID <b>$invoiceId</b>, click on:<br>";
echo "<a href='$paymentLink' target='_blank'>$paymentLink</a><br><br>";
echo '<h3><u>ExecutePayment Response Data:</u></h3><pre>';
print_r($data);
echo '</pre>';
} catch (Exception $ex) {
echo $ex->getMessage();
die;
}
Sample Project
You can download the sample project to test it out from here
Open OTP in iframe
Check the sample project to open the OTP in iframe from here
Updated 2 months ago