Try redirect to Checkout Link
To verify that your integration is going through as expected, after generating the checkout link. Next, we going to make some redirect request to that checkout link. If the request is successful you will redirect to PAYON's payment page.
Include PAYON's library
Add PAYON's lib helper for client side to your check out page.
<script th:src="@{../js/payonUtils.js}" charset="utf-8" type="text/javascript"></script>
Prepare your Checkout Page
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org">
<body>
<button class="btn btn-primary" id= "checkOut">Check Out</button>
<button class="btn btn-primary" id= "payonnCheckOut">PAY with PAYON</button>
<button class="btn btn-primary" id= "creditDebitCheckOut">PAY with Credit/Debit</button>
<button class="btn btn-primary" id= "pgBindingCheckOut">PAY with Credit/Debit</button>
<button class="btn btn-primary" id= "pgBtCheckOut">PAY with Bank Transfer</button>
</body>
</html>
Prepare your Checkout script
In order to process this step. First, you need to Checkout Link endpoint in step 2. This endpoint will be on back end side implementation.
JavaScript
$("#checkOut").click(function(){
var amount = "YOUR AMOUNT";
var currency = "USD";
var paymentMethod = "";
var merchantId = "YOUR MERCHANT ID"
var termId = "YOUR TERM ID"
var txId = "YOUR TRANSACTION ID"
var env = "TEST" //TEST:test enviroment, PRODUCTION: production enviroment
//Init PayonUtils
let payonUtils = new PayonUtils(amount,currency,paymentMethod,merchantId,termId,txId,env);
//Call checkout function
//payonUtils.checkOut("/order/orderItem","post");
payonUtils.checkOut("YOUR END POINT","post");
});
PHP
<?php
require "CheckoutURIBuilder.php";
if(isset($_POST['checkout'])) {
$check = new CheckoutURIBuilder(
$param["lang"],
$param["merchantId"],
$param["termId"],
$param["txId"],
$param["amount"],
$param["currency"],
$param["apiKey"]);
$check::Environment("TEST");
$url = $check::toCheckoutUrlString();
header("Location:".$url);
exit();
}
?>
Prepare your PAYON's Wallet Checkout Script
$("#payonnCheckOut").click(function(){
var amount = "YOUR AMOUNT";
var currency = "USD";
var paymentMethod = "PAYON";
var merchantId = "YOUR MERCHANT ID"
var termId = "YOUR TERM ID"
var txId = "YOUR TRANSACTION ID"
var env = "TEST" //TEST:test enviroment, UAT: User Acceptance Test, PRODUCTION: production enviroment
//Init PayonUtils
let payonUtils = new PayonUtils(amount,currency,paymentMethod,merchantId,termId,txId,env);
//Call checkout function
//payonUtils.checkOut("/order/orderItem","post");
payonUtils.checkOut("YOUR END POINT","post");
});
Prepare your Credit/Debit's Checkout Script
$("#creditDebitCheckOut").click(function(){
var amount = "YOUR AMOUNT";
var currency = "USD";
var paymentMethod = "CREDIT_DEBIT";
var merchantId = "YOUR MERCHANT ID"
var termId = "YOUR TERM ID"
var txId = "YOUR TRANSACTION ID"
var env = "TEST" //TEST:test enviroment,UAT: User Acceptance Test, PRODUCTION: production enviroment
//Init PayonUtils
let payonUtils = new PayonUtils(amount,currency,paymentMethod,merchantId,termId,txId,env);
//Call checkout function
payonUtils.payonPgCreditDebitCheckOut();
});
Prepare your Binding Payment Script
$("#pgBindingCheckOut").click(function(){
var amount = total;
var currency = "USD";
var paymentMethod = "PAYON"; //PAYON, CREDIT_DEBIT
var merchantId = $('#merchantId').val();
var termId = $('#termId').val();
var bindingId = $('#bindingId').val();
var clientId = $('#clientId').val();
var txId = Date.now();
var env = $('#env').val();
let payonUtils = new PayonUtils(amount,currency,paymentMethod,merchantId,termId,txId,env,bindingId,clientId);
payonUtils.payonPgBindingCheckOut();
});
Prepare your Bank Transfer Check out Script
$("#btCheckOut").click(function(){
var amount = total;
var currency = "USD";
var paymentMethod = "PPCBANK_TRANSFER";
var merchantId = $('#merchantId').val();
var trt = "10"; //10: PURCHASE
var termId = $('#termId').val();
var txId = Date.now();
var env = $('#env').val();
var buyerId = $('#buyerId').val();
var sellerId = $('#sellerId').val();
var description = $('#remark').val();
let payonUtils = new PayonUtils(amount, currency,paymentMethod,merchantId,termId,txId, env,"","",trt,"",description,buyerId,sellerId);
payonUtils.payonPgBankTransferCheckOut();
});
Prepare your Checkout Script
Android - Kotlin
// Here is the sample code, So please define it with your own structure project.
// dependencies/Library
implementation 'com.google.code.gson:gson:x.x.x'
implementation 'com.squareup.okhttp3:okhttp:x.x.x'
implementation 'com.squareup.okhttp3:logging-interceptor:x.x.x'
Step 1: In your Activity Class
// Global Variable
private val deepLink = "" //deeplink provided by PAYON PLC. Dev Team.
private val client = OkHttpClient()
private val pgUrl = "http://pgtest.payon.com.kh"
private val termID = "CT03000003"
private val txnID = ""
private val trt = "10"
private var payDvCd = "PAYON_QR"
private val merchantId = "C0000143"
private val currency = "USD" // payment currency.
private val amount = "1" // transaction amount.
private var paymentMethod = "PAYON"
private var isPayStart = false // set to false, the activity does not call check-transaction when first start of activity. set to true, check transaction after start Pay.
Step 2: in your Event/Function
// #### Event/Function clicked ####
val payDvCd = "PAYON_QR" // Payon App Pay = "PAYON_QR", Pay With Credit/Debit = "MPI"
val paymentMethod = "PAYON" // Payon App Pay = "PAYON", Pay With Credit/Debit = "CREDIT_DEBIT"
val httpUrl = "$pgUrl/pg/order/register".toHttpUrl()
val httpUrlBuilder = httpUrl.newBuilder()
val requestBuilder = Request.Builder().url(httpUrlBuilder.build())
val mediaTypeJson = "application/json; charset=utf-8".toMediaType()
dataHashMap = HashMap()
dataHashMap["termId"] = termID
dataHashMap["trt"] = trt
dataHashMap["payDvCd"] = payDvCd
dataHashMap["txId"] = txnID
dataHashMap["merchantId"] = merchantId
dataHashMap["currency"] = currency
dataHashMap["amount"] = amount
dataHashMap["paymentMethod"] = paymentMethod
requestBuilder.post(gsonObject.toJson(dataHashMap).toRequestBody(mediaTypeJson) )
client.newCall(requestBuilder.build()).enqueue(object : Callback {
override fun onResponse(call: Call, response: Response) {
try {
val bodyString: String? = response.body?.string()
val jsonData = JSONObject(bodyString!!)
val resultCode = jsonData.getString("resultCode")
val resultMsg = jsonData.getString("resultMsg")
val resultData = jsonData.getString("resultData")
if(resultCode.equals("0000")) {
thread {
try {
val iPayOnPay = Intent(Intent.ACTION_VIEW)
val payonScheme = Uri.parse("${deepLink}://payon/parameters/?data=${resultData}")
iPayOnPay.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
iPayOnPay.data = payonScheme
isPayStart = true
startActivity(iPayOnPay)
}
catch (ex: ActivityNotFoundException) {
// App not installed, open app to download in appstore
isPayStart = false
startActivity(Intent(Intent.ACTION_VIEW, Uri.parse(
"https://play.google.com/store/apps/details?id=kh.com.payon.payon")))
}
}
}
else { alertMessage("Request Payon: ResultCode=$resultCode, $resultMsg") }
}
catch (ex: Exception) {
ex.printStackTrace()
alertMessage("System Error")
}
}
override fun onFailure(call: Call, e: IOException) {
alertMessage("API execute failed")
}
})
Step 3: Check the Transaction
// Check Transaction Status after finishing payment from the payment method.
override fun onRestart() {
super.onRestart()
if(isPayStart) {
isPayStart = false // set to false to prevent request when first start activity and to allow request again
val httpUrl = "$pgUrl/pg/transaction/status".toHttpUrl()
val httpUrlBuilder = httpUrl.newBuilder()
val requestBuilder = Request.Builder().url(httpUrlBuilder.build())
val mediaTypeJson = "application/json".toMediaType()
dataHashMap = HashMap()
dataHashMap["termId"] = termID
dataHashMap["txId"] = txnID
dataHashMap["merchantId"] = merchantId
requestBuilder.post(gsonObject.toJson(dataHashMap).toRequestBody(mediaTypeJson))
client.newCall(requestBuilder.build()).enqueue(object : Callback {
override fun onResponse(call: Call, response: Response) {
try {
val bodyString: String? = response.body?.string()
val jsonData = JSONObject(bodyString!!)
val resultCode = jsonData.getString("resultCode")
val resultMsg = jsonData.getString("resultMsg")
val resultData = jsonData.getString("resultData")
if(resultCode.equals("0000")) {
// Request was successful.
// alert message or go to the result screen.
}
else {
// Request failed.
// alert message or go to the result screen.
}
}
catch (ex: Exception) {
ex.printStackTrace()
// alert message or go to the result screen.
}
}
override fun onFailure(call: Call, e: IOException) {
// Error/Unknown API.
// alert message or go to the error screen.
}
})
}
}
Prepare your Checkout Script
iOS - Swift
// Here is the sample code, So please define it with your own structure project.
Step 1: AppDelegate
// this function is used to check the transaction after the user comes back from payment process.
//add notification when re-open app after finished payment.
func applicationDidBecomeActive(_ application: UIApplication) {
NotificationCenter.default.post(name: UIApplication.didBecomeActiveNotification, object: "")
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
Step 2: In your Activity Class
// Variable
private let deepLink = "" // deep-link provided by PAYON PLC. Dev Team.
private let pgUrl = "http://pgtest.payon.com.kh"
private let termID = "CT03000003"
private let trt = "10"
private var payDvCd = "PAYON_QR"
private var paymentMethod = "PAYON"
private let txnID = Int64(Date().timeIntervalSince1970 * 1000)
private let merchantId = "C0000143"
private let currency = "USD"
private let amount = "1"
private let isPayStart = false // preven auto check transaction start activity.
Step 3: In your Activity Class
// add observer in viewDidLoad function. when user finished payment and back to your payment screen.
override func viewDidLoad() {
super.viewDidLoad()
NotificationCenter.default.addObserver(self, selector: #selector(viewDidBecomeActive), name: UIApplication.didBecomeActiveNotification, object: nil)
}
Step 4: in your Event/Function
// #### Event/Function clicked ####
let payDvCd = "PAYON_QR" // Payon App Pay = "PAYON_QR", Pay With Credit/Debit = "MPI"
let paymentMethod = "PAYON" // Payon App Pay = "PAYON", Pay With Credit/Debit = "CREDIT_DEBIT"
let semaphore = DispatchSemaphore (value: 0)
let parameters = "{\"termId\": \"\(termID)\", \"trt\": \"\(trt)\", \"payDvCd\": \"\(payDvCd)\", \"txId\": \"\(txnID)\", \"merchantId\": \"\(merchantId)\", \"currency\": \"\(currency)\", \"amount\": \"\(amount)\", \"paymentMethod\": \"\(paymentMethod)\"}"
let postData = parameters.data(using: .utf8)
var request = URLRequest(url: URL(string: "\(pgUrl)/pg/order/register")!,timeoutInterval: Double.infinity)
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
request.httpMethod = "POST"
request.httpBody = postData
let task = URLSession.shared.dataTask(with: request) {data, response, error in
guard let data = data else {
print(String(describing: error))
semaphore.signal()
return
}
let jsonString = String(data: data, encoding: .utf8)!
let dataDic = self.convertStringToDictionary(text: jsonString)
let resultCode = dataDic?["resultCode"]! as? String // Response request status code
let resultMsg = dataDic?["resultMsg"]! as? String // Response request status message
let resultData = dataDic?["resultData"]! as? String // Response QR Code
if(resultCode == "0000") {
DispatchQueue.main.async {
let urlString = "\(deepLink)://payon/parameters/?data=\(resultData!)".addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)
let url = URL(string: urlString!)
UIApplication.shared.open(url!) { (result) in
if result {
self.isPayStart = true
print("Open App: \(result)")
}
else {
// Payon App is not installed. Launch AppStore to install Payon app
UIApplication.shared.open(URL(string: 'https://itunes.apple.com/app/id1547237476?mt=8')!) { (result) in
}
}
}
}
}
else {
self.showAlertMessage(messsage: 'Request Error: \(String(describing: resultMsg)), \(String(describing: resultCode)), \(String(describing: resultData))'')
}
semaphore.signal()
}
task.resume()
semaphore.wait()
Step 5: Function to handle checking the Transaction.
// Check Transaction Status after finishing payment from the payment method.
@objc func viewDidBecomeActive() {
if(isPayStart) {
self.isPayStart = false
payDvCd = "PAYON_QR"
paymentMethod = "PAYON"
let semaphore = DispatchSemaphore (value: 0)
let parameters = "{\"termId\": \"\(termID)\", \"txId\": \"\(txnID)\", \"merchantId\": \"\(merchantId)\"}"
let postData = parameters.data(using: .utf8)
var request = URLRequest(url: URL(string: "\(pgUrl)/pg/transaction/status")!,timeoutInterval: Double.infinity)
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
request.httpMethod = "POST"
request.httpBody = postData
let task = URLSession.shared.dataTask(with: request) {data, response, error in
guard let data = data else {
print(String(describing: error))
semaphore.signal()
return
}
let jsonString = String(data: data, encoding: .utf8)!
let dataDic = self.convertStringToDictionary(text: jsonString)
let resultCode = dataDic?["resultCode"]! as? String
let resultMsg = dataDic?["resultMsg"]! as? String
let resultData = dataDic?["resultData"]! as? String
if(resultCode == "0000") {
// The request is successful.
// alert message or go to result screen.
}
else {
// The request is failed.
// alert message or go to result screen.
}
semaphore.signal()
}
task.resume()
semaphore.wait()
}
}
}
Step 6: helper functions
// convert string to dictionary
func convertStringToDictionary(text: String) -> [String: AnyObject]? {
if let data = text.data(using: .utf8) {
do {
let json = try JSONSerialization.jsonObject(with: data, options: .mutableContainers) as? [String:AnyObject]
return json
}
catch {
print("Something went wrong")
}
}
return nil
}
Flutter - Dart
// Here is the sample code, So please define it with your own structure project.
Step 1: Add dependencies
add "http" to your pubspec.yaml (https://pub.dev/packages/http)
Step 2: Create a class to respond networking
// Sample code
class Networking {
String sUrl;
Map<String, String> requestHeader() {
return {"Content-Type": "application/json",
"accept": "application/json" };
}
Uri rquestURL(sUrl) {
String urlString = "${BASE_URL}$sUrl";
return Uri.parse(urlString);
}
Future postRequest(String sBody) {
return http.post(rquestURL(sUrl), body: sBody, headers: requestHeader());
}
Future getRequest() {
return http.get(rquestURL(sUrl), headers: requestHeader());
}
}
Step 3: call it from your activity class
// main.dart
Future<String> requestCardList() async {
Map<String, String> jsonData = {"merchantId": "", "termId": "", "clientId": ""};
Response response = await Networking(sUrl: "/pg/bindingList").postRequest(jsonEncode(jsonData));
if (response.statusCode == 200) {
return response.body;
}
else {
var data = {"data": "make your own respond"};
return "$data";
}
}
React Native
// Here is the sample code
// Here is the sample code, So please define it with your own structure project.
Step 1: Request Function
fetch('http://pgtest.payon.com.kh/pg/bindingList', {
method: 'POST',
body: JSON.stringify({
merchantId: "",
termId: "",
clientId: "",
}),
headers: {
'Content-type': 'application/json; charset=UTF-8',
},
})
.then((response) => response.json())
.then((data) => {
console.log(data);
})
.catch((err) => {
console.log(err.message);
});
Step 2: Call it
<Button
title="Press me"
onPress={() => handleSubmit() }/>
Last updated