JavaScript SDK
PayHere Javascript SDK (payhere.js) lets you integrate PayHere into your Website, Web App or cross-platform Mobile App from front-end level to offer an Onsite Checkout Experience for consumers, which avoids redirecting the consumers out of your website or app. You just have to include payhere.js JavaScript library in your web page & initiate a payment instance by passing parameters into the methods provided by the library. The payment callback is same as the Checkout API & it can be handled from backend.
Please refer the below steps to achieve PayHere Onsite Checkout Experience.
Prerequisites
You need your PayHere Merchant ID & Merchant Secret to integrate with Checkout API.
- Merchant ID can be found at Integrations (or Settings > Domains & Credentials in old portal)
- Merchant Secret can be generated for your domain/app as follows
- Go to Integrations (or Settings > Domains & Credentials in old portal)
- Click 'Add Domain/App' > Fill details > Click 'Request to Allow'
- Wait for the approval for your domain
- Copy the Merchant Secret for your domain/app
Note: Merchant Secrets are domain/app specific, therefore you need to generate a new Merchant Secret every time you're integrating PayHere on a new domain/app.
1. Showing the Payment Popup
Regardless of whether you are using vanilla Javascript or a Framework, you can simply set the below variables and show the PayHere Payment Gateway page as a popup. When the popup is displayed, your customer can enter the credentials (Card No / CVV / eZCash No / PIN) there. The payment will be securely processed by PayHere.
payhere.js Script
<script type="text/javascript" src="https://www.payhere.lk/lib/payhere.js"></script>
Required name:value Parameters
merchant_id
- PayHere Merchant IDreturn_url
- URL to redirect users when successcancel_url
- URL to redirect users when cancellednotify_url
- URL to callback the status of the payment (Needs to be a URL accessible on a public IP/domain)first_name
- Customer’s First Namelast_name
- Customer’s Last Nameemail
- Customer’s Emailphone
- Customer’s Phone Noaddress
- Customer’s Address Line1 + Line2city
- Customer’s Citycountry
- Customer’s Countryorder_id
- Order ID generated by the merchantitems
- Item title or Order/Invoice numbercurrency
- Currency Code (LKR/USD)amount
- Total Payment Amount
Optional name:value Parameters
delivery_address
- Delivery Address Line1 + Line2delivery_city
- Delivery Citydelivery_country
- Delivery Countryitem_name_1
- Name of Item 1item_number_1
- Model number of Item 1amount_1
- Unit amount of Item 1quantity_1
- Quantity of Item 1item_name_2
- Name of Item 2item_number_2
- Model number of Item 2amount_2
- Unit amount of Item 2quantity_2
- Quantity of Item 2 (You can list rest of the items also like this)platform
- Referring Platformcustom_1
- Custom param 1 set by merchantcustom_2
- Custom param 2 set by merchanthash
- Generated hash value to ensure extra security
If you need to add extra security when initializing the payment you can use hash
parameter. Please note that this parameter should not be generated in client-side since it will expose your payhere_secret
The hash
value can be generated in following manner
hash = to_upper_case( md5( merchant_id + order_id + payhere_amount + payhere_currency + to_upper_case( md5(payhere_secret) ) ) )
Event handling
payhere.onCompleted
- Called when the checkout is completed. However, the payment can be successful or failed.payhere.onDismissed
- Called when the user closes the payment dialog before the payment can be processed.payhere.onError
- Called if the parameters passed in are invalid.
Code Sample
<script type="text/javascript" src="https://www.payhere.lk/lib/payhere.js"></script>
<button type="submit" id="payhere-payment" >PayHere Pay</button>
<script>
// Payment completed. It can be a successful failure.
payhere.onCompleted = function onCompleted(orderId) {
console.log("Payment completed. OrderID:" + orderId);
// Note: validate the payment and show success or failure page to the customer
};
// Payment window closed
payhere.onDismissed = function onDismissed() {
// Note: Prompt user to pay again or show an error page
console.log("Payment dismissed");
};
// Error occurred
payhere.onError = function onError(error) {
// Note: show an error page
console.log("Error:" + error);
};
// Put the payment variables here
var payment = {
"sandbox": true,
"merchant_id": "121XXXX", // Replace your Merchant ID
"return_url": undefined, // Important
"cancel_url": undefined, // Important
"notify_url": "http://sample.com/notify",
"order_id": "ItemNo12345",
"items": "Door bell wireles",
"amount": "1000.00",
"currency": "LKR",
"first_name": "Saman",
"last_name": "Perera",
"email": "[email protected]",
"phone": "0771234567",
"address": "No.1, Galle Road",
"city": "Colombo",
"country": "Sri Lanka",
"delivery_address": "No. 46, Galle road, Kalutara South",
"delivery_city": "Kalutara",
"delivery_country": "Sri Lanka",
"custom_1": "",
"custom_2": ""
};
// Show the payhere.js popup, when "PayHere Pay" is clicked
document.getElementById('payhere-payment').onclick = function (e) {
payhere.startPayment(payment);
};
</script>
2. Listening to Payment Notification
As soon as the payment is processed, PayHere notifies the payment status to the notify_url
you posted to the Checkout API as a server callback & redirects the customer back to your website to the return_url
. Payment notification will contain the following data as POST params, so you need to host a script on your notify_url
to fetch the following POST params & update your database accordingly.
POST params
merchant_id
- PayHere Merchant ID of the merchantorder_id
- Order ID sent by Merchant to Checkout pagepayment_id
- Unique Payment ID generated by PayHere for the processed paymentpayhere_amount
- Total Amount of the paymentpayhere_currency
- Currency code of the payment (LKR/USD/GBP/EUR/AUD)status_code
- Payment status code (2
,0
,-1
,-2
,-3
)md5sig
- Encrypted signature to verify the paymentcustom_1
- Custom param 1 sent by merchant to Checkout pagecustom_2
- Custom param 2 sent by merchant to Checkout pagemethod
- Payment method selected by the customer. (VISA
,MASTER
,AMEX
,EZCASH
,MCASH
,GENIE
,VISHWA
,PAYAPP
,HNB
,FRIMI
)status_message
- Message received from payment gateway which the customer tried to pay If the customer made the payment by `VISA` or `MASTER` credit/debit card, following parameters will also be available.card_holder_name
- Card Holder Namecard_no
- Masked card number (Ex:************4564
)card_expiry
- Card expiry in format MMYY (Ex:0122
)
Payment Status Codes
2
- success0
- pending-1
- canceled-2
- failed-3
- chargedback
Please note that;
- The request parameters are encoded in the 'application/x-www-form-urlencoded' format, not 'application/json'.
- You cannot test the payment notification by print/echo methods since
notify_url
never loads to the browser as it's a server callback. You can only test it by updating your database upon fetching the notification. - You cannot test the payment notification on localhost. You need to submit a publically accessible IP or domain based URL as your
notify_url
for PayHere to directly notify your server. - No payment status parameters are passed to the
return_url
when redirecting the customer back to your website. You need to update your database upon fetching payment status by your script onnotify_url
& then show the payment status to your customer in the page onreturn_url
by fetching the status from your database.
3. Verifying the Payment Status
It is important to verify the Payment Notification before taking any actions on the payment response. You can do the verification using the md5sig
checksum parameter that is generated & sent by PayHere along with the payment status params according to following logic.
md5sig = strtoupper(
md5 (
merchant_id +
order_id +
payhere_amount +
payhere_currency +
status_code +
strtoupper(md5(payhere_secret))
)
)
Once you receive the payment status params from PayHere, you can locally generate this checksum using the merchant_id, order_id, payhere_amount, payhere_currency & status_code sent by the payment notification and the payhere_secret you have locally (You can find your Merchant Secret in your PayHere Account's Settings page). Your locally generated checksum should equals to the md5sig sent by PayHere if the payment notification is valid.
Code Sample (PHP)
You can host this script at your notify_url
.
<?php
$merchant_id = $_POST['merchant_id'];
$order_id = $_POST['order_id'];
$payhere_amount = $_POST['payhere_amount'];
$payhere_currency = $_POST['payhere_currency'];
$status_code = $_POST['status_code'];
$md5sig = $_POST['md5sig'];
$merchant_secret = 'XXXXXXXXXXXXX'; // Replace with your Merchant Secret (Can be found on your PayHere account's Settings page)
$local_md5sig = strtoupper(
md5(
$merchant_id .
$order_id .
$payhere_amount .
$payhere_currency .
$status_code .
strtoupper(md5($merchant_secret))
)
);
if (($local_md5sig === $md5sig) AND ($status_code == 2) ){
//TODO: Update your database as payment success
}
?>