lobby url to be send to provider, if provider support call back to lobby
url.cashier
String
N
cashier url to be send to provider, if provider support call back to cashier
****NOTE****
For slots, the format for the call back URL will be
http://{domain_url}/slots/{product_id}/{type}?isMobile=false.
Merchants are required to map this call back URL back to this auth method (section 2. User authentication),
passing in the {product_id} and {type} variable to launch the slot game.
public function __construct()
{
//Get constant from constant.php (AG Code/ AG Token)
$this->kplaytHostname = KPLAYT_HOSTNAME;
$this->kplaytCode = KPLAYT_AG_CODE;
$this->kplaytToken = KPLAYT_AG_TOKEN;
}
public function getGame($gameId,$type,$isMobile)
{
try
{
$memberId = EXAMPLE_MEMBER_ID;
$domainUrl = DOMAIN_URL;
//get DB from constant.php
$servername = DB_SERVER_NAME;
$username = DB_USERNAME;
$password = DB_PASSWORD;
$dbname = DB_NAME;
$conn = new \mysqli($servername, $username, $password, $dbname);
//if DB error
if ($conn->connect_error)
{
var_dump("Connection failed: " . $conn->connect_error);exit;
}
//select id/balance/username from db
$selectBalance = "SELECT a.user_id,a.balance,b.username
FROM user_balance a
LEFT JOIN users b
ON a.user_id = b.id
WHERE a.user_id = ".$memberId;
$db = $conn->query($selectBalance);
if ($db->num_rows > 0)
{
while($row = $db->fetch_assoc())
{
$userId = $row['user_id'];//user id from merchant site
$balance = $row['balance'];//user balance from merchant site
$userName = $row['username']; //user name from merchant site
}
}
else
{
var_dump('USER_DOES_NOT_EXIST');exit;
}
$locale = 'en'; //language (en/ko) English/Korean
$currency = 'USD'; //currently only support “USD”
$hostName = $this->kplaytHostname; // KplayT Hostname
$token = $this->kplaytToken; //AG Token
$agent = $this->kplaytCode; //AG Code
$method = 'auth'; //auth game method
$url = $hostName.$method; //auth game endpoint
//check is it mobile version
if($isMobile == '1' || $isMobile)
{
$isMobile = true;
}
else
{
$isMobile = false;
}
//prepare header
$header = [
'Content-Type: application/json',
'Ag-Code: '.$agent,
'Ag-Token:'.$token,
];
//prepare data
$data = [
'user' =>
[
'id' => $userId
,'name' => $userName
,'language' => $locale
,'currency' => $currency
,'domain_url' => $domainUrl
],
'prd' =>
[
'id' => $gameId
,'type' => $type
,'is_mobile' => $isMobile
]
];
//post header&data via helper curl
$helper = new Helper;
$response = $helper->postData($url,$data,$header);
$data = json_decode($response);
//get IFRAME and KPLAYT ID from response
$iframe = $data->launch_url;
$kplaytId = $data->user_id;
// $txnStatus = $data->txn_status;
//pass these variable to update user details
self::updateUsers($userId,$kplaytId);
//return Iframe
return $iframe;
}
catch(\Exception $e)
{
var_dump($e);exit;
}
}
public static function updateUsers($userId,$kplaytId)
{
try
{
// db connection
$servername = DB_SERVER_NAME;
$username = DB_USERNAME;
$password = DB_PASSWORD;
$dbname = DB_NAME;
$conn = new \mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error)
{
var_dump("Connection failed: " . $conn->connect_error);exit;
}
//insert User to DB
$insertSQL = "INSERT INTO kplayt_users (user_id,kplayt_id)
VALUES (".$userId.",".$kplaytId.")
ON duplicate key UPDATE
kplayt_id = ".$kplaytId;
$db = $conn->query($insertSQL);
}
catch (Exception $e)
{
var_dump($e);exit;
}
}
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Map;
public class GameHandler {
private String kplaytHostname;
private String kplaytCode;
private String kplaytToken;
public GameHandler() {
//Get constant from constant.php (AG Code/ AG Token)
this.kplaytHostname = Constants.KPLAYT_HOSTNAME;
this.kplaytCode = Constants.KPLAYT_AG_CODE;
this.kplaytToken = Constants.KPLAYT_AG_TOKEN;
}
public String getGame(int gameId, String type, boolean isMobile) {
try {
int memberId = Constants.EXAMPLE_MEMBER_ID;
String domainUrl = Constants.DOMAIN_URL;
//get DB from constant.php
String servername = Constants.DB_SERVER_NAME;
String username = Constants.DB_USERNAME;
String password = Constants.DB_PASSWORD;
String dbname = Constants.DB_NAME;
Connection conn = DriverManager.getConnection("jdbc:mysql://" + servername + "/" + dbname, username, password);
//if DB error
if (conn == null) {
System.out.println("Connection failed");
return null;
}
//select id/balance/username from db
String selectBalance = "SELECT a.user_id,a.balance,b.username " +
"FROM user_balance a " +
"LEFT JOIN users b ON a.user_id = b.id " +
"WHERE a.user_id = ?";
PreparedStatement preparedStatement = conn.prepareStatement(selectBalance);
preparedStatement.setInt(1, memberId);
ResultSet db = preparedStatement.executeQuery();
int userId = 0;
int balance = 0;
String userName = "";
if (db.next()) {
userId = db.getInt("user_id");//user id from merchant site
balance = db.getInt("balance");//user balance from merchant site
userName = db.getString("username"); //user name from merchant site
} else {
System.out.println("USER_DOES_NOT_EXIST");
return null;
}
String locale = "en"; //language (en/ko) English/Korean
String currency = "USD"; //currently only support “USD”
String hostName = this.kplaytHostname; // KplayT Hostname
String token = this.kplaytToken; //AG Token
String agent = this.kplaytCode; //AG Code
String method = "auth"; //auth game method
String url = hostName + method; //auth game endpoint
//check is it mobile version
if (isMobile) {
isMobile = true;
} else {
isMobile = false;
}
//prepare header
Map header = new HashMap<>();
header.put("Content-Type", "application/json");
header.put("Ag-Code", agent);
header.put("Ag-Token", token);
//prepare data
Map data = new HashMap<>();
Map userMap = new HashMap<>();
userMap.put("id", userId);
userMap.put("name", userName);
userMap.put("language", locale);
userMap.put("currency", currency);
userMap.put("domain_url", domainUrl);
Map prdMap = new HashMap<>();
prdMap.put("id", gameId);
prdMap.put("type", type);
prdMap.put("is_mobile", isMobile);
data.put("user", userMap);
data.put("prd", prdMap);
//post header&data via helper curl
Helper helper = new Helper();
String response = helper.postData(url, data, header);
//Handle JSON response
// get IFRAME and KPLAYT ID from response
// JSONObject jsonObject = new JSONObject(response);
// String iframe = jsonObject.getString("launch_url");
// String kplaytId = jsonObject.getString("user_id");
// $txnStatus = jsonObject.getString("txn_status");
//pass these variable to update user details
updateUsers(userId, kplaytId);
//return Iframe
return response; // Returning JSON response for now
} catch (SQLException e) {
e.printStackTrace();
return null;
}
}
public static void updateUsers(int userId, int kplaytId) {
try {
// db connection
String servername = Constants.DB_SERVER_NAME;
String username = Constants.DB_USERNAME;
String password = Constants.DB_PASSWORD;
String dbname = Constants.DB_NAME;
Connection conn = DriverManager.getConnection("jdbc:mysql://" + servername + "/" + dbname, username, password);
if (conn == null) {
System.out.println("Connection failed");
return;
}
//insert User to DB
String insertSQL = "INSERT INTO kplayt_users (user_id,kplayt_id) VALUES (?, ?) " +
"ON DUPLICATE KEY UPDATE kplayt_id = ?";
PreparedStatement preparedStatement = conn.prepareStatement(insertSQL);
preparedStatement.setInt(1, userId);
preparedStatement.setInt(2, kplaytId);
preparedStatement.setInt(3, kplaytId);
preparedStatement.executeUpdate();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
using System;
using System.Data.SqlClient;
public class AuthGame
{
private string kplaytHostname;
private string kplaytCode;
private string kplaytToken;
public AuthGame()
{
// Get constants from constant.php (AG Code/ AG Token)
this.kplaytHostname = Constants.KPLAYT_HOSTNAME;
this.kplaytCode = Constants.KPLAYT_AG_CODE;
this.kplaytToken = Constants.KPLAYT_AG_TOKEN;
}
public string GetGame(int gameId, int type, bool isMobile)
{
try
{
int memberId = Constants.EXAMPLE_MEMBER_ID;
string domainUrl = Constants.DOMAIN_URL;
// Get database connection parameters from constant.php
string serverName = Constants.DB_SERVER_NAME;
string username = Constants.DB_USERNAME;
string password = Constants.DB_PASSWORD;
string dbName = Constants.DB_NAME;
using (SqlConnection conn = new SqlConnection($"Server={serverName};Database={dbName};User Id={username};Password={password};"))
{
conn.Open();
// Check if database connection failed
if (conn.State != System.Data.ConnectionState.Open)
{
Console.WriteLine("Database connection failed.");
return null;
}
// Query the database to get user balance and other details
string selectBalance = "SELECT a.user_id, a.balance, b.username FROM user_balance a LEFT JOIN users b ON a.user_id = b.id WHERE a.user_id = @memberId";
using (SqlCommand cmdSelect = new SqlCommand(selectBalance, conn))
{
cmdSelect.Parameters.AddWithValue("@memberId", memberId);
using (SqlDataReader reader = cmdSelect.ExecuteReader())
{
if (reader.Read())
{
int userId = reader.GetInt32(0);
decimal balance = reader.GetDecimal(1);
string userName = reader.GetString(2);
string locale = "en"; // Language (en/ko): English/Korean
string currency = "USD"; // Currently only supports "USD"
string hostName = kplaytHostname; // KplayT Hostname
string token = kplaytToken; // AG Token
string agent = kplaytCode; // AG Code
string method = "auth"; // Auth game method
string url = $"{hostName}{method}"; // Auth game endpoint
// Check if it is a mobile version
bool isMobileValue = isMobile;
// Prepare headers
string[] header = {
"Content-Type: application/json",
"Ag-Code: " + agent,
"Ag-Token: " + token
};
// Prepare data
var data = new
{
user = new
{
id = userId,
name = userName,
language = locale,
currency = currency,
domain_url = domainUrl
},
prd = new
{
id = gameId,
type,
is_mobile = isMobileValue
}
};
// Perform HTTP POST request via a Helper class
Helper helper = new Helper();
string response = helper.PostData(url, data, header);
dynamic responseData = Newtonsoft.Json.JsonConvert.DeserializeObject(response);
// Get the IFRAME and KPLAYT ID from the response
string iframe = responseData.launch_url;
string kplaytId = responseData.user_id;
// Pass these variables to update user details
UpdateUsers(userId, kplaytId);
// Return IFRAME
return iframe;
}
else
{
Console.WriteLine("USER_DOES_NOT_EXIST");
return null;
}
}
}
}
}
catch (Exception e)
{
Console.WriteLine(e.Message);
return null;
}
}
public void UpdateUsers(int userId, string kplaytId)
{
try
{
// Get database connection parameters from constant.php
string serverName = Constants.DB_SERVER_NAME;
string username = Constants.DB_USERNAME;
string password = Constants.DB_PASSWORD;
string dbName = Constants.DB_NAME;
using (SqlConnection conn = new SqlConnection($"Server={serverName};Database={dbName};User Id={username};Password={password};"))
{
conn.Open();
// Check if database connection failed
if (conn.State != System.Data.ConnectionState.Open)
{
Console.WriteLine("Database connection failed.");
return;
}
// Insert user details into the database
string insertSQL = "INSERT INTO kplayt_users (user_id, kplayt_id) VALUES (@userId, @kplaytId) ON DUPLICATE KEY UPDATE kplayt_id = @kplaytId";
using (SqlCommand cmdInsert = new SqlCommand(insertSQL, conn))
{
cmdInsert.Parameters.AddWithValue("@userId", userId);
cmdInsert.Parameters.AddWithValue("@kplaytId", kplaytId);
cmdInsert.ExecuteNonQuery();
}
}
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
}
}
<%
Sub Class_Initialize()
' Get constant from constant.asp (AG Code/ AG Token)
kplaytHostname = KPLAYT_HOSTNAME
kplaytCode = KPLAYT_AG_CODE
kplaytToken = KPLAYT_AG_TOKEN
End Sub
Function GetGame(gameId, type, isMobile)
Dim memberId
memberId = EXAMPLE_MEMBER_ID
domainUrl = DOMAIN_URL
' Get DB from constant.asp
servername = DB_SERVER_NAME
username = DB_USERNAME
password = DB_PASSWORD
dbname = DB_NAME
Set conn = Server.CreateObject("ADODB.Connection")
conn.Open "Provider=SQLOLEDB;Data Source=" & servername & ";Initial Catalog=" & dbname & ";User ID=" & username & ";Password=" & password & ";"
' If DB error
If conn.State = 0 Then
Response.Write "Connection failed: " & conn.Errors(0).Description
Response.End
End If
' Select id/balance/username from db
selectBalance = "SELECT a.user_id, a.balance, b.username " & _
"FROM user_balance a " & _
"LEFT JOIN users b " & _
"ON a.user_id = b.id " & _
"WHERE a.user_id = " & memberId
Set db = conn.Execute(selectBalance)
If Not db.EOF Then
userId = db("user_id") ' user id from merchant site
balance = db("balance") ' user balance from merchant site
userName = db("username") ' user name from merchant site
Else
Response.Write "USER_DOES_NOT_EXIST"
Response.End
End If
locale = "en" ' language (en/ko) English/Korean
currency = "USD" ' currently only support "USD"
hostName = kplaytHostname ' KplayT Hostname
token = kplaytToken ' AG Token
agent = kplaytCode ' AG Code
method = "auth" ' auth game method
url = hostName & method ' auth game endpoint
' Check if it's mobile version
If isMobile = "1" Or isMobile Then
isMobile = True
Else
isMobile = False
End If
' Prepare header
Set header = Server.CreateObject("Scripting.Dictionary")
header.Add "Content-Type", "application/json"
header.Add "Ag-Code", agent
header.Add "Ag-Token", token
' Prepare data
Set data = Server.CreateObject("Scripting.Dictionary")
Set userData = Server.CreateObject("Scripting.Dictionary")
Set prdData = Server.CreateObject("Scripting.Dictionary")
userData.Add "id", userId
userData.Add "name", userName
userData.Add "language", locale
userData.Add "currency", currency
userData.Add "domain_url", domainUrl
prdData.Add "id", gameId
prdData.Add "type", type
prdData.Add "is_mobile", isMobile
data.Add "user", userData
data.Add "prd", prdData
' Post header & data via helper curl
Set helper = Server.CreateObject("MSXML2.ServerXMLHTTP")
helper.Open "POST", url, False
For Each key In header.Keys
helper.setRequestHeader key, header(key)
Next
helper.Send Join(Array("user=", userId, "&name=", userName, "&language=", locale, "¤cy=", currency, "&domain_url=", domainUrl, "&prd=", gameId, "&type=", type, "&is_mobile=", isMobile), "")
responseText = helper.responseText
' Get IFRAME and KPLAYT ID from response
Set jsonData = GetJSON(responseText)
iframe = jsonData("launch_url")
kplaytId = jsonData("user_id")
' txnStatus = jsonData("txn_status")
' Pass these variables to update user details
UpdateUsers userId, kplaytId
' Return Iframe
GetGame = iframe
End Function
Sub UpdateUsers(userId, kplaytId)
' db connection
servername = DB_SERVER_NAME
username = DB_USERNAME
password = DB_PASSWORD
dbname = DB_NAME
Set conn = Server.CreateObject("ADODB.Connection")
conn.Open "Provider=SQLOLEDB;Data Source=" & servername & ";Initial Catalog=" & dbname & ";User ID=" & username & ";Password=" & password & ";"
If conn.State = 0 Then
Response.Write "Connection failed: " & conn.Errors(0).Description
Response.End
End If
' Insert User to DB
insertSQL = "INSERT INTO kplayt_users (user_id, kplayt_id) " & _
"VALUES (" & userId & "," & kplaytId & ") " & _
"ON duplicate key UPDATE kplayt_id = " & kplaytId
conn.Execute insertSQL
End Sub
Function GetJSON(jsonString)
Set js = Server.CreateObject("MSScriptControl.ScriptControl")
js.Language = "JScript"
js.ExecuteStatement "var json = " & jsonString
Set GetJSON = js.Eval("json")
End Function
%>
3. AUTH DEPOSIT
Merchant will call this API to launch the game. API will automatically create or update member's info.
****NOTE****
Every time when merchant call this API, will withdraw money from the last three deposited product
and deposit it to the latest auth product as the auto-transfer.
If the last three deposited products include 5202, 5204, 5209 & 5219, the system will not withdraw money
of decimal value. The decimal money will still remain in that product balance.
Failed deposit or withdrawal amount for auto-transfer will be stored in product id 0 temporary wallet.
HTTP methods : POST
Live Casino URL : <KPLAY endpoint>/auth-deposit
3.1 Request Format
Header
Name
Type
Mandatory
Remark
ag-code
String
Y
ag-token
String
Y
Body
Name
Type
Mandatory
Remark
user
Object
Y
user.id
Number
Y
Unique identifier for member
Length 9
user.name
String
Y
Unique name for the member. Name can not be changed once it is created.
Length 3 – 20
user.language
String
Y
Korean : ko,
English : en
user.currency
String
Y
Member's currency
user.domain_url
String
Y
(FOR SLOT LOBBY)
This field is required to call back to your domain and redirect to the slot game.
lobby url to be send to provider, if provider support call back to lobby
url.cashier
String
N
cashier url to be send to provider, if provider support call back to cashier
deposit
Object
N
deposit.amount
Number
N
Amount to be deposit into provider wallet
deposit.txn_id
Number
N
Self generated unique number
max length = 12
****NOTE****
For slots, the format for the call back URL will be
http://{domain_url}/slots/{product_id}/{type}?isMobile=false.
Merchants are required to map this call back URL back to this auth method (section 2. User authentication),
passing in the {product_id} and {type} variable to launch the slot game.
Merchant can call 8.1 transfer status api
to check deposit/withdraw status and perform retry if require
Attention: Please note that 'txn_status' may equal to 1 (success) even when 'status' is
0 (error). When txn_status is NOT equal to 0, AG should be responsible to deduct the deposit amount from member account.
transactions
Array
List of transactions processed
transactions.txn_id
Number
For auth deposit transaction which deposit to product id 0
(temporary wallet) is merchant sent transaction id
transaction id for auto deposit is self generated by Kplay
transactions.prd_id
Number
Product ID
transactions.amount
Number
Amount to be deposit to or withdraw from provider wallet
transactions.type
Char
d = deposit
w = withdraw
transactions.txn_status
Number
Status for the deposit transaction
0 = failed
1 = success
Merchant can call 8.1 transfer status api
to check deposit/withdraw status and perform retry if required
transactions.error
String
Error Message if txn_status = 0
Response Example
When success
{
"status":1,
"user_id":100018,
"username":"johndoe",
"launch_url":
"http://game.url",
"txn_status":1
"transactions":[
{
"txn_id":99999999,
"prd_id":0,
"amount":"10000.00",
"type":"d",
"txn_status":1
}
{
"txn_id":10000001,
"prd_id":5001,
"amount":"2000.00",
"type":"w",
"txn_status":1
}
{
"txn_id":10000002,
"prd_id":5006,
"amount":"0.00",
"type":"w",
"txn_status":0
}
{
"txn_id":10000003,
"prd_id":5202,
"amount":"12000.00",
"type":"d",
"txn_status":1
}
]
}
When error
{
"status":0,
"error":"ACCESS_DENIED",
"txn_status":0,
"transactions":[]
}
Error Message
Remarks
INTERNAL ERROR
KPLAY internal error
ACCESS_DENIED
Invalid merchant credential is invalid
INVALID_USER
Invalid user id
public function __construct()
{
//Get constant from constant.php (AG Code/ AG Token)
$this->kplaytHostname = KPLAYT_HOSTNAME;
$this->kplaytCode = KPLAYT_AG_CODE;
$this->kplaytToken = KPLAYT_AG_TOKEN;
}
public function getGame($gameId,$type,$isMobile)
{
try
{
$memberId = EXAMPLE_MEMBER_ID;
$domainUrl = DOMAIN_URL;
//get DB from constant.php
$servername = DB_SERVER_NAME;
$username = DB_USERNAME;
$password = DB_PASSWORD;
$dbname = DB_NAME;
$conn = new \mysqli($servername, $username, $password, $dbname);
//if DB error
if ($conn->connect_error)
{
var_dump("Connection failed: " . $conn->connect_error);exit;
}
//select id/balance/username from db
$selectBalance = "SELECT a.user_id,a.balance,b.username
FROM user_balance a
LEFT JOIN users b
ON a.user_id = b.id
WHERE a.user_id = ".$memberId;
$db = $conn->query($selectBalance);
if ($db->num_rows > 0)
{
while($row = $db->fetch_assoc())
{
$userId = $row['user_id'];//user id from merchant site
$balance = $row['balance'];//user balance from merchant site
$userName = $row['username']; //user name from merchant site
}
}
else
{
var_dump('USER_DOES_NOT_EXIST');exit;
}
$locale = 'en'; //language (en/ko) English/Korean
$currency = 'USD'; //currently only support “USD”
$hostName = $this->kplaytHostname; // KplayT Hostname
$token = $this->kplaytToken; //AG Token
$agent = $this->kplaytCode; //AG Code
$method = 'auth-deposit'; //auth deposit method
$url = $hostName.$method; //auth deposit endpoint
//check is it mobile version
if($isMobile == '1' || $isMobile)
{
$isMobile = true;
}
else
{
$isMobile = false;
}
//prepare header
$header = [
'Content-Type: application/json',
'Ag-Code: '.$agent,
'Ag-Token:'.$token,
];
//prepare data
$data = [
'user' =>
[
'id' => $userId
,'name' => $userName
,'language' => $locale
,'currency' => $currency
,'domain_url' => $domainUrl
],
'prd' =>
[
'id' => $gameId
,'type' => $type
,'is_mobile' => $isMobile
]
];
if($gameId != 100) //if not calling slot lobby will provide balance amount to do internal transfer
{
$txn_id = $balance > 0 ? round(microtime(true)*1000) : ''; //generate unique txn id
// txn id cannot be more than 12 digits
$txn_id = (strlen($txn_id) > 12) ? substr($txn_id, 0, 12) : $txn_id;
$deposit = array(
'amount' => $balance
,'txn_id' => $txn_id);
$data['deposit'] = $deposit;
}
//post header&data via helper curl
$helper = new Helper;
$response = $helper->postData($url,$data,$header);
$data = json_decode($response);
//get IFRAME and KPLAYT ID from response
$iframe = $data->launch_url;
$kplaytId = $data->user_id;
$txnStatus = $data->txn_status;
//pass these variable to update user details
self::updateUsers($userId,$kplaytId);
if($txnStatus == 1)
{
$amount = $balance * -1;
self::updateUserBalance($userId,$amount);
}
//return Iframe
return $iframe;
}
catch(\Exception $e)
{
var_dump($e);exit;
}
}
public static function updateUsers($userId,$kplaytId)
{
try
{
// db connection
$servername = DB_SERVER_NAME;
$username = DB_USERNAME;
$password = DB_PASSWORD;
$dbname = DB_NAME;
$conn = new \mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error)
{
var_dump("Connection failed: " . $conn->connect_error);exit;
}
//insert User to DB
$insertSQL = "INSERT INTO kplayt_users (user_id,kplayt_id)
VALUES (".$userId.",".$kplaytId.")
ON duplicate key UPDATE
kplayt_id = ".$kplaytId;
$db = $conn->query($insertSQL);
}
catch (Exception $e)
{
var_dump($e);exit;
}
}
public static function updateUserBalance($userId,$amount)
{
try
{
// db connection
$servername = DB_SERVER_NAME;
$username = DB_USERNAME;
$password = DB_PASSWORD;
$dbname = DB_NAME;
$conn = new \mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error)
{
var_dump("Connection failed: " . $conn->connect_error);exit;
}
// Update user balance
$updateSQL = "UPDATE user_balance
SET balance = balance + ".$amount."
WHERE user_id = ".$userId;
$updateDB = $conn->query($updateSQL);
if($updateDB)
{
//select user balance
$selectBalance = "SELECT a.balance
FROM user_balance a
WHERE user_id = ".$userId;
$db = $conn->query($selectBalance);
if ($db->num_rows > 0)
{
while($row = $db->fetch_assoc())
{
$balance = $row['balance'];//member Balance for KPLAY
return $balance;
}
}
else
{
// return false;
var_dump('INTERNAL_ERROR');exit;
}
}
else
{
return 0;
}
}
catch (Exception $e)
{
var_dump($e);exit;
}
}
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Map;
public class GameHandler {
private String kplaytHostname;
private String kplaytCode;
private String kplaytToken;
public GameHandler() {
// Get constant from constant.php (AG Code/ AG Token)
this.kplaytHostname = Constants.KPLAYT_HOSTNAME;
this.kplaytCode = Constants.KPLAYT_AG_CODE;
this.kplaytToken = Constants.KPLAYT_AG_TOKEN;
}
public String getGame(int gameId, String type, boolean isMobile) {
try {
int memberId = Constants.EXAMPLE_MEMBER_ID;
String domainUrl = Constants.DOMAIN_URL;
// get DB from constant.php
String servername = Constants.DB_SERVER_NAME;
String username = Constants.DB_USERNAME;
String password = Constants.DB_PASSWORD;
String dbname = Constants.DB_NAME;
Connection conn = DriverManager.getConnection("jdbc:mysql://" + servername + "/" + dbname, username, password);
// if DB error
if (conn == null) {
System.out.println("Connection failed");
return null;
}
// select id/balance/username from db
String selectBalance = "SELECT a.user_id, a.balance, b.username " +
"FROM user_balance a " +
"LEFT JOIN users b ON a.user_id = b.id " +
"WHERE a.user_id = ?";
PreparedStatement preparedStatement = conn.prepareStatement(selectBalance);
preparedStatement.setInt(1, memberId);
ResultSet db = preparedStatement.executeQuery();
int userId = 0;
int balance = 0;
String userName = "";
if (db.next()) {
userId = db.getInt("user_id");// user id from merchant site
balance = db.getInt("balance");// user balance from merchant site
userName = db.getString("username"); // user name from merchant site
} else {
System.out.println("USER_DOES_NOT_EXIST");
return null;
}
String locale = "en"; // language (en/ko) English/Korean
String currency = "USD"; // currently only support “USD”
String hostName = this.kplaytHostname; // KplayT Hostname
String token = this.kplaytToken; // AG Token
String agent = this.kplaytCode; // AG Code
String method = "auth-deposit"; // auth deposit method
String url = hostName + method; // auth deposit endpoint
// check is it mobile version
if (isMobile) {
isMobile = true;
} else {
isMobile = false;
}
// prepare header
Map header = new HashMap<>();
header.put("Content-Type", "application/json");
header.put("Ag-Code", agent);
header.put("Ag-Token", token);
// prepare data
Map data = new HashMap<>();
Map userMap = new HashMap<>();
userMap.put("id", userId);
userMap.put("name", userName);
userMap.put("language", locale);
userMap.put("currency", currency);
userMap.put("domain_url", domainUrl);
Map prdMap = new HashMap<>();
prdMap.put("id", gameId);
prdMap.put("type", type);
prdMap.put("is_mobile", isMobile);
data.put("user", userMap);
data.put("prd", prdMap);
if (gameId != 100) { // if not calling slot lobby will provide balance amount to do internal transfer
long txn_id = balance > 0 ? System.currentTimeMillis() : 0; // generate unique txn id
// txn id cannot be more than 12 digits
String txnId = String.valueOf(txn_id).length() > 12 ? String.valueOf(txn_id).substring(0, 12) : String.valueOf(txn_id);
Map deposit = new HashMap<>();
deposit.put("amount", balance);
deposit.put("txn_id", txnId);
data.put("deposit", deposit);
}
// post header&data via helper curl
Helper helper = new Helper();
String response = helper.postData(url, data, header);
// Handle JSON response
// get IFRAME and KPLAYT ID from response
// JSONObject jsonObject = new JSONObject(response);
// String iframe = jsonObject.getString("launch_url");
// String kplaytId = jsonObject.getString("user_id");
// String txnStatus = jsonObject.getString("txn_status");
// pass these variable to update user details
updateUsers(userId, kplaytId);
if (txnStatus.equals("1")) {
int amount = balance * -1;
updateUserBalance(userId, amount);
}
// return Iframe
return response;
} catch (SQLException e) {
e.printStackTrace();
return null;
}
}
public static void updateUsers(int userId, int kplaytId) {
try {
// db connection
String servername = Constants.DB_SERVER_NAME;
String username = Constants.DB_USERNAME;
String password = Constants.DB_PASSWORD;
String dbname = Constants.DB_NAME;
Connection conn = DriverManager.getConnection("jdbc:mysql://" + servername + "/" + dbname, username, password);
if (conn == null) {
System.out.println("Connection failed");
return;
}
// insert User to DB
String insertSQL = "INSERT INTO kplayt_users (user_id,kplayt_id) VALUES (?, ?) " +
"ON DUPLICATE KEY UPDATE kplayt_id = ?";
PreparedStatement preparedStatement = conn.prepareStatement(insertSQL);
preparedStatement.setInt(1, userId);
preparedStatement.setInt(2, kplaytId);
preparedStatement.setInt(3, kplaytId);
preparedStatement.executeUpdate();
} catch (SQLException e) {
e.printStackTrace();
}
}
public static int updateUserBalance(int userId, int amount) {
try {
// db connection
String servername = Constants.DB_SERVER_NAME;
String username = Constants.DB_USERNAME;
String password = Constants.DB_PASSWORD;
String dbname = Constants.DB_NAME;
Connection conn = DriverManager.getConnection("jdbc:mysql://" + servername + "/" + dbname, username, password);
if (conn == null) {
System.out.println("Connection failed");
return 0;
}
// Update user balance
String updateSQL = "UPDATE user_balance " +
"SET balance = balance + ? " +
"WHERE user_id = ?";
PreparedStatement preparedStatement = conn.prepareStatement(updateSQL);
preparedStatement.setInt(1, amount);
preparedStatement.setInt(2, userId);
int updateDB = preparedStatement.executeUpdate();
if (updateDB > 0) {
// select user balance
String selectBalance = "SELECT a.balance " +
"FROM user_balance a " +
"WHERE user_id = ?";
PreparedStatement selectStatement = conn.prepareStatement(selectBalance);
selectStatement.setInt(1, userId);
ResultSet resultSet = selectStatement.executeQuery();
if (resultSet.next()) {
int balance = resultSet.getInt("balance"); // member Balance for KPLAY
return balance;
} else {
System.out.println("INTERNAL_ERROR");
return 0;
}
} else {
return 0;
}
} catch (SQLException e) {
e.printStackTrace();
return 0;
}
}
}
using System;
using System.Data.SqlClient;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
public class AuthGame
{
private string kplaytHostname;
private string kplaytCode;
private string kplaytToken;
public AuthGame()
{
// Get constants from constant.php (AG Code/ AG Token)
this.kplaytHostname = Constants.KPLAYT_HOSTNAME;
this.kplaytCode = Constants.KPLAYT_AG_CODE;
this.kplaytToken = Constants.KPLAYT_AG_TOKEN;
}
public async Task GetGame(int gameId, int type, bool isMobile)
{
try
{
int memberId = Constants.EXAMPLE_MEMBER_ID;
string domainUrl = Constants.DOMAIN_URL;
// Get database connection parameters from constant.php
string serverName = Constants.DB_SERVER_NAME;
string username = Constants.DB_USERNAME;
string password = Constants.DB_PASSWORD;
string dbName = Constants.DB_NAME;
using (SqlConnection conn = new SqlConnection($"Server={serverName};Database={dbName};User Id={username};Password={password};"))
{
conn.Open();
// Check if database connection failed
if (conn.State != System.Data.ConnectionState.Open)
{
Console.WriteLine("Database connection failed.");
return null;
}
// Query the database to get user balance and other details
string selectBalance = "SELECT a.user_id, a.balance, b.username FROM user_balance a LEFT JOIN users b ON a.user_id = b.id WHERE a.user_id = @memberId";
using (SqlCommand cmdSelect = new SqlCommand(selectBalance, conn))
{
cmdSelect.Parameters.AddWithValue("@memberId", memberId);
using (SqlDataReader reader = cmdSelect.ExecuteReader())
{
if (reader.Read())
{
int userId = reader.GetInt32(0);
decimal balance = reader.GetDecimal(1);
string userName = reader.GetString(2);
string locale = "en"; // Language (en/ko): English/Korean
string currency = "USD"; // Currently only supports "USD"
string hostName = this.kplaytHostname; // KplayT Hostname
string token = this.kplaytToken; // AG Token
string agent = this.kplaytCode; // AG Code
string method = "auth-deposit"; // Auth deposit method
string url = $"{hostName}{method}"; // Auth deposit endpoint
// Check if it is a mobile version
bool isMobileValue = isMobile;
// Prepare headers
string[] header = {
"Content-Type: application/json",
"Ag-Code: " + agent,
"Ag-Token: " + token
};
// Prepare data
var data = new
{
user = new
{
id = userId,
name = userName,
language = locale,
currency = currency,
domain_url = domainUrl
},
prd = new
{
id = gameId,
type,
is_mobile = isMobileValue
}
};
if (gameId != 100) // If not calling the slot lobby, provide balance amount for internal transfer
{
string txnId = balance > 0 ? (Math.Round(DateTime.Now.Subtract(new DateTime(1970, 1, 1)).TotalMilliseconds) * 1000).ToString() : ""; // Generate unique txn id
txnId = txnId.Length > 12 ? txnId.Substring(0, 12) : txnId; // Ensure txn id is not more than 12 digits
var deposit = new
{
amount = balance,
txn_id = txnId
};
data.deposit = deposit;
}
// Serialize data to JSON
string jsonData = Newtonsoft.Json.JsonConvert.SerializeObject(data);
// Create a HttpClient instance and send a POST request
using (HttpClient client = new HttpClient())
{
var content = new StringContent(jsonData, Encoding.UTF8, "application/json");
foreach (string h in header)
{
string[] parts = h.Split(':');
client.DefaultRequestHeaders.Add(parts[0], parts[1].Trim());
}
HttpResponseMessage responseMessage = await client.PostAsync(url, content);
string response = await responseMessage.Content.ReadAsStringAsync();
dynamic responseData = Newtonsoft.Json.JsonConvert.DeserializeObject(response);
// Get the IFRAME and KPLAYT ID from the response
string iframe = responseData.launch_url;
string kplaytId = responseData.user_id;
int txnStatus = responseData.txn_status;
// Pass these variables to update user details
UpdateUsers(userId, kplaytId);
if (txnStatus == 1)
{
decimal amount = -balance;
UpdateUserBalance(userId, amount);
}
// Return IFRAME
return iframe;
}
}
else
{
Console.WriteLine("USER_DOES_NOT_EXIST");
return null;
}
}
}
}
}
catch (Exception e)
{
Console.WriteLine(e.Message);
return null;
}
}
public async Task UpdateUsers(int userId, string kplaytId)
{
try
{
// Get database connection parameters from constant.php
string serverName = Constants.DB_SERVER_NAME;
string username = Constants.DB_USERNAME;
string password = Constants.DB_PASSWORD;
string dbName = Constants.DB_NAME;
using (SqlConnection conn = new SqlConnection($"Server={serverName};Database={dbName};User Id={username};Password={password};"))
{
conn.Open();
// Check if database connection failed
if (conn.State != System.Data.ConnectionState.Open)
{
Console.WriteLine("Database connection failed.");
return;
}
// Insert user details into the database
string insertSQL = "INSERT INTO kplayt_users (user_id, kplayt_id) VALUES (@userId, @kplaytId) ON DUPLICATE KEY UPDATE kplayt_id = @kplaytId";
using (SqlCommand cmdInsert = new SqlCommand(insertSQL, conn))
{
cmdInsert.Parameters.AddWithValue("@userId", userId);
cmdInsert.Parameters.AddWithValue("@kplaytId", kplaytId);
await cmdInsert.ExecuteNonQueryAsync();
}
}
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
}
public async Task UpdateUserBalance(int userId, decimal amount)
{
try
{
// Get database connection parameters from constant.php
string serverName = Constants.DB_SERVER_NAME;
string username = Constants.DB_USERNAME;
string password = Constants.DB_PASSWORD;
string dbName = Constants.DB_NAME;
using (SqlConnection conn = new SqlConnection($"Server={serverName};Database={dbName};User Id={username};Password={password};"))
{
conn.Open();
// Check if database connection failed
if (conn.State != System.Data.ConnectionState.Open)
{
Console.WriteLine("Database connection failed.");
return 0;
}
// Update user balance
string updateSQL = "UPDATE user_balance SET balance = balance + @amount WHERE user_id = @userId";
using (SqlCommand cmdUpdate = new SqlCommand(updateSQL, conn))
{
cmdUpdate.Parameters.AddWithValue("@amount", amount);
cmdUpdate.Parameters.AddWithValue("@userId", userId);
await cmdUpdate.ExecuteNonQueryAsync();
// Select user balance
string selectBalance = "SELECT a.balance FROM user_balance a WHERE user_id = @userId";
using (SqlCommand cmdSelectBalance = new SqlCommand(selectBalance, conn))
{
cmdSelectBalance.Parameters.AddWithValue("@userId", userId);
object balanceObj = await cmdSelectBalance.ExecuteScalarAsync();
if (balanceObj != null && balanceObj != DBNull.Value)
{
decimal balance = (decimal)balanceObj;
return balance;
}
}
}
}
return 0;
}
catch (Exception e)
{
Console.WriteLine(e.Message);
return 0;
}
}
}
<%
Class MyClass
Private kplaytHostname
Private kplaytCode
Private kplaytToken
Private Sub Class_Initialize()
' Get constant from constant.asp (AG Code/ AG Token)
kplaytHostname = KPLAYT_HOSTNAME
kplaytCode = KPLAYT_AG_CODE
kplaytToken = KPLAYT_AG_TOKEN
End Sub
Public Function GetGame(gameId, type, isMobile)
On Error Resume Next
Dim memberId
memberId = EXAMPLE_MEMBER_ID
domainUrl = DOMAIN_URL
' get DB from constant.asp
servername = DB_SERVER_NAME
username = DB_USERNAME
password = DB_PASSWORD
dbname = DB_NAME
Set conn = Server.CreateObject("ADODB.Connection")
conn.Open "Provider=SQLOLEDB;Data Source=" & servername & ";Initial Catalog=" & dbname & ";User ID=" & username & ";Password=" & password & ";"
' if DB error
If conn.State = 0 Then
Response.Write "Connection failed: " & conn.Errors(0).Description
Response.End
End If
' select id/balance/username from db
selectBalance = "SELECT a.user_id, a.balance, b.username " & _
"FROM user_balance a " & _
"LEFT JOIN users b " & _
"ON a.user_id = b.id " & _
"WHERE a.user_id = " & memberId
Set db = conn.Execute(selectBalance)
If Not db.EOF Then
userId = db("user_id") ' user id from merchant site
balance = db("balance") ' user balance from merchant site
userName = db("username") ' user name from merchant site
Else
Response.Write "USER_DOES_NOT_EXIST"
Response.End
End If
locale = "en" ' language (en/ko) English/Korean
currency = "USD" ' currently only support "USD"
hostName = kplaytHostname ' KplayT Hostname
token = kplaytToken ' AG Token
agent = kplaytCode ' AG Code
method = "auth-deposit" ' auth deposit method
url = hostName & method ' auth deposit endpoint
' check is it mobile version
If isMobile = "1" Or isMobile Then
isMobile = True
Else
isMobile = False
End If
' prepare header
Set header = Server.CreateObject("Scripting.Dictionary")
header.Add "Content-Type", "application/json"
header.Add "Ag-Code", agent
header.Add "Ag-Token", token
' prepare data
Set data = Server.CreateObject("Scripting.Dictionary")
Set userData = Server.CreateObject("Scripting.Dictionary")
Set prdData = Server.CreateObject("Scripting.Dictionary")
userData.Add "id", userId
userData.Add "name", userName
userData.Add "language", locale
userData.Add "currency", currency
userData.Add "domain_url", domainUrl
prdData.Add "id", gameId
prdData.Add "type", type
prdData.Add "is_mobile", isMobile
data.Add "user", userData
data.Add "prd", prdData
If gameId <> 100 Then ' if not calling slot lobby will provide balance amount to do internal transfer
txn_id = ""
If balance > 0 Then
txn_id = Round(Timer() * 1000)
If Len(txn_id) > 12 Then txn_id = Left(txn_id, 12)
End If
deposit = Server.CreateObject("Scripting.Dictionary")
deposit.Add "amount", balance
deposit.Add "txn_id", txn_id
data.Add "deposit", deposit
End If
' post header & data via helper curl
Set helper = Server.CreateObject("MSXML2.ServerXMLHTTP")
helper.Open "POST", url, False
For Each key In header.Keys
helper.setRequestHeader key, header(key)
Next
helper.Send Join(Array("user=", userId, "&name=", userName, "&language=", locale, "¤cy=", currency, "&domain_url=", domainUrl, "&prd=", gameId, "&type=", type, "&is_mobile=", isMobile), "")
responseText = helper.responseText
' get IFRAME and KPLAYT ID from response
Set jsonData = GetJSON(responseText)
iframe = jsonData("launch_url")
kplaytId = jsonData("user_id")
txnStatus = jsonData("txn_status")
' pass these variable to update user details
UpdateUsers userId, kplaytId
If txnStatus = 1 Then
amount = balance * -1
UpdateUserBalance userId, amount
End If
' return Iframe
GetGame = iframe
End Function
Private Sub UpdateUsers(userId, kplaytId)
' db connection
servername = DB_SERVER_NAME
username = DB_USERNAME
password = DB_PASSWORD
dbname = DB_NAME
Set conn = Server.CreateObject("ADODB.Connection")
conn.Open "Provider=SQLOLEDB;Data Source=" & servername & ";Initial Catalog=" & dbname & ";User ID=" & username & ";Password=" & password & ";"
If conn.State = 0 Then
Response.Write "Connection failed: " & conn.Errors(0).Description
Response.End
End If
' insert User to DB
insertSQL = "INSERT INTO kplayt_users (user_id, kplayt_id) " & _
"VALUES (" & userId & "," & kplaytId & ") " & _
"ON duplicate key UPDATE kplayt_id = " & kplaytId
conn.Execute insertSQL
End Sub
Private Sub UpdateUserBalance(userId, amount)
' db connection
servername = DB_SERVER_NAME
username = DB_USERNAME
password = DB_PASSWORD
dbname = DB_NAME
Set conn = Server.CreateObject("ADODB.Connection")
conn.Open "Provider=SQLOLEDB;Data Source=" & servername & ";Initial Catalog=" & dbname & ";User ID=" & username & ";Password=" & password & ";"
If conn.State = 0 Then
Response.Write "Connection failed: " & conn.Errors(0).Description
Response.End
End If
' Update user balance
updateSQL = "UPDATE user_balance " & _
"SET balance = balance + " & amount & " " & _
"WHERE user_id = " & userId
conn.Execute updateSQL
' select user balance
selectBalance = "SELECT a.balance " & _
"FROM user_balance a " & _
"WHERE user_id = " & userId
Set db = conn.Execute(selectBalance)
If Not db.EOF Then
balance = db("balance") ' member Balance for KPLAY
Response.Write balance ' or return balance or handle it accordingly
Else
' return false or handle error
Response.Write "INTERNAL_ERROR"
End If
End Sub
Private Function GetJSON(jsonString)
Set js = Server.CreateObject("MSScriptControl.ScriptControl")
js.Language = "JScript"
js.ExecuteStatement "var json = " & jsonString
Set GetJSON = js.Eval("json")
End Function
End Class
%>
4. DEPOSIT
Merchant can call this API to deposit money to provider wallet.
HTTP methods : POST
URL : <KPLAY endpoint>/deposit
****NOTE****
New member of the provider below have to access the game first before perform DEPOSIT. BOTA, Taishan, CC88.
4.1 Request Format
Header
Name
Type
Mandatory
Remark
ag-code
String
Y
ag-token
String
Y
Body
Name
Type
Mandatory
Remark
user
Object
Y
user.id
Number
Y
Unique identifier for member
Length 9
user.name
String
Y
Unique name for member, name can not be changed once it is created.
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.util.HashMap;
import java.util.Map;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.google.gson.JsonElement;
public class GetPushBet {
private String dbServerName;
private String dbUsername;
private String dbPassword;
private String dbName;
private String KPLAYHostname;
private String KPLAYCode;
private String KPLAYToken;
public GetPushBet() {
// Get constants from constant.java (DB and KPLAY settings)
this.dbServerName = constant.DB_SERVER_NAME;
this.dbUsername = constant.DB_USERNAME;
this.dbPassword = constant.DB_PASSWORD;
this.dbName = constant.DB_NAME;
this.KPLAYHostname = constant.KPLAY_HOSTNAME;
this.KPLAYCode = constant.KPLAY_CODE;
this.KPLAYToken = constant.KPLAY_TOKEN;
}
public String getPushBet(String prdId, String txnId) {
try {
String method = "getpushbets"; // Push bet method
String url = KPLAYHostname + method;
String token = KPLAYToken;
String agent = KPLAYCode;
// Prepare headers
Map header = new HashMap<>();
header.put("Content-Type", "application/json");
header.put("ag-code", agent);
header.put("ag-token", token);
// Prepare data
Map data = new HashMap<>();
data.put("prd_id", prdId);
data.put("txn_id", txnId);
String response = Helper.postData(url, data, header);
// Parse the response JSON
// (You can use a JSON library like Jackson or Gson for this)
// Example:
JsonParser jsonParser = new JsonParser();
JsonObject jo = (JsonObject)jsonParser.parse(response);
if (jo.get("status").getAsInt() == 1 && jo.has("data")) {
Connection conn = DriverManager.getConnection("jdbc:mysql://" + dbServerName + "/" + dbName, dbUsername, dbPassword);
conn.createStatement().execute("SET NAMES 'UTF8'");
JsonElement jsonData = jo.getAsJsonArray("data").get(0);
String txnIdValue = jsonData.getAsJsonObject().get("txn_id").getAsString();
int pushedAmt = jsonData.getAsJsonObject().get("pushed_amount").getAsInt();
int pushedAmt1 = jsonData.getAsJsonObject().get("pushed_amount1").getAsInt();
String insertQuery = "INSERT INTO pushed_txn (txn_id, prd_id, pushed_amount, pushed_amount1) VALUES (?, ?, ?, ?)";
PreparedStatement stmt = conn.prepareStatement(insertQuery);
stmt.setString(1, txnIdValue);
stmt.setInt(2, Integer.parseInt(prdId));
stmt.setInt(3, pushedAmt);
stmt.setInt(4, pushedAmt1);
stmt.executeUpdate();
stmt.close();
conn.close();
}
return response;
} catch (Exception e) {
e.printStackTrace();
return "";
}
}
public static void main(String[] args) {
GetPushBet pushBet = new GetPushBet();
String response = pushBet.getPushBet("your_prd_id_here", "your_txn_id_here");
System.out.println(response);
}
}
using System;
using System.Data.SqlClient;
using System.Net.Http;
using Newtonsoft.Json;
using System.Collections.Generic;
public class GetPushBet
{
private string servername;
private string username;
private string password;
private string dbname;
private string hostName;
private string token;
private string agent;
private Dictionary header;
public GetPushBet()
{
this.servername = Constants.DB_SERVER_NAME;
this.username = Constants.DB_USERNAME;
this.password = Constants.DB_PASSWORD;
this.dbname = Constants.DB_NAME;
this.hostName = Constants.KPLAYHostname; // Hostname
this.token = Constants.KPLAYToken; // AG Token
this.agent = Constants.KPLAYCode; // AG Code
// Prepare headers
this.header = new Dictionary
{
{ "Content-Type", "application/json" },
{ "Ag-Code", agent },
{ "Ag-Token", token }
};
}
public string GetPushBet(int prdId, string txnId)
{
try
{
string method = "getpushbets"; // Auth game method
string url = hostName + method;
// Prepare data
var data = new Dictionary
{
{ "prd_id", prdId },
{ "txn_id", txnId }
};
using (HttpClient httpClient = new HttpClient())
{
foreach (var headerItem in header)
{
httpClient.DefaultRequestHeaders.Add(headerItem.Key, headerItem.Value);
}
string jsonData = JsonConvert.SerializeObject(data);
HttpContent content = new StringContent(jsonData);
content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/json");
HttpResponseMessage response = httpClient.PostAsync(url, content).Result;
string responseContent = response.Content.ReadAsStringAsync().Result;
dynamic responseData = JsonConvert.DeserializeObject(responseContent);
if (responseData.status == 1 && responseData.data.Count > 0)
{
string connectionString = Constants.DB_CONNECTION_STRING;
using (SqlConnection conn = new SqlConnection(connectionString))
{
conn.Open();
string txnIdFromData = responseData.data[0].txn_id;
int pushedAmt = responseData.data[0].pushed_amount;
int pushedAmt1 = responseData.data[0].pushed_amount1;
string insertPushedTxn = "INSERT INTO pushed_txn (txn_id, prd_id, pushed_amount, pushed_amount1) VALUES (@txnId, @prdId, @pushedAmt, @pushedAmt1)";
using (SqlCommand insertPushedTxnCmd = new SqlCommand(insertPushedTxn, conn))
{
insertPushedTxnCmd.Parameters.AddWithValue("@txnId", txnIdFromData);
insertPushedTxnCmd.Parameters.AddWithValue("@prdId", prdId);
insertPushedTxnCmd.Parameters.AddWithValue("@pushedAmt", pushedAmt);
insertPushedTxnCmd.Parameters.AddWithValue("@pushedAmt1", pushedAmt1);
insertPushedTxnCmd.ExecuteNonQuery();
}
}
}
return responseContent;
}
}
catch (Exception e)
{
Console.WriteLine(e);
return e.ToString();
}
}
}
<%
Sub getPushBet(prdId, txnId)
On Error Resume Next
' Define API parameters
Dim method, url, data, header, conn
method = "getpushbets" ' Auth game method
url = hostName & method
' Prepare data
Set data = Server.CreateObject("Scripting.Dictionary")
data.Add "prd_id", prdId
data.Add "txn_id", txnId
' Create an HTTP request object
Dim xmlhttp
Set xmlhttp = Server.CreateObject("MSXML2.ServerXMLHTTP.6.0")
' Set request headers
Set header = Server.CreateObject("Scripting.Dictionary")
header.Add "Content-Type", "application/json"
' Send a POST request with JSON data
xmlhttp.open "POST", url, False
For Each key In header.Keys
xmlhttp.setRequestHeader key, header(key)
Next
xmlhttp.send JSONStringify(data)
' Check if the request was successful
If xmlhttp.Status = 200 Then
' Parse the JSON response
Dim responseJson
Set responseJson = JSONParse(xmlhttp.responseText)
' Check if the 'status' key exists in the response
If responseJson.Exists("status") Then
If responseJson("status") = 1 Then
' Get data from the response
Set dataArray = responseJson("data")
If Not IsEmpty(dataArray) Then
' Create a database connection
Set conn = Server.CreateObject("ADODB.Connection")
conn.Open "Provider=SQLOLEDB;Data Source=" & serverName & ";Initial Catalog=" & dbName & ";User ID=" &
username & ";Password=" & password & ";"
' Check if the database connection is successful
If Err.Number <> 0 Then
Response.Write "Connection failed: " & Err.Description
Err.Clear
Set conn = Nothing
Exit Sub
End If
conn.Execute "SET NAMES 'UTF8'"
' Get data from the response
txnId = dataArray(0)("txn_id")
pushedAmt = dataArray(0)("pushed_amount")
pushedAmt1 = dataArray(0)("pushed_amount1")
' Prepare and execute the SQL INSERT statement
sql = "INSERT INTO pushed_txn (txn_id, prd_id, pushed_amount, pushed_amount1) VALUES (?, ?, ?, ?)"
Set stmt = conn.Prepare(sql)
stmt.Parameters.Append stmt.CreateParameter("@txnId", 200, 1, Len(txnId), txnId)
stmt.Parameters.Append stmt.CreateParameter("@prdId", 3, 1, 4, prdId)
stmt.Parameters.Append stmt.CreateParameter("@pushedAmt", 3, 1, 4, pushedAmt)
stmt.Parameters.Append stmt.CreateParameter("@pushedAmt1", 3, 1, 4, pushedAmt1)
stmt.Execute
stmt.Close
' Clean up the database connection
conn.Close
Set conn = Nothing
End If
End If
End If
Else
' HTTP request failed
Response.Write "HTTP request failed"
End If
' Clean up objects
Set xmlhttp = Nothing
Set responseJson = Nothing
Set data = Nothing
Set header = Nothing
End Sub
Sub JSONStringify(data)
Dim jsonString, key, value, valueType
jsonString = "{"
For Each key In data.Keys
value = data(key)
valueType = TypeName(value)
If valueType = "String" Then
jsonString = jsonString & """" & key & """:""" & Replace(value, """", "\""") & ""","
ElseIf valueType = "Double" Then
jsonString = jsonString & """" & key & """:" & Replace(value, ",", ".") & ","
ElseIf valueType = "Integer" Then
jsonString = jsonString & """" & key & """:" & value & ","
ElseIf valueType = "Boolean" Then
jsonString = jsonString & """" & key & """:" & IIf(value, "true", "false") & ","
ElseIf valueType = "Dictionary" Then
jsonString = jsonString & """" & key & """:" & JSONStringify(value) & ","
End If
Next
If Right(jsonString, 1) = "," Then
jsonString = Left(jsonString, Len(jsonString) - 1)
End If
jsonString = jsonString & "}"
JSONStringify = jsonString
End Sub
Sub JSONParse(jsonString)
Dim xmlDoc, jsonText
Set xmlDoc = Server.CreateObject("MSXML2.DOMDocument.6.0")
xmlDoc.async = False
xmlDoc.loadXML jsonString
If xmlDoc.parseError.errorCode <> 0 Then
Set JSONParse = Nothing
Exit Sub
End If
Set jsonText = Server.CreateObject("Scripting.Dictionary")
JSONParse = JSONPopulateObject(jsonText, xmlDoc.documentElement)
End Sub
Sub JSONPopulateObject(ByRef obj, xml)
Dim i, xmlNode, nodeName, nodeValue, childNode, childName
For Each xmlNode In xml.childNodes
nodeName = xmlNode.nodeName
nodeValue = xmlNode.nodeValue
If xmlNode.nodeType = 3 Then
obj(nodeName) = nodeValue
ElseIf xmlNode.nodeType = 1 And xmlNode.hasChildNodes Then
Set childNode = Server.CreateObject("Scripting.Dictionary")
JSONPopulateObject childNode, xmlNode
obj(nodeName) = childNode
End If
Next
Set JSONPopulateObject = obj
End Sub
%>
13. WITHDRAW ALL
Merchant can call this API to withdraw money from all available products wallet for member
HTTP methods : POST
URL : <KPLAY endpoint>/withdraw-all
13.1 Request Format
Header
Name
Type
Mandatory
Remark
ag-code
String
Y
ag-token
String
Y
Body
Name
Type
Mandatory
Remark
user
String
Y
user.id
Number
Y
Unique identifier for member
Length 9
user.name
String
Y
Unique name for member, name can not be changed once it is created.
Length 3 - 20
user.currency
String
Y
Member's currency
txn_id
string
Y
Self generated unique number
max length = 12
Request Example
{
"user":{
"id":18,
"name":"test_user",
"currency":"USD",
}
"txn_id":123456
}
13.2 Response Format
Body
Name
Type
Mandatory
Remark
status
Number
Y
0 = failed
1 = success
user_id
Number
Y
username
Number
Y
transaction
Array
Y
transaction.prd_id
Number
Y
transaction.txn_id
Number
Y
transaction.amount
Decimal (10,2)
Y
Money withdrawal
transaction.status
Number
Y
0 = failed
1 = success
2 = unknown
message
String
Y
Message show for status of the withdrawal process
error
String
N
Error message when status = 0
Response Example
When success
{
"status":1,
"user_id":999157,
"username":"AAAchowtest71",
"transaction":[
{
"prd_id":0,
"txn_id":null,
"amount":"0.00",
"status":1
"message":"Balance already 0, no perform withdraw"
},
{
"prd_id":5001,
"txn_id":null,
"amount":"-1.00",
"status":1
"message":"Fail when get balance from provider"
},
{
"prd_id":5010,
"txn_id":null,
"amount":"0.00",
"status":1
"message":"Balance already 0, no perform withdraw"
},
{
"prd_id":5012,
"txn_id":null,
"amount":"0.00",
"status":1
"message":"Balance already 0, no perform withdraw"
using System;
using System.Data.SqlClient;
using Newtonsoft.Json.Linq;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
public class AvailableProductUpdater
{
private const string DB_SERVER_NAME = "YourServerName";
private const string DB_USERNAME = "YourUsername";
private const string DB_PASSWORD = "YourPassword";
private const string DB_NAME = "YourDBName";
private const string KPLAYT_HOSTNAME = "YourKPLAYT_HOSTNAME";
private const string KPLAYT_AG_TOKEN = "YourKPLAYT_AG_TOKEN";
private const string KPLAYT_AG_CODE = "YourKPLAYT_AG_CODE";
public async Task UpdateAvailableProducts()
{
try
{
string serverName = DB_SERVER_NAME;
string username = DB_USERNAME;
string password = DB_PASSWORD;
string dbName = DB_NAME;
using (SqlConnection conn = new SqlConnection($"Server={serverName};Database={dbName};User Id={username};Password={password};"))
{
conn.Open();
// Check if the database connection failed
if (conn.State != System.Data.ConnectionState.Open)
{
Console.WriteLine("Connection failed: " + conn.State);
return;
}
string hostName = KPLAYT_HOSTNAME; // Hostname
string token = KPLAYT_AG_TOKEN; // AG Token
string agent = KPLAYT_AG_CODE; // AG Code
string method = "/available-product";
string[] header = {
"Content-Type: application/json",
"ag-code: " + agent,
"ag-token: " + token
};
string url = hostName + method;
HttpClient httpClient = new HttpClient();
string response = await httpClient.GetStringAsync(url);
dynamic responseData = JObject.Parse(response);
if (responseData != null && responseData.prd != null)
{
if (responseData.status == 1)
{
var prdList = (JArray)responseData.prd;
foreach (var prd in prdList)
{
int prdId = prd["prd_id"].Value();
string sql = "INSERT INTO kplayt_product (product_id) VALUES (@prdId) ON DUPLICATE KEY UPDATE product_id = @prdId";
using (SqlCommand insertStmt = new SqlCommand(sql, conn))
{
insertStmt.Parameters.AddWithValue("@prdId", prdId);
insertStmt.ExecuteNonQuery();
}
}
}
}
else
{
Console.WriteLine("call_api_error");
}
}
}
catch (Exception e)
{
Console.WriteLine("run_cron_error");
Console.WriteLine(e);
}
}
}
<%
On Error Resume Next
Dim servername, username, password, dbname, conn, selectSQL, stmt, result, row, hostName, token, agent, method, url, header, helper, responseText, data, prdList, prdId, sql
servername = DB_SERVER_NAME
username = DB_USERNAME
password = DB_PASSWORD
dbname = DB_NAME
Set conn = Server.CreateObject("ADODB.Connection")
conn.Open "Provider=SQLOLEDB;Data Source=" & servername & ";Initial Catalog=" & dbname & ";User ID=" & username & ";Password=" & password & ";"
If conn.State = 0 Then
Response.Write("connect_db_error")
Response.End
End If
hostName = KPLAYT_HOSTNAME ' Hostname
token = KPLAYT_AG_TOKEN ' Token
agent = KPLAYT_AG_CODE ' Code
method = "/available-product"
Set header = Server.CreateObject("Scripting.Dictionary")
header.Add "Content-Type", "application/json"
header.Add "ag-code", agent
header.Add "ag-token", token
url = hostName & method
Set helper = Server.CreateObject("MSXML2.ServerXMLHTTP")
helper.Open "GET", url, False
For Each key In header.Keys
helper.setRequestHeader key, header(key)
Next
helper.Send
responseText = helper.responseText
Set data = JSON.parse(responseText)
If Not IsEmpty(data) And IsObject(data) And data.Exists("prd") Then
If data("status") = 1 Then
Set prdList = data("prd")
For Each prd In prdList
prdId = prd("prd_id")
sql = "INSERT INTO kplayt_product (product_id) VALUES (?) ON DUPLICATE KEY UPDATE product_id = ?"
Set stmt = conn.Prepare(sql)
stmt.Parameters.Append stmt.CreateParameter("@prdId", 200, 1, 255, prdId)
stmt.Parameters.Append stmt.CreateParameter("@prdId2", 200, 1, 255, prdId)
stmt.Execute
stmt.Close
Next
End If
Else
Response.Write("call_api_error")
Response.End
End If
%>
15. BET DETAIL
Merchant can call this API to get the detail of the bet
HTTP methods : POST
URL : <KPLAY endpoint>/betresults
15.1 Request Format
Header
Name
Type
Mandatory
Remark
ag-code
String
Y
ag-token
String
Y
Body
Name
Type
Mandatory
Remark
lang
String
Y
Korean: ko,
English: en
prd_id
Number
Y
txn_id
string
Y
Request Example
{
"lang":"en",
"prd_id":5001,
"txn_id":"8888888888"
}
15.2 Response Format
If the txn id is valid and successfully retrieves bet detail, we will return a URL that will open the bet detail page. If txn id is not valid or fails to retrieve bet detail, we will respond with the error code.
using System;
using System.Data.SqlClient;
using Newtonsoft.Json.Linq;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
public class RemainingDepositUpdater
{
private const string DB_SERVER_NAME = "YourServerName";
private const string DB_USERNAME = "YourUsername";
private const string DB_PASSWORD = "YourPassword";
private const string DB_NAME = "YourDBName";
private const string KPLAYT_HOSTNAME = "YourKPLAYT_HOSTNAME";
private const string KPLAYT_AG_TOKEN = "YourKPLAYT_AG_TOKEN";
private const string KPLAYT_AG_CODE = "YourKPLAYT_AG_CODE";
private const int EXAMPLE_MEMBER_ID = 123; // Replace with your member ID
public async Task UpdateRemainingDeposit()
{
try
{
string serverName = DB_SERVER_NAME;
string username = DB_USERNAME;
string password = DB_PASSWORD;
string dbName = DB_NAME;
int memberId = EXAMPLE_MEMBER_ID;
using (SqlConnection conn = new SqlConnection($"Server={serverName};Database={dbName};User Id={username};Password={password};"))
{
conn.Open();
// Check if the database connection failed
if (conn.State != System.Data.ConnectionState.Open)
{
Console.WriteLine("Connection failed: " + conn.State);
return;
}
string hostName = KPLAYT_HOSTNAME; // Hostname
string token = KPLAYT_AG_TOKEN; // AG Token
string agent = KPLAYT_AG_CODE; // AG Code
string[] header = {
"Content-Type: application/json",
"ag-code: " + agent,
"ag-token: " + token
};
string method = "/remainingdeposit";
string url = hostName + method;
HttpClient httpClient = new HttpClient();
var response = await httpClient.GetAsync(url);
if (response.IsSuccessStatusCode)
{
var responseContent = await response.Content.ReadAsStringAsync();
JObject data = JObject.Parse(responseContent);
if (data["status"].ToObject() == 1)
{
int givenDeposit = data["given_deposit"].ToObject();
int availableDeposit = data["available_deposit"].ToObject();
string sql = "INSERT INTO remaining_deposit (given_deposit, available_deposit) " +
"VALUES (@givenDeposit, @availableDeposit) " +
"ON DUPLICATE KEY UPDATE given_deposit = @givenDeposit, available_deposit = @availableDeposit";
using (SqlCommand cmd = new SqlCommand(sql, conn))
{
cmd.Parameters.AddWithValue("@givenDeposit", givenDeposit);
cmd.Parameters.AddWithValue("@availableDeposit", availableDeposit);
cmd.ExecuteNonQuery();
}
}
}
else
{
Console.WriteLine("call_api_error");
}
}
}
catch (Exception e)
{
Console.WriteLine("run_cron_error");
Console.WriteLine(e);
}
}
}
<%
On Error Resume Next
Dim servername, username, password, dbname, memberId, conn, hostName, token, agent, header, method, url, helper, responseText, data, givenDeposit, availableDeposit, sql, stmt
servername = DB_SERVER_NAME
username = DB_USERNAME
password = DB_PASSWORD
dbname = DB_NAME
memberId = EXAMPLE_MEMBER_ID
Set conn = Server.CreateObject("ADODB.Connection")
conn.Open "Provider=SQLOLEDB;Data Source=" & servername & ";Initial Catalog=" & dbname & ";User ID=" & username & ";Password=" & password & ";"
If conn.State = 0 Then
Response.Write("connect_db_error")
Response.End
End If
hostName = KPLAYT_HOSTNAME ' Hostname
token = KPLAYT_AG_TOKEN ' Token
agent = KPLAYT_AG_CODE ' Code
Set header = Server.CreateObject("Scripting.Dictionary")
header.Add "Content-Type", "application/json"
header.Add "ag-code", agent
header.Add "ag-token", token
method = "/remainingdeposit"
url = hostName & method
Set helper = Server.CreateObject("MSXML2.ServerXMLHTTP")
helper.Open "GET", url, False
For Each key In header.Keys
helper.setRequestHeader key, header(key)
Next
helper.Send
responseText = helper.responseText
Set data = JSON.parse(responseText)
If Not IsEmpty(data) Then
If data("status") = 1 Then
givenDeposit = data("given_deposit")
availableDeposit = data("available_deposit")
sql = "INSERT INTO remaining_deposit (given_deposit, available_deposit) VALUES (?, ?) " & _
"ON DUPLICATE KEY UPDATE given_deposit = ?, available_deposit = ?"
Set stmt = conn.Execute(sql, Array(givenDeposit, availableDeposit, givenDeposit, availableDeposit))
stmt.Close
End If
Else
Response.Write("call_api_error")
Response.End
End If
%>
17. Get Game Table ID API
Merchants can call this API to get table ID(s) of Evolution based on their current skin setting from KPLAY. For direct launch to specific table purposes.
HTTP methods : GET
URL : <KPLAY endpoint>/getgametable
17.1 Request Format
Header
Field
Type
Description
ag-code
String
KPLAY merchant code
ag-token
String
KPLAY merchant token
17.2 Response Example
Field
Type
Desciptipn
status
Int
0 - error 1 - success
skin_id
Int
The current skin ID of the AG.
game_name
String
The name of the game, from Evolution.
table_id
String
The table ID for direct launch to a specific game table.
game_id
Int
The game ID.
game_type
String
Game Type
error
String
Error message when status = 0
17.3 Response Example
When success
{
"status":1,
"tables":[
{
"skin_id": 9,
"game_name":"Golden Wealth Baccarat",
"game_id": 1,
"table_id":[
"gwbaccarat000001",
"n7ltqx5j25sr7xbe"
],
"game_type":"Baccarat"
},
{
"skin_id": 9,
"game_name":"Baccarat Control Squeeze",
"game_id": 92,
"table_id":[
"k2oswnib7jjaaznw"
],
"game_type":"Baccarat"
}
]
}
18. ERROR MESSAGE
18.1 List of API error message
Header
Error Message
Description
ACCESS_DENIED
Invalid AG credential.
INVALID_PRODUCT
Invalid Product
INVALID_USER
Invalid user information
INVALID_PARAMETER
Missing domain url
INVALID_DATA_TYPE
Invalid format for amount field
MISSING_TXNID
Missing deposit txn_id
DUPLICATED_TXNID
Duplicated txn_id
UNABLE_DEPOSIT_SLOT_LOBBY
Unable deposit with prd_id = 5000
INTERNAL_ERROR
Unknown error
INVALID_NUMBER_FORMAT
Invalid format for number field
UNABLE_DEPOSIT_DECIMAL
Amount contain decimal value
INVALID_TXN_ID
txn_id exist or txn_id longer than 12 digits
UNABLE_DEPOSIT_TEMP_WALLET
Unable deposit to temporary wallet
EXCEED_DEPOSIT_LIMIT
Deposit amount exceed deposit limit
UNABLE_WITHDRAW_DECIMAL_FROM_SPECIFIC_PRODUCT
When withdraw from specific product with decimal amount
INVALID_CREDENTIAL
Member ID not belong to AG
SHARED_WALLET
Shared wallet please refer to note under section 6. Balance
TXN_ID_NOT_EXIST
txn_id not exist
INVALID_LANGUAGE
Invalid language
GAME_INFO_NOT_FOUND
Game round doesn’t exist in system
MISSING_LANGUAGE_FIELD
Language field missing
MISSING_PRD_ID_FIELD
Product ID missing
REQUEST_TOO_FREQUENT
Specific API unable to call too frequent
INVALID_START_DATE
Invalid start date
INVALID_END_DATE
Invalid end date
PERIOD_EXCEED_5_MINUTES
The Gap between start time and end time more than 5 minutes
PREV_DEPOSIT_PENDING
The Previous deposit transfer on the particular member still pending, deposit and transfer status API unavailable until the deposit transfer complete