Try redirect to Checkout Link
Last updated
Was this helpful?
Last updated
Was this helpful?
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.
Add helper for client side to your check out page.
<script th:src="@{../js/payonUtils.js}" charset="utf-8" type="text/javascript"></script>
<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>
In order to process this step. First, you need to . This endpoint will be on back end side implementation.
$("#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
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();
}
?>
$("#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");
});
$("#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();
});
$("#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();
});
$("#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();
});
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'
// 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.
// #### 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")
}
})
// 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.
}
})
}
}
iOS - Swift
// Here is the sample code, So please define it with your own structure project.
// 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.
}
// 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.
// 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)
}
// #### 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()
// 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()
}
}
}
// 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.
add "http" to your pubspec.yaml (https://pub.dev/packages/http)
// 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());
}
}
// 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";
}
}
// Here is the sample code
// Here is the sample code, So please define it with your own structure project.
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);
});
<Button
title="Press me"
onPress={() => handleSubmit() }/>