PHP Sample
Java Sample
.Net Sample
ASP Sample
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 = 'KRW'; //currently only support “KRW”
$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 = "KRW"; //currently only support “KRW”
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 = "KRW"; // Currently only supports "KRW"
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 = "KRW" ' currently only support "KRW"
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
%>
PHP Sample
Java Sample
.Net Sample
ASP Sample
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 = 'KRW'; //currently only support “KRW”
$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 = "KRW"; // currently only support “KRW”
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 = "KRW"; // Currently only supports "KRW"
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 = "KRW" ' currently only support "KRW"
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
%>
PHP Sample
Java Sample
.Net Sample
ASP Sample
function submitTransfer($data)
{
try
{
// db connection
$servername = DB_SERVER_NAME;
$username = DB_USERNAME;
$password = DB_PASSWORD;
$dbname = DB_NAME;
$conn = new \mysqli($servername, $username, $password, $dbname);
//if connect to DB failed
if ($conn->connect_error)
{
return $response = [
'status' => 0
,'error' => 'UNKNOWN_ERROR'
];
}
$param = json_decode($data);
$userId = $param->user_id;
$amount = $param->amount;
$type = $param->type;
$product = $param->prd;
//check if user is exist
$selectSQL = "SELECT username FROM users WHERE id = ".$userId;
$db = $conn->query($selectSQL);
if ($db->num_rows > 0)
{
while($row = $db->fetch_assoc())
{
$userName = $row['username'];
}
}
else
{
return $response = [
'status' => 0
,'error' => 'INVALID_USER'
];
}
$hostName = KPLAYT_HOSTNAME; //Hostname
$token = KPLAYT_AG_TOKEN; //AG Token
$agent = KPLAYT_AG_CODE; //AG Code
$userBalance = self::getUserBalance($userId);
$txn_id = round(microtime(true)*1000);
$txn_id = (strlen($txn_id) > 12) ? substr($txn_id, 0, 12) : $txn_id;
if($type == 'w')
{
$selectSQL = "SELECT kplayt_id FROM kplayt_users WHERE user_id =".$userId;
$db = $conn->query($selectSQL);
if ($db->num_rows > 0)
{
while($row = $db->fetch_assoc())
{
$memberId = $row['kplayt_id'];
}
$walletBalance = new Balance();
$balanceData = array(
'user_id' => $memberId
,'prd' => $product
);
$balanceData = json_encode($balanceData);
$balance = $walletBalance->getMemberBalance($balanceData);
}
else
{
$balance['balance'] = 0;
}
if($balance['balance'] >= $amount)
{
$method = '/withdraw';
$newAmount = $amount;
}
else
{
$response = [
'status' => 0
,'error' => 'Insufficient Wallet Balance'
];
return json_encode($response);
}
}
else
{
if($userBalance >= $amount)
{
$method = '/deposit';
$newAmount = $amount * -1;
}
else
{
$response = [
'status' => 0
,'error' => 'Insufficient Funds'
];
return json_encode($response);
}
}
$url = $hostName.$method;
$header = array('Content-Type: application/json',
'ag-code: '.$agent,
'ag-token:'.$token);
$data = array(
'user' => array(
'id' => $userId
,'name' => $userName
,'currency' => 'KRW' //currently only support KRW
)
,'prd' => $product
,'amount' => $amount
,'txn_id' => $txn_id
);
//post header&data via helper curl
$helper = new Helper;
$response = $helper->postData($url,$data,$header);
$data = json_decode($response);
if($data->txn_status === 1 && $data->status === 1) //success case
{
$walletBalance = self::updateUserBalance($userId,$newAmount);
if($walletBalance)
{
$txnStatus = 1; // txn status 1 == success
$insertSQL = "INSERT INTO funds_transfer (user_id, amount, type, product, txn_id, txn_status)
VALUES (?, ?, ?, ?, ?, ?)";
$stmt = $conn->prepare($insertSQL);
// Bind parameters
$stmt->bind_param("iisiii", $userId, $amount, $type, $product, $txn_id, $txnStatus);
// Execute the statement
if (!$stmt->execute())
{
echo "Error: " . $stmt->error;
}
$stmt->close();
$response = [
'status' => 1
,'balance' => round($data->balance,2)
,'wallet_balance' => $walletBalance
];
self::updateUsers($userId,$data->user_id);
}
else
{
$response = [
'status' => 0
,'error' => 'Internal Error'
];
}
return json_encode($response);
}
elseif($data->txn_status === 0 && ($data->status === 1 || $data->status === 0)) //transfer failed case
{
$txnStatus = 0; // txn status 0 == failed
$insertSQL = "INSERT INTO funds_transfer (user_id, amount, type, product, txn_id, txn_status)
VALUES (?, ?, ?, ?, ?, ?)";
$stmt = $conn->prepare($insertSQL);
// Bind parameters
$stmt->bind_param("iisiii", $userId, $amount, $type, $product, $txn_id, $txnStatus);
// Execute the statement
if (!$stmt->execute())
{
echo "Error: " . $stmt->error;
}
$stmt->close();
$response = [
'status' => 0
,'error' => $data->error
];
return json_encode($response);
}
else //for unkwon case proceed the balance 1st, need process the transaction with cronjob
{
$txnStatus = 2; // txn status 2 == unknown
$walletBalance = self::updateUserBalance($userId,$newAmount);
if($walletBalance)
{
$insertSQL = "INSERT INTO funds_transfer (user_id, amount, type, product, txn_id, txn_status)
VALUES (?, ?, ?, ?, ?, ?)";
$stmt = $conn->prepare($insertSQL);
// Bind parameters
$stmt->bind_param("iisiii", $userId, $amount, $type, $product, $txn_id, $txnStatus);
// Execute the statement
if (!$stmt->execute())
{
echo "Error: " . $stmt->error;
}
$stmt->close();
$response = [
'status' => 1
,'balance' => round($data->balance,2)
,'wallet_balance' => $walletBalance
];
}
else
{
$response = [
'status' => 0
,'error' => 'Internal Error'
];
}
return json_encode($response);
}
}
catch (Exception $e)
{
//if error
return $response = [
'status' => 0
,'error' => 'UNKNOWN_ERROR'
];
}
}
public static function getUserBalance($userId)
{
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;
}
//select user balance
$selectBalance = "SELECT a.user_id,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'];//user balance from merchant site
return $balance;
}
}
else
{
// return false;
var_dump('USER_DOES_NOT_EXIST');exit;
}
}
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'];//user balance from merchant site
return $balance;
}
}
else
{
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 TransferHandler {
public String submitTransfer(String data) {
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 connect to DB failed
if (conn == null) {
Map response = new HashMap<>();
response.put("status", 0);
response.put("error", "UNKNOWN_ERROR");
return new Gson().toJson(response);
}
Map param = new Gson().fromJson(data, Map.class);
int userId = (int) param.get("user_id");
int amount = (int) param.get("amount");
String type = (String) param.get("type");
String product = (String) param.get("prd");
// check if user is exist
String selectSQL = "SELECT username FROM users WHERE id = " + userId;
PreparedStatement preparedStatement = conn.prepareStatement(selectSQL);
ResultSet db = preparedStatement.executeQuery();
String userName = "";
if (db.next()) {
userName = db.getString("username");
} else {
Map response = new HashMap<>();
response.put("status", 0);
response.put("error", "INVALID_USER");
return new Gson().toJson(response);
}
String hostName = Constants.KPLAYT_HOSTNAME; // Hostname
String token = Constants.KPLAYT_AG_TOKEN; // AG Token
String agent = Constants.KPLAYT_AG_CODE; // AG Code
int userBalance = getUserBalance(userId);
long txn_id = System.currentTimeMillis();
txn_id = (String.valueOf(txn_id).length() > 12) ? Long.parseLong(String.valueOf(txn_id).substring(0, 12)) : txn_id;
String method;
int newAmount;
if (type.equals("w")) {
String selectSQL = "SELECT kplayt_id FROM kplayt_users WHERE user_id =" + userId;
db = conn.createStatement().executeQuery(selectSQL);
int memberId = 0;
if (db.next()) {
memberId = db.getInt("kplayt_id");
}
Balance walletBalance = new Balance();
Map balanceData = new HashMap<>();
balanceData.put("user_id", memberId);
balanceData.put("prd", product);
String balanceJson = new Gson().toJson(balanceData);
Map balance = walletBalance.getMemberBalance(balanceJson);
if ((int) balance.get("balance") >= amount) {
method = "/withdraw";
newAmount = amount;
} else {
Map response = new HashMap<>();
response.put("status", 0);
response.put("error", "Insufficient Wallet Balance");
return new Gson().toJson(response);
}
} else {
if (userBalance >= amount) {
method = "/deposit";
newAmount = amount * -1;
} else {
Map response = new HashMap<>();
response.put("status", 0);
response.put("error", "Insufficient Funds");
return new Gson().toJson(response);
}
}
String url = hostName + method;
Map header = new HashMap<>();
header.put("Content-Type", "application/json");
header.put("ag-code", agent);
header.put("ag-token", token);
Map requestData = new HashMap<>();
Map userMap = new HashMap<>();
userMap.put("id", userId);
userMap.put("name", userName);
userMap.put("currency", "KRW"); // currently only support KRW
requestData.put("user", userMap);
requestData.put("prd", product);
requestData.put("amount", amount);
requestData.put("txn_id", txn_id);
// post header&data via helper curl
Helper helper = new Helper();
String response = helper.postData(url, new Gson().toJson(requestData), new Gson().toJson(header));
Map responseData = new Gson().fromJson(response, Map.class);
if ((int) responseData.get("txn_status") == 1 && (int) responseData.get("status") == 1) {
int walletBalance = updateUserBalance(userId, newAmount);
if (walletBalance > 0) {
int txnStatus = 1; // txn status 1 == success
String insertSQL = "INSERT INTO funds_transfer (user_id, amount, type, product, txn_id, txn_status) " +
"VALUES (?, ?, ?, ?, ?, ?)";
PreparedStatement stmt = conn.prepareStatement(insertSQL);
stmt.setInt(1, userId);
stmt.setInt(2, amount);
stmt.setString(3, type);
stmt.setString(4, product);
stmt.setLong(5, txn_id);
stmt.setInt(6, txnStatus);
// Execute the statement
if (!stmt.execute()) {
System.out.println("Error: " + stmt.getWarnings());
}
stmt.close();
Map finalResponse = new HashMap<>();
finalResponse.put("status", 1);
finalResponse.put("balance", Math.round((double) responseData.get("balance") * 100) / 100.0);
finalResponse.put("wallet_balance", walletBalance);
updateUsers(userId, (int) responseData.get("user_id"));
return new Gson().toJson(finalResponse);
} else {
Map finalResponse = new HashMap<>();
finalResponse.put("status", 0);
finalResponse.put("error", "Internal Error");
return new Gson().toJson(finalResponse);
}
} else if ((int) responseData.get("txn_status") == 0 && ((int) responseData.get("status") == 1 || (int) responseData.get("status") == 0)) {
int txnStatus = 0; // txn status 0 == failed
String insertSQL = "INSERT INTO funds_transfer (user_id, amount, type, product, txn_id, txn_status) " +
"VALUES (?, ?, ?, ?, ?, ?)";
PreparedStatement stmt = conn.prepareStatement(insertSQL);
stmt.setInt(1, userId);
stmt.setInt(2, amount);
stmt.setString(3, type);
stmt.setString(4, product);
stmt.setLong(5, txn_id);
stmt.setInt(6, txnStatus);
// Execute the statement
if (!stmt.execute()) {
System.out.println("Error: " + stmt.getWarnings());
}
stmt.close();
Map finalResponse = new HashMap<>();
finalResponse.put("status", 0);
finalResponse.put("error", responseData.get("error"));
return new Gson().toJson(finalResponse);
} else {
int txnStatus = 2; // txn status 2 == unknown
int walletBalance = updateUserBalance(userId, newAmount);
if (walletBalance > 0) {
String insertSQL = "INSERT INTO funds_transfer (user_id, amount, type, product, txn_id, txn_status) " +
"VALUES (?, ?, ?, ?, ?, ?)";
PreparedStatement stmt = conn.prepareStatement(insertSQL);
stmt.setInt(1, userId);
stmt.setInt(2, amount);
stmt.setString(3, type);
stmt.setString(4, product);
stmt.setLong(5, txn_id);
stmt.setInt(6, txnStatus);
// Execute the statement
if (!stmt.execute()) {
System.out.println("Error: " + stmt.getWarnings());
}
stmt.close();
Map finalResponse = new HashMap<>();
finalResponse.put("status", 1);
finalResponse.put("balance", Math.round((double) responseData.get("balance") * 100) / 100.0);
finalResponse.put("wallet_balance", walletBalance);
return new Gson().toJson(finalResponse);
} else {
Map finalResponse = new HashMap<>();
finalResponse.put("status", 0);
finalResponse.put("error", "Internal Error");
return new Gson().toJson(finalResponse);
}
}
} catch (Exception e) {
e.printStackTrace();
Map response = new HashMap<>();
response.put("status", 0);
response.put("error", "UNKNOWN_ERROR");
return new Gson().toJson(response);
}
}
public int getUserBalance(int userId) {
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;
}
String selectBalance = "SELECT a.user_id, a.balance FROM user_balance a WHERE user_id = " + userId;
ResultSet db = conn.createStatement().executeQuery(selectBalance);
int balance = 0;
if (db.next()) {
balance = db.getInt("balance");
} else {
System.out.println("USER_DOES_NOT_EXIST");
}
conn.close();
return balance;
} catch (Exception e) {
e.printStackTrace();
return 0;
}
}
public 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;
}
String insertSQL = "INSERT INTO kplayt_users (user_id,kplayt_id) VALUES (?, ?) ON duplicate key UPDATE kplayt_id = ?";
PreparedStatement stmt = conn.prepareStatement(insertSQL);
stmt.setInt(1, userId);
stmt.setInt(2, kplaytId);
stmt.setInt(3, kplaytId);
// Execute the statement
if (!stmt.execute()) {
System.out.println("Error: " + stmt.getWarnings());
}
stmt.close();
conn.close();
} catch (Exception e) {
e.printStackTrace();
}
}
public 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;
}
String updateSQL = "UPDATE user_balance SET balance = balance + " + amount + " WHERE user_id = " + userId;
boolean updateDB = conn.createStatement().execute(updateSQL);
if (updateDB) {
String selectBalance = "SELECT a.balance FROM user_balance a WHERE user_id = " + userId;
ResultSet db = conn.createStatement().executeQuery(selectBalance);
int balance = 0;
if (db.next()) {
balance = db.getInt("balance");
} else {
System.out.println("INTERNAL_ERROR");
}
conn.close();
return balance;
} else {
return 0;
}
} catch (Exception e) {
e.printStackTrace();
return 0;
}
}
}
using System;
using System.Data.SqlClient;
public class FundsTransfer
{
public static string SubmitTransfer(string data)
{
try
{
// Database connection parameters
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)
{
return JsonConvert.SerializeObject(new { status = 0, error = "UNKNOWN_ERROR" });
}
dynamic param = JsonConvert.DeserializeObject(data);
int userId = param.user_id;
decimal amount = param.amount;
string type = param.type;
string product = param.prd;
// Check if the user exists
string selectSQL = "SELECT username FROM users WHERE id = @userId";
using (SqlCommand cmdSelect = new SqlCommand(selectSQL, conn))
{
cmdSelect.Parameters.AddWithValue("@userId", userId);
using (SqlDataReader reader = cmdSelect.ExecuteReader())
{
if (reader.Read())
{
string userName = reader.GetString(0);
string hostName = Constants.KPLAYT_HOSTNAME; // Hostname
string token = Constants.KPLAYT_AG_TOKEN; // AG Token
string agent = Constants.KPLAYT_AG_CODE; // AG Code
decimal userBalance = GetUserBalance(userId);
long txn_id = (long)(DateTime.Now.Ticks / TimeSpan.TicksPerMillisecond);
// Txn id cannot be more than 12 digits
txn_id = (txn_id.ToString().Length > 12) ? long.Parse(txn_id.ToString().Substring(0, 12)) : txn_id;
string method;
decimal newAmount;
if (type == "w")
{
string selectKplaytSQL = "SELECT kplayt_id FROM kplayt_users WHERE user_id = @userId";
using (SqlCommand cmdSelectKplayt = new SqlCommand(selectKplaytSQL, conn))
{
cmdSelectKplayt.Parameters.AddWithValue("@userId", userId);
using (SqlDataReader kplaytReader = cmdSelectKplayt.ExecuteReader())
{
if (kplaytReader.Read())
{
string memberId = kplaytReader.GetString(0);
Balance walletBalance = new Balance();
dynamic balanceData = new
{
user_id = memberId,
prd = product
};
string balanceDataJson = JsonConvert.SerializeObject(balanceData);
dynamic balance = walletBalance.GetMemberBalance(balanceDataJson);
if (balance.balance >= amount)
{
method = "/withdraw";
newAmount = amount;
}
else
{
return JsonConvert.SerializeObject(new { status = 0, error = "Insufficient Wallet Balance" });
}
}
else
{
return JsonConvert.SerializeObject(new { status = 0, error = "INVALID_USER" });
}
}
}
}
else
{
if (userBalance >= amount)
{
method = "/deposit";
newAmount = amount * -1;
}
else
{
return JsonConvert.SerializeObject(new { status = 0, error = "Insufficient Funds" });
}
}
string url = $"{hostName}{method}";
string[] header = {
"Content-Type: application/json",
"ag-code: " + agent,
"ag-token: " + token
};
dynamic transferData = new
{
user = new
{
id = userId,
name = userName,
currency = "KRW" // Currently only supports KRW
},
prd = product,
amount = amount,
txn_id = txn_id
};
// Perform HTTP POST request via a Helper class
Helper helper = new Helper();
string response = helper.PostData(url, transferData, header);
dynamic data = JsonConvert.DeserializeObject(response);
if (data.txn_status == 1 && data.status == 1) // Success case
{
decimal walletBalance = UpdateUserBalance(userId, newAmount);
if (walletBalance > 0)
{
int txnStatus = 1; // Txn status 1 == success
string insertSQL = "INSERT INTO funds_transfer (user_id, amount, type, product, txn_id, txn_status) " +
"VALUES (@userId, @amount, @type, @product, @txn_id, @txnStatus)";
using (SqlCommand cmdInsert = new SqlCommand(insertSQL, conn))
{
cmdInsert.Parameters.AddWithValue("@userId", userId);
cmdInsert.Parameters.AddWithValue("@amount", amount);
cmdInsert.Parameters.AddWithValue("@type", type);
cmdInsert.Parameters.AddWithValue("@product", product);
cmdInsert.Parameters.AddWithValue("@txn_id", txn_id);
cmdInsert.Parameters.AddWithValue("@txnStatus", txnStatus);
cmdInsert.ExecuteNonQuery();
}
return JsonConvert.SerializeObject(new
{
status = 1,
balance = Math.Round(data.balance, 2),
wallet_balance = walletBalance
});
UpdateUsers(userId, data.user_id);
}
else
{
return JsonConvert.SerializeObject(new { status = 0, error = "Internal Error" });
}
}
else if (data.txn_status == 0 && (data.status == 1 || data.status == 0)) // Transfer failed case
{
int txnStatus = 0; // Txn status 0 == failed
string insertSQL = "INSERT INTO funds_transfer (user_id, amount, type, product, txn_id, txn_status) " +
"VALUES (@userId, @amount, @type, @product, @txn_id, @txnStatus)";
using (SqlCommand cmdInsert = new SqlCommand(insertSQL, conn))
{
cmdInsert.Parameters.AddWithValue("@userId", userId);
cmdInsert.Parameters.AddWithValue("@amount", amount);
cmdInsert.Parameters.AddWithValue("@type", type);
cmdInsert.Parameters.AddWithValue("@product", product);
cmdInsert.Parameters.AddWithValue("@txn_id", txn_id);
cmdInsert.Parameters.AddWithValue("@txnStatus", txnStatus);
cmdInsert.ExecuteNonQuery();
}
return JsonConvert.SerializeObject(new { status = 0, error = data.error });
}
else // For unknown case, proceed the balance first; the transaction will be processed with a cron job
{
int txnStatus = 2; // Txn status 2 == unknown
decimal walletBalance = UpdateUserBalance(userId, newAmount);
if (walletBalance > 0)
{
string insertSQL = "INSERT INTO funds_transfer (user_id, amount, type, product, txn_id, txn_status) " +
"VALUES (@userId, @amount, @type, @product, @txn_id, @txnStatus)";
using (SqlCommand cmdInsert = new SqlCommand(insertSQL, conn))
{
cmdInsert.Parameters.AddWithValue("@userId", userId);
cmdInsert.Parameters.AddWithValue("@amount", amount);
cmdInsert.Parameters.AddWithValue("@type", type);
cmdInsert.Parameters.AddWithValue("@product", product);
cmdInsert.Parameters.AddWithValue("@txn_id", txn_id);
cmdInsert.Parameters.AddWithValue("@txnStatus", txnStatus);
cmdInsert.ExecuteNonQuery();
}
return JsonConvert.SerializeObject(new
{
status = 1,
balance = Math.Round(data.balance, 2),
wallet_balance = walletBalance
});
}
else
{
return JsonConvert.SerializeObject(new { status = 0, error = "Internal Error" });
}
}
}
else
{
return JsonConvert.SerializeObject(new { status = 0, error = "INVALID_USER" });
}
}
}
}
}
catch (Exception e)
{
// If an error occurs
return JsonConvert.SerializeObject(new { status = 0, error = "UNKNOWN_ERROR" });
}
}
public static decimal GetUserBalance(int userId)
{
try
{
// Database connection parameters
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;
}
// Select user balance
string selectBalance = "SELECT a.user_id, a.balance FROM user_balance a WHERE user_id = @userId";
using (SqlCommand cmdSelectBalance = new SqlCommand(selectBalance, conn))
{
cmdSelectBalance.Parameters.AddWithValue("@userId", userId);
using (SqlDataReader reader = cmdSelectBalance.ExecuteReader())
{
if (reader.Read())
{
decimal balance = reader.GetDecimal(1);
return balance;
}
else
{
Console.WriteLine("USER_DOES_NOT_EXIST");
return 0;
}
}
}
}
}
catch (Exception e)
{
Console.WriteLine(e.Message);
return 0;
}
}
public static decimal UpdateUserBalance(int userId, decimal amount)
{
try
{
// Database connection parameters
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("@userId", userId);
cmdUpdate.Parameters.AddWithValue("@amount", amount);
cmdUpdate.ExecuteNonQuery();
}
// 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);
using (SqlDataReader reader = cmdSelectBalance.ExecuteReader())
{
if (reader.Read())
{
decimal balance = reader.GetDecimal(0);
return balance;
}
else
{
Console.WriteLine("INTERNAL_ERROR");
return 0;
}
}
}
}
}
catch (Exception e)
{
Console.WriteLine(e.Message);
return 0;
}
}
}
<%
Function SubmitTransfer(data)
On Error Resume Next
Dim servername, username, password, dbname, conn, param, userId, amount, type, product, selectSQL, db, row, userName, hostName, token, agent, userBalance, txn_id, balance, method, newAmount, walletBalance, responseText, helper, response, jsonData, insertSQL, stmt, txnStatus, updateSQL
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 = "{""status"": 0, ""error"": ""UNKNOWN_ERROR""}"
SubmitTransfer = response
Exit Function
End If
Set param = JSON.parse(data)
userId = param("user_id")
amount = param("amount")
type = param("type")
product = param("prd")
selectSQL = "SELECT username FROM users WHERE id = " & userId
Set db = conn.Execute(selectSQL)
If Not db.EOF Then
userName = db("username")
Else
response = "{""status"": 0, ""error"": ""INVALID_USER""}"
SubmitTransfer = response
Exit Function
End If
hostName = KPLAYT_HOSTNAME ' Hostname
token = KPLAYT_AG_TOKEN ' AG Token
agent = KPLAYT_AG_CODE ' AG Code
userBalance = GetUserBalance(userId)
txn_id = Round(Timer() * 1000)
If Len(txn_id) > 12 Then txn_id = Left(txn_id, 12)
If type = "w" Then
selectSQL = "SELECT kplayt_id FROM kplayt_users WHERE user_id =" & userId
Set db = conn.Execute(selectSQL)
If Not db.EOF Then
memberId = db("kplayt_id")
Set walletBalance = New Balance
balanceData = "{""user_id"": """ & memberId & """, ""prd"": """ & product & """}"
balance = walletBalance.GetMemberBalance(balanceData)
Else
balance = "{""balance"": 0}"
End If
If balance("balance") >= amount Then
method = "/withdraw"
newAmount = amount
Else
response = "{""status"": 0, ""error"": ""Insufficient Wallet Balance""}"
SubmitTransfer = response
Exit Function
End If
Else
If userBalance >= amount Then
method = "/deposit"
newAmount = amount * -1
Else
response = "{""status"": 0, ""error"": ""Insufficient Funds""}"
SubmitTransfer = response
Exit Function
End If
End If
url = hostName & method
Set header = Server.CreateObject("Scripting.Dictionary")
header.Add "Content-Type", "application/json"
header.Add "ag-code", agent
header.Add "ag-token", token
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 "currency", "KRW" ' currently only support KRW
prdData.Add "id", userId
prdData.Add "prd", product
prdData.Add "amount", amount
prdData.Add "txn_id", txn_id
data.Add "user", userData
data.Add "prd", prdData
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, "¤cy=KRW", "&prd=", product, "&amount=", amount, "&txn_id=", txn_id), "")
responseText = helper.responseText
Set jsonData = JSON.parse(responseText)
If jsonData("txn_status") = 1 And jsonData("status") = 1 Then
Set walletBalance = UpdateUserBalance(userId, newAmount)
If Not walletBalance Is Nothing Then
txnStatus = 1 ' txn status 1 == success
insertSQL = "INSERT INTO funds_transfer (user_id, amount, type, product, txn_id, txn_status) VALUES (?, ?, ?, ?, ?, ?)"
Set stmt = conn.Prepare(insertSQL)
stmt.Parameters.Append stmt.CreateParameter(1, 3, 1, 10, userId)
stmt.Parameters.Append stmt.CreateParameter(2, 3, 1, 10, amount)
stmt.Parameters.Append stmt.CreateParameter(3, 200, 1, 50, type)
stmt.Parameters.Append stmt.CreateParameter(4, 200, 1, 50, product)
stmt.Parameters.Append stmt.CreateParameter(5, 3, 1, 10, txn_id)
stmt.Parameters.Append stmt.CreateParameter(6, 3, 1, 10, txnStatus)
stmt.Execute
stmt.Close
response = "{""status"": 1, ""balance"": " & Round(jsonData("balance"), 2) & ", ""wallet_balance"": " & walletBalance & "}"
UpdateUsers userId, jsonData("user_id")
Else
response = "{""status"": 0, ""error"": ""Internal Error""}"
End If
SubmitTransfer = response
ElseIf jsonData("txn_status") = 0 And (jsonData("status") = 1 Or jsonData("status") = 0) Then
txnStatus = 0 ' txn status 0 == failed
insertSQL = "INSERT INTO funds_transfer (user_id, amount, type, product, txn_id, txn_status) VALUES (?, ?, ?, ?, ?, ?)"
Set stmt = conn.Prepare(insertSQL)
stmt.Parameters.Append stmt.CreateParameter(1, 3, 1, 10, userId)
stmt.Parameters.Append stmt.CreateParameter(2, 3, 1, 10, amount)
stmt.Parameters.Append stmt.CreateParameter(3, 200, 1, 50, type)
stmt.Parameters.Append stmt.CreateParameter(4, 200, 1, 50, product)
stmt.Parameters.Append stmt.CreateParameter(5, 3, 1, 10, txn_id)
stmt.Parameters.Append stmt.CreateParameter(6, 3, 1, 10, txnStatus)
stmt.Execute
stmt.Close
response = "{""status"": 0, ""error"": """ & jsonData("error") & """}"
SubmitTransfer = response
Else
txnStatus = 2 ' txn status 2 == unknown
Set walletBalance = UpdateUserBalance(userId, newAmount)
If Not walletBalance Is Nothing Then
insertSQL = "INSERT INTO funds_transfer (user_id, amount, type, product, txn_id, txn_status) VALUES (?, ?, ?, ?, ?, ?)"
Set stmt = conn.Prepare(insertSQL)
stmt.Parameters.Append stmt.CreateParameter(1, 3, 1, 10, userId)
stmt.Parameters.Append stmt.CreateParameter(2, 3, 1, 10, amount)
stmt.Parameters.Append stmt.CreateParameter(3, 200, 1, 50, type)
stmt.Parameters.Append stmt.CreateParameter(4, 200, 1, 50, product)
stmt.Parameters.Append stmt.CreateParameter(5, 3, 1, 10, txn_id)
stmt.Parameters.Append stmt.CreateParameter(6, 3, 1, 10, txnStatus)
stmt.Execute
stmt.Close
response = "{""status"": 1, ""balance"": " & Round(jsonData("balance"), 2) & ", ""wallet_balance"": " & walletBalance & "}"
Else
response = "{""status"": 0, ""error"": ""Internal Error""}"
End If
SubmitTransfer = response
End If
End Function
Function GetUserBalance(userId)
On Error Resume Next
Dim servername, username, password, dbname, conn, selectBalance, db, row, balance
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
GetUserBalance = "USER_DOES_NOT_EXIST"
Exit Function
End If
selectBalance = "SELECT a.user_id, a.balance FROM user_balance a WHERE user_id = " & userId
Set db = conn.Execute(selectBalance)
If Not db.EOF Then
balance = db("balance")
GetUserBalance = balance
Else
GetUserBalance = "USER_DOES_NOT_EXIST"
End If
End Function
Sub UpdateUsers(userId, kplaytId)
On Error Resume Next
Dim servername, username, password, dbname, conn, insertSQL, db
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 Exit Sub
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 UpdateUserBalance(userId, amount)
On Error Resume Next
Dim servername, username, password, dbname, conn, updateSQL, db, balance
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 Exit Function
updateSQL = "UPDATE user_balance SET balance = balance + " & amount & " WHERE user_id = " & userId
conn.Execute updateSQL
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")
UpdateUserBalance = balance
Else
UpdateUserBalance = "INTERNAL_ERROR"
End If
End Function
%>
PHP Sample
Java Sample
.Net Sample
ASP Sample
function submitTransfer($data)
{
try
{
// db connection
$servername = DB_SERVER_NAME;
$username = DB_USERNAME;
$password = DB_PASSWORD;
$dbname = DB_NAME;
$conn = new \mysqli($servername, $username, $password, $dbname);
//if connect to DB failed
if ($conn->connect_error)
{
return $response = [
'status' => 0
,'error' => 'UNKNOWN_ERROR'
];
}
$param = json_decode($data);
$userId = $param->user_id;
$amount = $param->amount;
$type = $param->type;
$product = $param->prd;
//check if user is exist
$selectSQL = "SELECT username FROM users WHERE id = ".$userId;
$db = $conn->query($selectSQL);
if ($db->num_rows > 0)
{
while($row = $db->fetch_assoc())
{
$userName = $row['username'];
}
}
else
{
return $response = [
'status' => 0
,'error' => 'INVALID_USER'
];
}
$hostName = KPLAYT_HOSTNAME; //Hostname
$token = KPLAYT_AG_TOKEN; //AG Token
$agent = KPLAYT_AG_CODE; //AG Code
$userBalance = self::getUserBalance($userId);
$txn_id = round(microtime(true)*1000);
$txn_id = (strlen($txn_id) > 12) ? substr($txn_id, 0, 12) : $txn_id;
if($type == 'w')
{
$selectSQL = "SELECT kplayt_id FROM kplayt_users WHERE user_id =".$userId;
$db = $conn->query($selectSQL);
if ($db->num_rows > 0)
{
while($row = $db->fetch_assoc())
{
$memberId = $row['kplayt_id'];
}
$walletBalance = new Balance();
$balanceData = array(
'user_id' => $memberId
,'prd' => $product
);
$balanceData = json_encode($balanceData);
$balance = $walletBalance->getMemberBalance($balanceData);
}
else
{
$balance['balance'] = 0;
}
if($balance['balance'] >= $amount)
{
$method = '/withdraw';
$newAmount = $amount;
}
else
{
$response = [
'status' => 0
,'error' => 'Insufficient Wallet Balance'
];
return json_encode($response);
}
}
else
{
if($userBalance >= $amount)
{
$method = '/deposit';
$newAmount = $amount * -1;
}
else
{
$response = [
'status' => 0
,'error' => 'Insufficient Funds'
];
return json_encode($response);
}
}
$url = $hostName.$method;
$header = array('Content-Type: application/json',
'ag-code: '.$agent,
'ag-token:'.$token);
$data = array(
'user' => array(
'id' => $userId
,'name' => $userName
,'currency' => 'KRW' //currently only support KRW
)
,'prd' => $product
,'amount' => $amount
,'txn_id' => $txn_id
);
//post header&data via helper curl
$helper = new Helper;
$response = $helper->postData($url,$data,$header);
$data = json_decode($response);
if($data->txn_status === 1 && $data->status === 1) //success case
{
$walletBalance = self::updateUserBalance($userId,$newAmount);
if($walletBalance)
{
$txnStatus = 1; // txn status 1 == success
$insertSQL = "INSERT INTO funds_transfer (user_id, amount, type, product, txn_id, txn_status)
VALUES (?, ?, ?, ?, ?, ?)";
$stmt = $conn->prepare($insertSQL);
// Bind parameters
$stmt->bind_param("iisiii", $userId, $amount, $type, $product, $txn_id, $txnStatus);
// Execute the statement
if (!$stmt->execute())
{
echo "Error: " . $stmt->error;
}
$stmt->close();
$response = [
'status' => 1
,'balance' => round($data->balance,2)
,'wallet_balance' => $walletBalance
];
self::updateUsers($userId,$data->user_id);
}
else
{
$response = [
'status' => 0
,'error' => 'Internal Error'
];
}
return json_encode($response);
}
elseif($data->txn_status === 0 && ($data->status === 1 || $data->status === 0)) //transfer failed case
{
$txnStatus = 0; // txn status 0 == failed
$insertSQL = "INSERT INTO funds_transfer (user_id, amount, type, product, txn_id, txn_status)
VALUES (?, ?, ?, ?, ?, ?)";
$stmt = $conn->prepare($insertSQL);
// Bind parameters
$stmt->bind_param("iisiii", $userId, $amount, $type, $product, $txn_id, $txnStatus);
// Execute the statement
if (!$stmt->execute())
{
echo "Error: " . $stmt->error;
}
$stmt->close();
$response = [
'status' => 0
,'error' => $data->error
];
return json_encode($response);
}
else //for unkwon case proceed the balance 1st, need process the transaction with cronjob
{
$txnStatus = 2; // txn status 2 == unknown
$walletBalance = self::updateUserBalance($userId,$newAmount);
if($walletBalance)
{
$insertSQL = "INSERT INTO funds_transfer (user_id, amount, type, product, txn_id, txn_status)
VALUES (?, ?, ?, ?, ?, ?)";
$stmt = $conn->prepare($insertSQL);
// Bind parameters
$stmt->bind_param("iisiii", $userId, $amount, $type, $product, $txn_id, $txnStatus);
// Execute the statement
if (!$stmt->execute())
{
echo "Error: " . $stmt->error;
}
$stmt->close();
$response = [
'status' => 1
,'balance' => round($data->balance,2)
,'wallet_balance' => $walletBalance
];
}
else
{
$response = [
'status' => 0
,'error' => 'Internal Error'
];
}
return json_encode($response);
}
}
catch (Exception $e)
{
//if error
return $response = [
'status' => 0
,'error' => 'UNKNOWN_ERROR'
];
}
}
public static function getUserBalance($userId)
{
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;
}
//select user balance
$selectBalance = "SELECT a.user_id,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'];//user balance from merchant site
return $balance;
}
}
else
{
// return false;
var_dump('USER_DOES_NOT_EXIST');exit;
}
}
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'];//user balance from merchant site
return $balance;
}
}
else
{
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 TransferHandler {
public String submitTransfer(String data) {
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 connect to DB failed
if (conn == null) {
Map response = new HashMap<>();
response.put("status", 0);
response.put("error", "UNKNOWN_ERROR");
return new Gson().toJson(response);
}
Map param = new Gson().fromJson(data, Map.class);
int userId = (int) param.get("user_id");
int amount = (int) param.get("amount");
String type = (String) param.get("type");
String product = (String) param.get("prd");
// check if user is exist
String selectSQL = "SELECT username FROM users WHERE id = " + userId;
PreparedStatement preparedStatement = conn.prepareStatement(selectSQL);
ResultSet db = preparedStatement.executeQuery();
String userName = "";
if (db.next()) {
userName = db.getString("username");
} else {
Map response = new HashMap<>();
response.put("status", 0);
response.put("error", "INVALID_USER");
return new Gson().toJson(response);
}
String hostName = Constants.KPLAYT_HOSTNAME; // Hostname
String token = Constants.KPLAYT_AG_TOKEN; // AG Token
String agent = Constants.KPLAYT_AG_CODE; // AG Code
int userBalance = getUserBalance(userId);
long txn_id = System.currentTimeMillis();
txn_id = (String.valueOf(txn_id).length() > 12) ? Long.parseLong(String.valueOf(txn_id).substring(0, 12)) : txn_id;
String method;
int newAmount;
if (type.equals("w")) {
String selectSQL = "SELECT kplayt_id FROM kplayt_users WHERE user_id =" + userId;
db = conn.createStatement().executeQuery(selectSQL);
int memberId = 0;
if (db.next()) {
memberId = db.getInt("kplayt_id");
}
Balance walletBalance = new Balance();
Map balanceData = new HashMap<>();
balanceData.put("user_id", memberId);
balanceData.put("prd", product);
String balanceJson = new Gson().toJson(balanceData);
Map balance = walletBalance.getMemberBalance(balanceJson);
if ((int) balance.get("balance") >= amount) {
method = "/withdraw";
newAmount = amount;
} else {
Map response = new HashMap<>();
response.put("status", 0);
response.put("error", "Insufficient Wallet Balance");
return new Gson().toJson(response);
}
} else {
if (userBalance >= amount) {
method = "/deposit";
newAmount = amount * -1;
} else {
Map response = new HashMap<>();
response.put("status", 0);
response.put("error", "Insufficient Funds");
return new Gson().toJson(response);
}
}
String url = hostName + method;
Map header = new HashMap<>();
header.put("Content-Type", "application/json");
header.put("ag-code", agent);
header.put("ag-token", token);
Map requestData = new HashMap<>();
Map userMap = new HashMap<>();
userMap.put("id", userId);
userMap.put("name", userName);
userMap.put("currency", "KRW"); // currently only support KRW
requestData.put("user", userMap);
requestData.put("prd", product);
requestData.put("amount", amount);
requestData.put("txn_id", txn_id);
// post header&data via helper curl
Helper helper = new Helper();
String response = helper.postData(url, new Gson().toJson(requestData), new Gson().toJson(header));
Map responseData = new Gson().fromJson(response, Map.class);
if ((int) responseData.get("txn_status") == 1 && (int) responseData.get("status") == 1) {
int walletBalance = updateUserBalance(userId, newAmount);
if (walletBalance > 0) {
int txnStatus = 1; // txn status 1 == success
String insertSQL = "INSERT INTO funds_transfer (user_id, amount, type, product, txn_id, txn_status) " +
"VALUES (?, ?, ?, ?, ?, ?)";
PreparedStatement stmt = conn.prepareStatement(insertSQL);
stmt.setInt(1, userId);
stmt.setInt(2, amount);
stmt.setString(3, type);
stmt.setString(4, product);
stmt.setLong(5, txn_id);
stmt.setInt(6, txnStatus);
// Execute the statement
if (!stmt.execute()) {
System.out.println("Error: " + stmt.getWarnings());
}
stmt.close();
Map finalResponse = new HashMap<>();
finalResponse.put("status", 1);
finalResponse.put("balance", Math.round((double) responseData.get("balance") * 100) / 100.0);
finalResponse.put("wallet_balance", walletBalance);
updateUsers(userId, (int) responseData.get("user_id"));
return new Gson().toJson(finalResponse);
} else {
Map finalResponse = new HashMap<>();
finalResponse.put("status", 0);
finalResponse.put("error", "Internal Error");
return new Gson().toJson(finalResponse);
}
} else if ((int) responseData.get("txn_status") == 0 && ((int) responseData.get("status") == 1 || (int) responseData.get("status") == 0)) {
int txnStatus = 0; // txn status 0 == failed
String insertSQL = "INSERT INTO funds_transfer (user_id, amount, type, product, txn_id, txn_status) " +
"VALUES (?, ?, ?, ?, ?, ?)";
PreparedStatement stmt = conn.prepareStatement(insertSQL);
stmt.setInt(1, userId);
stmt.setInt(2, amount);
stmt.setString(3, type);
stmt.setString(4, product);
stmt.setLong(5, txn_id);
stmt.setInt(6, txnStatus);
// Execute the statement
if (!stmt.execute()) {
System.out.println("Error: " + stmt.getWarnings());
}
stmt.close();
Map finalResponse = new HashMap<>();
finalResponse.put("status", 0);
finalResponse.put("error", responseData.get("error"));
return new Gson().toJson(finalResponse);
} else {
int txnStatus = 2; // txn status 2 == unknown
int walletBalance = updateUserBalance(userId, newAmount);
if (walletBalance > 0) {
String insertSQL = "INSERT INTO funds_transfer (user_id, amount, type, product, txn_id, txn_status) " +
"VALUES (?, ?, ?, ?, ?, ?)";
PreparedStatement stmt = conn.prepareStatement(insertSQL);
stmt.setInt(1, userId);
stmt.setInt(2, amount);
stmt.setString(3, type);
stmt.setString(4, product);
stmt.setLong(5, txn_id);
stmt.setInt(6, txnStatus);
// Execute the statement
if (!stmt.execute()) {
System.out.println("Error: " + stmt.getWarnings());
}
stmt.close();
Map finalResponse = new HashMap<>();
finalResponse.put("status", 1);
finalResponse.put("balance", Math.round((double) responseData.get("balance") * 100) / 100.0);
finalResponse.put("wallet_balance", walletBalance);
return new Gson().toJson(finalResponse);
} else {
Map finalResponse = new HashMap<>();
finalResponse.put("status", 0);
finalResponse.put("error", "Internal Error");
return new Gson().toJson(finalResponse);
}
}
} catch (Exception e) {
e.printStackTrace();
Map response = new HashMap<>();
response.put("status", 0);
response.put("error", "UNKNOWN_ERROR");
return new Gson().toJson(response);
}
}
public int getUserBalance(int userId) {
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;
}
String selectBalance = "SELECT a.user_id, a.balance FROM user_balance a WHERE user_id = " + userId;
ResultSet db = conn.createStatement().executeQuery(selectBalance);
int balance = 0;
if (db.next()) {
balance = db.getInt("balance");
} else {
System.out.println("USER_DOES_NOT_EXIST");
}
conn.close();
return balance;
} catch (Exception e) {
e.printStackTrace();
return 0;
}
}
public 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;
}
String insertSQL = "INSERT INTO kplayt_users (user_id,kplayt_id) VALUES (?, ?) ON duplicate key UPDATE kplayt_id = ?";
PreparedStatement stmt = conn.prepareStatement(insertSQL);
stmt.setInt(1, userId);
stmt.setInt(2, kplaytId);
stmt.setInt(3, kplaytId);
// Execute the statement
if (!stmt.execute()) {
System.out.println("Error: " + stmt.getWarnings());
}
stmt.close();
conn.close();
} catch (Exception e) {
e.printStackTrace();
}
}
public 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;
}
String updateSQL = "UPDATE user_balance SET balance = balance + " + amount + " WHERE user_id = " + userId;
boolean updateDB = conn.createStatement().execute(updateSQL);
if (updateDB) {
String selectBalance = "SELECT a.balance FROM user_balance a WHERE user_id = " + userId;
ResultSet db = conn.createStatement().executeQuery(selectBalance);
int balance = 0;
if (db.next()) {
balance = db.getInt("balance");
} else {
System.out.println("INTERNAL_ERROR");
}
conn.close();
return balance;
} else {
return 0;
}
} catch (Exception e) {
e.printStackTrace();
return 0;
}
}
}
using System;
using System.Data.SqlClient;
public class FundsTransfer
{
public static string SubmitTransfer(string data)
{
try
{
// Database connection parameters
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)
{
return JsonConvert.SerializeObject(new { status = 0, error = "UNKNOWN_ERROR" });
}
dynamic param = JsonConvert.DeserializeObject(data);
int userId = param.user_id;
decimal amount = param.amount;
string type = param.type;
string product = param.prd;
// Check if the user exists
string selectSQL = "SELECT username FROM users WHERE id = @userId";
using (SqlCommand cmdSelect = new SqlCommand(selectSQL, conn))
{
cmdSelect.Parameters.AddWithValue("@userId", userId);
using (SqlDataReader reader = cmdSelect.ExecuteReader())
{
if (reader.Read())
{
string userName = reader.GetString(0);
string hostName = Constants.KPLAYT_HOSTNAME; // Hostname
string token = Constants.KPLAYT_AG_TOKEN; // AG Token
string agent = Constants.KPLAYT_AG_CODE; // AG Code
decimal userBalance = GetUserBalance(userId);
long txn_id = (long)(DateTime.Now.Ticks / TimeSpan.TicksPerMillisecond);
// Txn id cannot be more than 12 digits
txn_id = (txn_id.ToString().Length > 12) ? long.Parse(txn_id.ToString().Substring(0, 12)) : txn_id;
string method;
decimal newAmount;
if (type == "w")
{
string selectKplaytSQL = "SELECT kplayt_id FROM kplayt_users WHERE user_id = @userId";
using (SqlCommand cmdSelectKplayt = new SqlCommand(selectKplaytSQL, conn))
{
cmdSelectKplayt.Parameters.AddWithValue("@userId", userId);
using (SqlDataReader kplaytReader = cmdSelectKplayt.ExecuteReader())
{
if (kplaytReader.Read())
{
string memberId = kplaytReader.GetString(0);
Balance walletBalance = new Balance();
dynamic balanceData = new
{
user_id = memberId,
prd = product
};
string balanceDataJson = JsonConvert.SerializeObject(balanceData);
dynamic balance = walletBalance.GetMemberBalance(balanceDataJson);
if (balance.balance >= amount)
{
method = "/withdraw";
newAmount = amount;
}
else
{
return JsonConvert.SerializeObject(new { status = 0, error = "Insufficient Wallet Balance" });
}
}
else
{
return JsonConvert.SerializeObject(new { status = 0, error = "INVALID_USER" });
}
}
}
}
else
{
if (userBalance >= amount)
{
method = "/deposit";
newAmount = amount * -1;
}
else
{
return JsonConvert.SerializeObject(new { status = 0, error = "Insufficient Funds" });
}
}
string url = $"{hostName}{method}";
string[] header = {
"Content-Type: application/json",
"ag-code: " + agent,
"ag-token: " + token
};
dynamic transferData = new
{
user = new
{
id = userId,
name = userName,
currency = "KRW" // Currently only supports KRW
},
prd = product,
amount = amount,
txn_id = txn_id
};
// Perform HTTP POST request via a Helper class
Helper helper = new Helper();
string response = helper.PostData(url, transferData, header);
dynamic data = JsonConvert.DeserializeObject(response);
if (data.txn_status == 1 && data.status == 1) // Success case
{
decimal walletBalance = UpdateUserBalance(userId, newAmount);
if (walletBalance > 0)
{
int txnStatus = 1; // Txn status 1 == success
string insertSQL = "INSERT INTO funds_transfer (user_id, amount, type, product, txn_id, txn_status) " +
"VALUES (@userId, @amount, @type, @product, @txn_id, @txnStatus)";
using (SqlCommand cmdInsert = new SqlCommand(insertSQL, conn))
{
cmdInsert.Parameters.AddWithValue("@userId", userId);
cmdInsert.Parameters.AddWithValue("@amount", amount);
cmdInsert.Parameters.AddWithValue("@type", type);
cmdInsert.Parameters.AddWithValue("@product", product);
cmdInsert.Parameters.AddWithValue("@txn_id", txn_id);
cmdInsert.Parameters.AddWithValue("@txnStatus", txnStatus);
cmdInsert.ExecuteNonQuery();
}
return JsonConvert.SerializeObject(new
{
status = 1,
balance = Math.Round(data.balance, 2),
wallet_balance = walletBalance
});
UpdateUsers(userId, data.user_id);
}
else
{
return JsonConvert.SerializeObject(new { status = 0, error = "Internal Error" });
}
}
else if (data.txn_status == 0 && (data.status == 1 || data.status == 0)) // Transfer failed case
{
int txnStatus = 0; // Txn status 0 == failed
string insertSQL = "INSERT INTO funds_transfer (user_id, amount, type, product, txn_id, txn_status) " +
"VALUES (@userId, @amount, @type, @product, @txn_id, @txnStatus)";
using (SqlCommand cmdInsert = new SqlCommand(insertSQL, conn))
{
cmdInsert.Parameters.AddWithValue("@userId", userId);
cmdInsert.Parameters.AddWithValue("@amount", amount);
cmdInsert.Parameters.AddWithValue("@type", type);
cmdInsert.Parameters.AddWithValue("@product", product);
cmdInsert.Parameters.AddWithValue("@txn_id", txn_id);
cmdInsert.Parameters.AddWithValue("@txnStatus", txnStatus);
cmdInsert.ExecuteNonQuery();
}
return JsonConvert.SerializeObject(new { status = 0, error = data.error });
}
else // For unknown case, proceed the balance first; the transaction will be processed with a cron job
{
int txnStatus = 2; // Txn status 2 == unknown
decimal walletBalance = UpdateUserBalance(userId, newAmount);
if (walletBalance > 0)
{
string insertSQL = "INSERT INTO funds_transfer (user_id, amount, type, product, txn_id, txn_status) " +
"VALUES (@userId, @amount, @type, @product, @txn_id, @txnStatus)";
using (SqlCommand cmdInsert = new SqlCommand(insertSQL, conn))
{
cmdInsert.Parameters.AddWithValue("@userId", userId);
cmdInsert.Parameters.AddWithValue("@amount", amount);
cmdInsert.Parameters.AddWithValue("@type", type);
cmdInsert.Parameters.AddWithValue("@product", product);
cmdInsert.Parameters.AddWithValue("@txn_id", txn_id);
cmdInsert.Parameters.AddWithValue("@txnStatus", txnStatus);
cmdInsert.ExecuteNonQuery();
}
return JsonConvert.SerializeObject(new
{
status = 1,
balance = Math.Round(data.balance, 2),
wallet_balance = walletBalance
});
}
else
{
return JsonConvert.SerializeObject(new { status = 0, error = "Internal Error" });
}
}
}
else
{
return JsonConvert.SerializeObject(new { status = 0, error = "INVALID_USER" });
}
}
}
}
}
catch (Exception e)
{
// If an error occurs
return JsonConvert.SerializeObject(new { status = 0, error = "UNKNOWN_ERROR" });
}
}
public static decimal GetUserBalance(int userId)
{
try
{
// Database connection parameters
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;
}
// Select user balance
string selectBalance = "SELECT a.user_id, a.balance FROM user_balance a WHERE user_id = @userId";
using (SqlCommand cmdSelectBalance = new SqlCommand(selectBalance, conn))
{
cmdSelectBalance.Parameters.AddWithValue("@userId", userId);
using (SqlDataReader reader = cmdSelectBalance.ExecuteReader())
{
if (reader.Read())
{
decimal balance = reader.GetDecimal(1);
return balance;
}
else
{
Console.WriteLine("USER_DOES_NOT_EXIST");
return 0;
}
}
}
}
}
catch (Exception e)
{
Console.WriteLine(e.Message);
return 0;
}
}
public static decimal UpdateUserBalance(int userId, decimal amount)
{
try
{
// Database connection parameters
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("@userId", userId);
cmdUpdate.Parameters.AddWithValue("@amount", amount);
cmdUpdate.ExecuteNonQuery();
}
// 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);
using (SqlDataReader reader = cmdSelectBalance.ExecuteReader())
{
if (reader.Read())
{
decimal balance = reader.GetDecimal(0);
return balance;
}
else
{
Console.WriteLine("INTERNAL_ERROR");
return 0;
}
}
}
}
}
catch (Exception e)
{
Console.WriteLine(e.Message);
return 0;
}
}
}
<%
Function SubmitTransfer(data)
On Error Resume Next
Dim servername, username, password, dbname, conn, param, userId, amount, type, product, selectSQL, db, row, userName, hostName, token, agent, userBalance, txn_id, balance, method, newAmount, walletBalance, responseText, helper, response, jsonData, insertSQL, stmt, txnStatus, updateSQL
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 = "{""status"": 0, ""error"": ""UNKNOWN_ERROR""}"
SubmitTransfer = response
Exit Function
End If
Set param = JSON.parse(data)
userId = param("user_id")
amount = param("amount")
type = param("type")
product = param("prd")
selectSQL = "SELECT username FROM users WHERE id = " & userId
Set db = conn.Execute(selectSQL)
If Not db.EOF Then
userName = db("username")
Else
response = "{""status"": 0, ""error"": ""INVALID_USER""}"
SubmitTransfer = response
Exit Function
End If
hostName = KPLAYT_HOSTNAME ' Hostname
token = KPLAYT_AG_TOKEN ' AG Token
agent = KPLAYT_AG_CODE ' AG Code
userBalance = GetUserBalance(userId)
txn_id = Round(Timer() * 1000)
If Len(txn_id) > 12 Then txn_id = Left(txn_id, 12)
If type = "w" Then
selectSQL = "SELECT kplayt_id FROM kplayt_users WHERE user_id =" & userId
Set db = conn.Execute(selectSQL)
If Not db.EOF Then
memberId = db("kplayt_id")
Set walletBalance = New Balance
balanceData = "{""user_id"": """ & memberId & """, ""prd"": """ & product & """}"
balance = walletBalance.GetMemberBalance(balanceData)
Else
balance = "{""balance"": 0}"
End If
If balance("balance") >= amount Then
method = "/withdraw"
newAmount = amount
Else
response = "{""status"": 0, ""error"": ""Insufficient Wallet Balance""}"
SubmitTransfer = response
Exit Function
End If
Else
If userBalance >= amount Then
method = "/deposit"
newAmount = amount * -1
Else
response = "{""status"": 0, ""error"": ""Insufficient Funds""}"
SubmitTransfer = response
Exit Function
End If
End If
url = hostName & method
Set header = Server.CreateObject("Scripting.Dictionary")
header.Add "Content-Type", "application/json"
header.Add "ag-code", agent
header.Add "ag-token", token
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 "currency", "KRW" ' currently only support KRW
prdData.Add "id", userId
prdData.Add "prd", product
prdData.Add "amount", amount
prdData.Add "txn_id", txn_id
data.Add "user", userData
data.Add "prd", prdData
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, "¤cy=KRW", "&prd=", product, "&amount=", amount, "&txn_id=", txn_id), "")
responseText = helper.responseText
Set jsonData = JSON.parse(responseText)
If jsonData("txn_status") = 1 And jsonData("status") = 1 Then
Set walletBalance = UpdateUserBalance(userId, newAmount)
If Not walletBalance Is Nothing Then
txnStatus = 1 ' txn status 1 == success
insertSQL = "INSERT INTO funds_transfer (user_id, amount, type, product, txn_id, txn_status) VALUES (?, ?, ?, ?, ?, ?)"
Set stmt = conn.Prepare(insertSQL)
stmt.Parameters.Append stmt.CreateParameter(1, 3, 1, 10, userId)
stmt.Parameters.Append stmt.CreateParameter(2, 3, 1, 10, amount)
stmt.Parameters.Append stmt.CreateParameter(3, 200, 1, 50, type)
stmt.Parameters.Append stmt.CreateParameter(4, 200, 1, 50, product)
stmt.Parameters.Append stmt.CreateParameter(5, 3, 1, 10, txn_id)
stmt.Parameters.Append stmt.CreateParameter(6, 3, 1, 10, txnStatus)
stmt.Execute
stmt.Close
response = "{""status"": 1, ""balance"": " & Round(jsonData("balance"), 2) & ", ""wallet_balance"": " & walletBalance & "}"
UpdateUsers userId, jsonData("user_id")
Else
response = "{""status"": 0, ""error"": ""Internal Error""}"
End If
SubmitTransfer = response
ElseIf jsonData("txn_status") = 0 And (jsonData("status") = 1 Or jsonData("status") = 0) Then
txnStatus = 0 ' txn status 0 == failed
insertSQL = "INSERT INTO funds_transfer (user_id, amount, type, product, txn_id, txn_status) VALUES (?, ?, ?, ?, ?, ?)"
Set stmt = conn.Prepare(insertSQL)
stmt.Parameters.Append stmt.CreateParameter(1, 3, 1, 10, userId)
stmt.Parameters.Append stmt.CreateParameter(2, 3, 1, 10, amount)
stmt.Parameters.Append stmt.CreateParameter(3, 200, 1, 50, type)
stmt.Parameters.Append stmt.CreateParameter(4, 200, 1, 50, product)
stmt.Parameters.Append stmt.CreateParameter(5, 3, 1, 10, txn_id)
stmt.Parameters.Append stmt.CreateParameter(6, 3, 1, 10, txnStatus)
stmt.Execute
stmt.Close
response = "{""status"": 0, ""error"": """ & jsonData("error") & """}"
SubmitTransfer = response
Else
txnStatus = 2 ' txn status 2 == unknown
Set walletBalance = UpdateUserBalance(userId, newAmount)
If Not walletBalance Is Nothing Then
insertSQL = "INSERT INTO funds_transfer (user_id, amount, type, product, txn_id, txn_status) VALUES (?, ?, ?, ?, ?, ?)"
Set stmt = conn.Prepare(insertSQL)
stmt.Parameters.Append stmt.CreateParameter(1, 3, 1, 10, userId)
stmt.Parameters.Append stmt.CreateParameter(2, 3, 1, 10, amount)
stmt.Parameters.Append stmt.CreateParameter(3, 200, 1, 50, type)
stmt.Parameters.Append stmt.CreateParameter(4, 200, 1, 50, product)
stmt.Parameters.Append stmt.CreateParameter(5, 3, 1, 10, txn_id)
stmt.Parameters.Append stmt.CreateParameter(6, 3, 1, 10, txnStatus)
stmt.Execute
stmt.Close
response = "{""status"": 1, ""balance"": " & Round(jsonData("balance"), 2) & ", ""wallet_balance"": " & walletBalance & "}"
Else
response = "{""status"": 0, ""error"": ""Internal Error""}"
End If
SubmitTransfer = response
End If
End Function
Function GetUserBalance(userId)
On Error Resume Next
Dim servername, username, password, dbname, conn, selectBalance, db, row, balance
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
GetUserBalance = "USER_DOES_NOT_EXIST"
Exit Function
End If
selectBalance = "SELECT a.user_id, a.balance FROM user_balance a WHERE user_id = " & userId
Set db = conn.Execute(selectBalance)
If Not db.EOF Then
balance = db("balance")
GetUserBalance = balance
Else
GetUserBalance = "USER_DOES_NOT_EXIST"
End If
End Function
Sub UpdateUsers(userId, kplaytId)
On Error Resume Next
Dim servername, username, password, dbname, conn, insertSQL, db
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 Exit Sub
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 UpdateUserBalance(userId, amount)
On Error Resume Next
Dim servername, username, password, dbname, conn, updateSQL, db, balance
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 Exit Function
updateSQL = "UPDATE user_balance SET balance = balance + " & amount & " WHERE user_id = " & userId
conn.Execute updateSQL
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")
UpdateUserBalance = balance
Else
UpdateUserBalance = "INTERNAL_ERROR"
End If
End Function
%>
PHP Sample
Java Sample
.Net Sample
ASP Sample
function getMemberBalance($data)
{
try
{
// db connection
$servername = DB_SERVER_NAME;
$username = DB_USERNAME;
$password = DB_PASSWORD;
$dbname = DB_NAME;
$conn = new \mysqli($servername, $username, $password, $dbname);
//if connect to DB failed
if ($conn->connect_error)
{
return $response = [
'status' => 0
,'error' => 'UNKNOWN_ERROR'
];
}
$param = json_decode($data);
$kplaytId = $param->user_id; //member id of kplayt
$prd_id = $param->prd;
//check if user is exist
$selectSQL = "SELECT user_id
FROM kplayt_users
WHERE kplayt_id = ".$kplaytId;
$db = $conn->query($selectSQL);
if ($db->num_rows > 0)
{
while($row = $db->fetch_assoc())
{
$userId = $row['user_id'];
}
}
else
{
return $response = [
'status' => 0
,'error' => 'INVALID_USER'
];
}
$hostName = KPLAYT_HOSTNAME; //Hostname
$token = KPLAYT_AG_TOKEN; //Token
$agent = KPLAYT_AG_CODE; //Code
$method = "/balance";
$url = $hostName.$method;
$header = array('Content-Type: application/json',
'ag-code: '.$agent,
'ag-token:'.$token);
$data = array(
'user' => array(
'id' => $kplaytId
,'currency' => 'KRW' //currently only support “KRW”
)
,'prd' => $prd_id
);
//post header&data via helper curl
$helper = new Helper;
$response = $helper->postData($url,$data,$header);
$data = json_decode($response);
if($data->status == 1)
{
$response = [
'status' => 1
,'prd_id' => $prd_id
,'balance' => $data->balance
];
}
else
{
$response = [
'status' => 1
,'prd_id' => $prd_id
,'balance' => 0.00
];
}
return $response;
}
catch (Exception $e)
{
//if error
return $response = [
'status' => 0
,'error' => 'UNKNOWN_ERROR'
];
}
}
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.HashMap;
import java.util.Map;
public class MemberBalanceHandler {
public Map getMemberBalance(String data) {
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 connect to DB failed
if (conn == null) {
Map response = new HashMap<>();
response.put("status", 0);
response.put("error", "UNKNOWN_ERROR");
return response;
}
Map param = new Gson().fromJson(data, Map.class);
int kplaytId = (int) param.get("user_id"); // member id of kplayt
int prdId = (int) param.get("prd");
// check if user exists
String selectSQL = "SELECT user_id FROM kplayt_users WHERE kplayt_id = " + kplaytId;
PreparedStatement preparedStatement = conn.prepareStatement(selectSQL);
ResultSet db = preparedStatement.executeQuery();
int userId = 0;
if (db.next()) {
userId = db.getInt("user_id");
} else {
Map response = new HashMap<>();
response.put("status", 0);
response.put("error", "INVALID_USER");
return response;
}
String hostName = Constants.KPLAYT_HOSTNAME; // Hostname
String token = Constants.KPLAYT_AG_TOKEN; // Token
String agent = Constants.KPLAYT_AG_CODE; // Code
String method = "/balance";
String url = hostName + method;
Map header = new HashMap<>();
header.put("Content-Type", "application/json");
header.put("ag-code", agent);
header.put("ag-token", token);
Map requestData = new HashMap<>();
Map userMap = new HashMap<>();
userMap.put("id", kplaytId);
userMap.put("currency", "KRW"); // currently only support “KRW”
requestData.put("user", userMap);
requestData.put("prd", prdId);
// post header&data via helper curl
Helper helper = new Helper();
String response = helper.postData(url, new Gson().toJson(requestData), new Gson().toJson(header));
Map responseData = new Gson().fromJson(response, Map.class);
Map finalResponse = new HashMap<>();
finalResponse.put("status", responseData.get("status"));
finalResponse.put("prd_id", prdId);
finalResponse.put("balance", responseData.get("balance"));
return finalResponse;
} catch (Exception e) {
e.printStackTrace();
Map response = new HashMap<>();
response.put("status", 0);
response.put("error", "UNKNOWN_ERROR");
return response;
}
}
}
using System;
using System.Data.SqlClient;
public class MemberBalance
{
public static string GetMemberBalance(string data)
{
try
{
// Database connection parameters
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 the database connection failed
if (conn.State != System.Data.ConnectionState.Open)
{
return JsonConvert.SerializeObject(new { status = 0, error = "UNKNOWN_ERROR" });
}
dynamic param = JsonConvert.DeserializeObject(data);
string kplaytId = param.user_id; // Member ID of Kplayt
int prdId = param.prd;
// Check if the user exists
string selectSQL = "SELECT user_id FROM kplayt_users WHERE kplayt_id = @kplaytId";
using (SqlCommand cmdSelect = new SqlCommand(selectSQL, conn))
{
cmdSelect.Parameters.AddWithValue("@kplaytId", kplaytId);
using (SqlDataReader reader = cmdSelect.ExecuteReader())
{
if (reader.Read())
{
int userId = reader.GetInt32(0);
string hostName = Constants.KPLAYT_HOSTNAME; // Hostname
string token = Constants.KPLAYT_AG_TOKEN; // Token
string agent = Constants.KPLAYT_AG_CODE; // Code
string method = "/balance";
string url = $"{hostName}{method}";
string[] header = {
"Content-Type: application/json",
"ag-code: " + agent,
"ag-token: " + token
};
dynamic postData = new
{
user = new
{
id = kplaytId,
currency = "KRW" // Currently only supports "KRW"
},
prd = prdId
};
// Perform HTTP POST request via a Helper class
Helper helper = new Helper();
string response = helper.PostData(url, postData, header);
dynamic responseData = JsonConvert.DeserializeObject(response);
if (responseData.status == 1)
{
return JsonConvert.SerializeObject(new
{
status = 1,
prd_id = prdId,
balance = responseData.balance
});
}
else
{
return JsonConvert.SerializeObject(new
{
status = 1,
prd_id = prdId,
balance = 0.00
});
}
}
else
{
return JsonConvert.SerializeObject(new { status = 0, error = "INVALID_USER" });
}
}
}
}
}
catch (Exception e)
{
// If an error occurs
return JsonConvert.SerializeObject(new { status = 0, error = "UNKNOWN_ERROR" });
}
}
}
<%
Function GetMemberBalance(data)
On Error Resume Next
Dim servername, username, password, dbname, conn, param, kplaytId, prd_id, selectSQL, db, row, userId, hostName, token, agent, method, url, header, requestData, helper, responseText, responseData, response
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 = "{""status"": 0, ""error"": ""UNKNOWN_ERROR""}"
GetMemberBalance = response
Exit Function
End If
Set param = JSON.parse(data)
kplaytId = param("user_id") ' member id of kplayt
prd_id = param("prd")
selectSQL = "SELECT user_id FROM kplayt_users WHERE kplayt_id = " & kplaytId
Set db = conn.Execute(selectSQL)
If Not db.EOF Then
userId = db("user_id")
Else
response = "{""status"": 0, ""error"": ""INVALID_USER""}"
GetMemberBalance = response
Exit Function
End If
hostName = KPLAYT_HOSTNAME ' Hostname
token = KPLAYT_AG_TOKEN ' Token
agent = KPLAYT_AG_CODE ' Code
method = "/balance"
url = hostName & method
Set header = Server.CreateObject("Scripting.Dictionary")
header.Add "Content-Type", "application/json"
header.Add "ag-code", agent
header.Add "ag-token", token
Set requestData = Server.CreateObject("Scripting.Dictionary")
Set userData = Server.CreateObject("Scripting.Dictionary")
userData.Add "id", kplaytId
userData.Add "currency", "KRW" ' currently only support “KRW”
requestData.Add "user", userData
requestData.Add "prd", prd_id
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=", kplaytId, "¤cy=KRW", "&prd=", prd_id), "")
responseText = helper.responseText
Set responseData = JSON.parse(responseText)
If responseData("status") = 1 Then
response = "{""status"": 1, ""prd_id"": """ & prd_id & """, ""balance"": " & responseData("balance") & "}"
Else
response = "{""status"": 1, ""prd_id"": """ & prd_id & """, ""balance"": 0.00}"
End If
GetMemberBalance = response
End Function
%>
PHP Sample
Java Sample
.Net Sample
ASP Sample
try
{
$servername = DB_SERVER_NAME;
$username = DB_USERNAME;
$password = DB_PASSWORD;
$dbname = DB_NAME;
$memberId = EXAMPLE_MEMBER_ID;
$conn = new \mysqli($servername, $username, $password, $dbname);
//if connect to DB failed
if ($conn->connect_error)
{
error_log('connect_db_error');
exit;
}
$hostName = KPLAYT_HOSTNAME; //Hostname
$token = KPLAYT_AG_TOKEN; //AG Token
$agent = KPLAYT_AG_CODE; //AG Code
$method = '/balance-all';
$header = array('Content-Type: application/json',
'ag-code: '.$agent,
'ag-token:'.$token);
$stmt = $conn->prepare("SELECT kplayt_id FROM kplayt_users WHERE user_id = ?");
$stmt->bind_param("s", $memberId);
$stmt->execute();
$result = $stmt->get_result();
$db = $result->fetch_all(MYSQLI_ASSOC);
$stmt->close();
if (count($db) == 0)
{
error_log('run_cron_error');
exit;
}
$kplaytId = $db[0]['kplayt_id'];
$data = [
'user' => [
'id' => $kplaytId,
'currency' => 'KRW'
]
];
$url = $hostName.$method;
$helper = new Helper;
$response = $helper->postData($url,$data,$header);
$data = json_decode($response);
if (!empty($data) && array_key_exists('data', $data))
{
if ($data->status == 1)
{
$prodBalances = (array) $data->data;
foreach ($prodBalances as $prodBalance)
{
$prdId = $prodBalance->prd_id;
$balance = $prodBalance->balance;
$status = $prodBalance->status;
$sql = "INSERT INTO kplayt_member_prod_balance (member_id, prd_id, balance, status)
VALUES (?, ?, ?, ?)
ON DUPLICATE KEY UPDATE
balance = ?,
status = ?";
$stmt = $conn->prepare($sql);
$stmt->bind_param("iiiiii", $memberId, $prdId, $balance, $status, $balance, $status);
$stmt->execute();
$stmt->close();
}
}
}
else
{
error_log('call_api_error');
exit;
}
}
catch (Exception $e)
{
error_log('run_cron_error');
exit;
}
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;
public class BalanceAllCronJob {
public void executeCron() {
try {
String servername = Constants.DB_SERVER_NAME;
String username = Constants.DB_USERNAME;
String password = Constants.DB_PASSWORD;
String dbname = Constants.DB_NAME;
String memberId = Constants.EXAMPLE_MEMBER_ID;
Connection conn = DriverManager.getConnection("jdbc:mysql://" + servername + "/" + dbname, username, password);
if (conn == null) {
System.out.println("connect_db_error");
return;
}
String hostName = Constants.KPLAYT_HOSTNAME;
String token = Constants.KPLAYT_AG_TOKEN;
String agent = Constants.KPLAYT_AG_CODE;
String method = "/balance-all";
String[] header = {
"Content-Type: application/json",
"ag-code: " + agent,
"ag-token:" + token
};
PreparedStatement stmt = conn.prepareStatement("SELECT kplayt_id FROM kplayt_users WHERE user_id = ?");
stmt.setString(1, memberId);
ResultSet result = stmt.executeQuery();
List db = new ArrayList<>();
while (result.next()) {
db.add(result.getString("kplayt_id"));
}
stmt.close();
if (db.size() == 0) {
System.out.println("run_cron_error");
return;
}
String kplaytId = db.get(0);
String postData = "{\"user\": {\"id\": \"" + kplaytId + "\", \"currency\": \"KRW\"}}";
String url = hostName + method;
Helper helper = new Helper();
String response = helper.postData(url, postData, header);
// Assuming a Helper method to parse JSON response is available
Map data = Helper.parseJson(response);
if (data != null && data.containsKey("data")) {
Map[] prodBalances = (Map[]) data.get("data");
for (Map prodBalance : prodBalances) {
int prdId = (int) prodBalance.get("prd_id");
double balance = (double) prodBalance.get("balance");
int status = (int) prodBalance.get("status");
String sql = "INSERT INTO kplayt_member_prod_balance (member_id, prd_id, balance, status)" +
" VALUES (?, ?, ?, ?)" +
" ON DUPLICATE KEY UPDATE" +
" balance = ?," +
" status = ?";
PreparedStatement insertStmt = conn.prepareStatement(sql);
insertStmt.setString(1, memberId);
insertStmt.setInt(2, prdId);
insertStmt.setDouble(3, balance);
insertStmt.setInt(4, status);
insertStmt.setDouble(5, balance);
insertStmt.setInt(6, status);
insertStmt.executeUpdate();
insertStmt.close();
}
} else {
System.out.println("call_api_error");
return;
}
} catch (Exception e) {
System.out.println("run_cron_error");
e.printStackTrace();
}
}
}
using System;
using System.Data.SqlClient;
using Newtonsoft.Json.Linq;
public class BalanceCron
{
public static void RunCron()
{
try
{
// Replace these constants with actual values
string serverName = "YourServerName";
string username = "YourUsername";
string password = "YourPassword";
string dbName = "YourDBName";
string memberId = "YourMemberId";
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)
{
ErrorLog("connect_db_error");
return;
}
string hostName = "YourKPLAYT_HOSTNAME"; // Hostname
string token = "YourKPLAYT_AG_TOKEN"; // AG Token
string agent = "YourKPLAYT_AG_CODE"; // AG Code
string method = "/balance-all";
string[] header = {
"Content-Type: application/json",
"ag-code: " + agent,
"ag-token: " + token
};
using (SqlCommand stmt = new SqlCommand("SELECT kplayt_id FROM kplayt_users WHERE user_id = @memberId", conn))
{
stmt.Parameters.AddWithValue("@memberId", memberId);
using (SqlDataReader reader = stmt.ExecuteReader())
{
if (reader.Read())
{
string kplaytId = reader.GetString(0);
var data = new
{
user = new
{
id = kplaytId,
currency = "KRW"
}
};
string url = hostName + method;
Helper helper = new Helper();
string response = helper.PostData(url, data, header);
dynamic responseData = JObject.Parse(response);
if (responseData != null && responseData.data != null)
{
if (responseData.status == 1)
{
foreach (var prodBalance in responseData.data)
{
int prdId = prodBalance.prd_id;
decimal balance = prodBalance.balance;
int status = prodBalance.status;
string sql = "INSERT INTO kplayt_member_prod_balance (member_id, prd_id, balance, status) " +
"VALUES (@memberId, @prdId, @balance, @status) " +
"ON DUPLICATE KEY UPDATE balance = @balance, status = @status";
using (SqlCommand updateStmt = new SqlCommand(sql, conn))
{
updateStmt.Parameters.AddWithValue("@memberId", memberId);
updateStmt.Parameters.AddWithValue("@prdId", prdId);
updateStmt.Parameters.AddWithValue("@balance", balance);
updateStmt.Parameters.AddWithValue("@status", status);
updateStmt.ExecuteNonQuery();
}
}
}
}
else
{
ErrorLog("call_api_error");
}
}
else
{
ErrorLog("run_cron_error");
}
}
}
}
}
catch (Exception e)
{
ErrorLog("run_cron_error");
}
}
private static void ErrorLog(string message)
{
// Implement error logging logic here, e.g., writing to log files or databases
Console.WriteLine(message);
}
}
<%
On Error Resume Next
Dim servername, username, password, dbname, conn, memberId, hostName, token, agent, method, header, stmt, result, db, kplaytId, data, url, helper, responseText, responseData, prodBalance, prdId, balance, status, sql
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 ' AG Token
agent = KPLAYT_AG_CODE ' AG Code
method = "/balance-all"
Set header = Server.CreateObject("Scripting.Dictionary")
header.Add "Content-Type", "application/json"
header.Add "ag-code", agent
header.Add "ag-token", token
Set stmt = conn.Prepare("SELECT kplayt_id FROM kplayt_users WHERE user_id = ?")
stmt.Parameters.Append stmt.CreateParameter("@memberId", 200, 1, 255, memberId)
stmt.Execute
Set result = stmt.GetResult
If Not result.EOF Then
db = result.GetRows()
kplaytId = db(0, 0)
stmt.Close
Set data = Server.CreateObject("Scripting.Dictionary")
Set userData = Server.CreateObject("Scripting.Dictionary")
userData.Add "id", kplaytId
userData.Add "currency", "KRW" ' Currently only support “KRW”
data.Add "user", userData
url = hostName & method
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=", kplaytId, "¤cy=KRW"), "")
responseText = helper.responseText
Set responseData = JSON.parse(responseText)
If IsObject(responseData) And responseData("status") = 1 Then
For Each prodBalance In responseData("data")
prdId = prodBalance("prd_id")
balance = prodBalance("balance")
status = prodBalance("status")
sql = "INSERT INTO kplayt_member_prod_balance (member_id, prd_id, balance, status) " & _
"VALUES (?, ?, ?, ?) " & _
"ON DUPLICATE KEY UPDATE " & _
"balance = ?, " & _
"status = ?"
Set stmt = conn.Prepare(sql)
stmt.Parameters.Append stmt.CreateParameter("@memberId", 200, 1, 255, memberId)
stmt.Parameters.Append stmt.CreateParameter("@prdId", 3, 1, 255, prdId)
stmt.Parameters.Append stmt.CreateParameter("@balance", 3, 1, 255, balance)
stmt.Parameters.Append stmt.CreateParameter("@status", 3, 1, 255, status)
stmt.Parameters.Append stmt.CreateParameter("@balanceUpdate", 3, 1, 255, balance)
stmt.Parameters.Append stmt.CreateParameter("@statusUpdate", 3, 1, 255, status)
stmt.Execute
stmt.Close
Next
Else
Response.Write("call_api_error")
Response.End
End If
Else
Response.Write("run_cron_error")
Response.End
End If
%>
PHP Sample
Java Sample
.Net Sample
ASP Sample
try
{
// db connection
$servername = DB_SERVER_NAME;
$username = DB_USERNAME;
$password = DB_PASSWORD;
$dbname = DB_NAME;
$txnStatus = 2;
$processed = 0;
$conn = new \mysqli($servername, $username, $password, $dbname);
//if connect to DB failed
if ($conn->connect_error)
{
error_log('connect_db_error');
exit;
}
$hostName = KPLAYT_HOSTNAME; //Hostname
$token = KPLAYT_AG_TOKEN; //AG Token
$agent = KPLAYT_AG_CODE; //AG Code
$method = '/transfer-status';
$selectSQL = "SELECT user_id, type, amount, product, txn_id
FROM funds_transfer
WHERE txn_status = ? and processed = ?";
$stmt = $conn->prepare($selectSQL);
$stmt->bind_param("ii", $txnStatus, $processed);
$stmt->execute();
$result = $stmt->get_result();
error_log('xxdsjaskldjklasjdlaskjdx');
error_log(count($result));
// Iterate through the result set
while ($row = $result->fetch_assoc())
{
error_log('xxx');
$userId = $row['user_id'];
$type = $row['type'];
$amount = $row['amount'];
$product = $row['product'];
$txn_id = $row['txn_id'];
$selectSQL = "SELECT a.kplayt_id, b.username FROM kplayt_users a left join users b on a.user_id = b.id WHERE a.user_id = ?";
$stmt = $conn->prepare($selectSQL);
$stmt->bind_param("i", $userId);
$stmt->execute();
$result = $stmt->get_result();
if ($result->num_rows > 0)
{
$row = $result->fetch_assoc();
$kplayId = $row['kplayt_id'];
$username = $row['username'];
}
$header = array('Content-Type: application/json',
'ag-code: '.$agent,
'ag-token:'.$token);
$data = array(
'user' => [
'id' => $kplayId,
'name' => $username,
'currency' => 'KRW'
],
'prd_id' => $product,
'txn_id' => $txn_id
);
$url = $hostName.$method;
$helper = new Helper;
$response = $helper->postData($url,$data,$header);
$data = json_decode($response);
if(isset($data->status) && isset($data->txn_status) && $data->txn_status === 1 && $data->status === 1) //success case
{
$updateSQL = "UPDATE funds_transfer
SET processed = 1, settle_as = 's'
WHERE txn_id = ".$txn_id;
$updateDB = $conn->query($updateSQL);
}
elseif(isset($data->status) && isset($data->txn_status) && $data->txn_status === 0 && $data->status === 1)//fail case
{
$updateSQL = "UPDATE funds_transfer
SET processed = 1, settle_as = 'f'
WHERE txn_id = ".$txn_id;
$updateDB = $conn->query($updateSQL);
}
elseif(isset($data->status) && $data->error == 'TXN_ID_NOT_EXIST' && $data->status === 0)//fail case
{
$updateSQL = "UPDATE funds_transfer
SET processed = 1, settle_as = 'f'
WHERE txn_id = ".$txn_id;
$updateDB = $conn->query($updateSQL);
}
}
}
catch (Exception $e)
{
error_log('run_cron_error');
exit;
}
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
public class TransferStatusCronJob {
public void executeCron() {
try {
String servername = Constants.DB_SERVER_NAME;
String username = Constants.DB_USERNAME;
String password = Constants.DB_PASSWORD;
String dbname = Constants.DB_NAME;
int txnStatus = 2;
int processed = 0;
Connection conn = DriverManager.getConnection("jdbc:mysql://" + servername + "/" + dbname, username, password);
if (conn == null) {
System.out.println("connect_db_error");
return;
}
String hostName = Constants.KPLAYT_HOSTNAME;
String token = Constants.KPLAYT_AG_TOKEN;
String agent = Constants.KPLAYT_AG_CODE;
String method = "/transfer-status";
String selectSQL = "SELECT user_id, type, amount, product, txn_id FROM funds_transfer WHERE txn_status = ? and processed = ?";
PreparedStatement stmt = conn.prepareStatement(selectSQL);
stmt.setInt(1, txnStatus);
stmt.setInt(2, processed);
ResultSet result = stmt.executeQuery();
while (result.next()) {
int userId = result.getInt("user_id");
String type = result.getString("type");
double amount = result.getDouble("amount");
int product = result.getInt("product");
int txnId = result.getInt("txn_id");
String selectUserSQL = "SELECT a.kplayt_id, b.username FROM kplayt_users a LEFT JOIN users b ON a.user_id = b.id WHERE a.user_id = ?";
PreparedStatement userStmt = conn.prepareStatement(selectUserSQL);
userStmt.setInt(1, userId);
ResultSet userResult = userStmt.executeQuery();
String kplayId = "";
String username = "";
if (userResult.next()) {
kplayId = userResult.getString("kplayt_id");
username = userResult.getString("username");
}
userStmt.close();
String[] header = {
"Content-Type: application/json",
"ag-code: " + agent,
"ag-token:" + token
};
String postData = "{\"user\": {\"id\": \"" + kplayId + "\", \"name\": \"" + username + "\", \"currency\": \"KRW\"}, \"prd_id\": " + product + ", \"txn_id\": " + txnId + "}";
String url = hostName + method;
Helper helper = new Helper();
String response = helper.postData(url, postData, header);
// Assuming a Helper method to parse JSON response is available
Map data = Helper.parseJson(response);
if (data != null && data.containsKey("status") && data.containsKey("txn_status")) {
int txnStatusResponse = (int) data.get("txn_status");
int status = (int) data.get("status");
String updateSQL = "";
if (txnStatusResponse == 1 && status == 1) {
updateSQL = "UPDATE funds_transfer SET processed = 1, settle_as = 's' WHERE txn_id = " + txnId;
} else if (txnStatusResponse == 0 && status == 1) {
updateSQL = "UPDATE funds_transfer SET processed = 1, settle_as = 'f' WHERE txn_id = " + txnId;
} else if (status == 0 && "TXN_ID_NOT_EXIST".equals(data.get("error"))) {
updateSQL = "UPDATE funds_transfer SET processed = 1, settle_as = 'f' WHERE txn_id = " + txnId;
}
if (!updateSQL.isEmpty()) {
PreparedStatement updateStmt = conn.prepareStatement(updateSQL);
updateStmt.executeUpdate();
updateStmt.close();
}
}
}
stmt.close();
} catch (Exception e) {
System.out.println("run_cron_error");
e.printStackTrace();
}
}
}
using System;
using System.Data.SqlClient;
using Newtonsoft.Json.Linq;
public class TransferStatusCron
{
public static void RunCron()
{
try
{
// Replace these constants with actual values
string serverName = "YourServerName";
string username = "YourUsername";
string password = "YourPassword";
string dbName = "YourDBName";
int txnStatus = 2;
int processed = 0;
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)
{
ErrorLog("connect_db_error");
return;
}
string hostName = "YourKPLAYT_HOSTNAME"; // Hostname
string token = "YourKPLAYT_AG_TOKEN"; // AG Token
string agent = "YourKPLAYT_AG_CODE"; // AG Code
string method = "/transfer-status";
string selectSQL = "SELECT user_id, type, amount, product, txn_id FROM funds_transfer WHERE txn_status = @txnStatus AND processed = @processed";
using (SqlCommand stmt = new SqlCommand(selectSQL, conn))
{
stmt.Parameters.AddWithValue("@txnStatus", txnStatus);
stmt.Parameters.AddWithValue("@processed", processed);
using (SqlDataReader reader = stmt.ExecuteReader())
{
while (reader.Read())
{
int userId = reader.GetInt32(0);
string type = reader.GetString(1);
decimal amount = reader.GetDecimal(2);
int product = reader.GetInt32(3);
long txn_id = reader.GetInt64(4);
string kplaytSelectSQL = "SELECT a.kplayt_id, b.username FROM kplayt_users a left join users b on a.user_id = b.id WHERE a.user_id = @userId";
using (SqlCommand kplaytStmt = new SqlCommand(kplaytSelectSQL, conn))
{
kplaytStmt.Parameters.AddWithValue("@userId", userId);
using (SqlDataReader kplaytReader = kplaytStmt.ExecuteReader())
{
if (kplaytReader.Read())
{
string kplayId = kplaytReader.GetString(0);
string username = kplaytReader.GetString(1);
string[] header = {
"Content-Type: application/json",
"ag-code: " + agent,
"ag-token: " + token
};
var data = new
{
user = new
{
id = kplayId,
name = username,
currency = "KRW"
},
prd_id = product,
txn_id = txn_id
};
string url = hostName + method;
Helper helper = new Helper();
string response = helper.PostData(url, data, header);
dynamic responseData = JObject.Parse(response);
if (responseData.status != null && responseData.txn_status != null && responseData.txn_status == 1 && responseData.status == 1) // Success case
{
string updateSQL = "UPDATE funds_transfer SET processed = 1, settle_as = 's' WHERE txn_id = @txn_id";
using (SqlCommand updateStmt = new SqlCommand(updateSQL, conn))
{
updateStmt.Parameters.AddWithValue("@txn_id", txn_id);
updateStmt.ExecuteNonQuery();
}
}
else if (responseData.status != null && responseData.txn_status != null && responseData.txn_status == 0 && responseData.status == 1) // Fail case
{
string updateSQL = "UPDATE funds_transfer SET processed = 1, settle_as = 'f' WHERE txn_id = @txn_id";
using (SqlCommand updateStmt = new SqlCommand(updateSQL, conn))
{
updateStmt.Parameters.AddWithValue("@txn_id", txn_id);
updateStmt.ExecuteNonQuery();
}
}
else if (responseData.status != null && responseData.error == "TXN_ID_NOT_EXIST" && responseData.status == 0) // Fail case
{
string updateSQL = "UPDATE funds_transfer SET processed = 1, settle_as = 'f' WHERE txn_id = @txn_id";
using (SqlCommand updateStmt = new SqlCommand(updateSQL, conn))
{
updateStmt.Parameters.AddWithValue("@txn_id", txn_id);
updateStmt.ExecuteNonQuery();
}
}
}
}
}
}
}
}
}
}
catch (Exception e)
{
ErrorLog("run_cron_error");
}
}
private static void ErrorLog(string message)
{
// Implement error logging logic here, e.g., writing to log files or databases
Console.WriteLine(message);
}
}
<%
On Error Resume Next
Dim servername, username, password, dbname, txnStatus, processed, conn, hostName, token, agent, method, selectSQL, stmt, result, row, userId, type, amount, product, txn_id, kplayId, header, data, url, helper, responseText, responseData, updateSQL, updateDB
servername = DB_SERVER_NAME
username = DB_USERNAME
password = DB_PASSWORD
dbname = DB_NAME
txnStatus = 2
processed = 0
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 ' AG Token
agent = KPLAYT_AG_CODE ' AG Code
method = "/transfer-status"
selectSQL = "SELECT user_id, type, amount, product, txn_id FROM funds_transfer WHERE txn_status = ? and processed = ?"
Set stmt = conn.Prepare(selectSQL)
stmt.Parameters.Append stmt.CreateParameter("@txnStatus", 200, 1, 255, txnStatus)
stmt.Parameters.Append stmt.CreateParameter("@processed", 200, 1, 255, processed)
stmt.Execute
Set result = stmt.GetResult
While Not result.EOF
userId = result.Fields.Item("user_id").Value
type = result.Fields.Item("type").Value
amount = result.Fields.Item("amount").Value
product = result.Fields.Item("product").Value
txn_id = result.Fields.Item("txn_id").Value
selectSQL = "SELECT a.kplayt_id, b.username FROM kplayt_users a left join users b on a.user_id = b.id WHERE a.user_id = ?"
Set stmt = conn.Prepare(selectSQL)
stmt.Parameters.Append stmt.CreateParameter("@userId", 200, 1, 255, userId)
stmt.Execute
Set result = stmt.GetResult
If result.RecordCount > 0 Then
kplayId = result.Fields.Item("kplayt_id").Value
username = result.Fields.Item("username").Value
End If
Set header = Server.CreateObject("Scripting.Dictionary")
header.Add "Content-Type", "application/json"
header.Add "ag-code", agent
header.Add "ag-token", token
Set data = Server.CreateObject("Scripting.Dictionary")
Set userData = Server.CreateObject("Scripting.Dictionary")
userData.Add "id", kplayId
userData.Add "name", username
userData.Add "currency", "KRW"
data.Add "user", userData
data.Add "prd_id", product
data.Add "txn_id", txn_id
url = hostName & method
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=", kplayId, "&name=", username, "¤cy=KRW", "&prd_id=", product, "&txn_id=", txn_id), "")
responseText = helper.responseText
Set responseData = JSON.parse(responseText)
If IsObject(responseData) Then
If responseData("status") = 1 And responseData("txn_status") = 1 Then
updateSQL = "UPDATE funds_transfer SET processed = 1, settle_as = 's' WHERE txn_id = " & txn_id
ElseIf responseData("status") = 1 And responseData("txn_status") = 0 Then
updateSQL = "UPDATE funds_transfer SET processed = 1, settle_as = 'f' WHERE txn_id = " & txn_id
ElseIf responseData("status") = 0 And responseData("error") = "TXN_ID_NOT_EXIST" Then
updateSQL = "UPDATE funds_transfer SET processed = 1, settle_as = 'f' WHERE txn_id = " & txn_id
End If
Set updateDB = conn.Execute(updateSQL)
End If
result.MoveNext
Wend
%>
PHP Sample
Java Sample
.Net Sample
ASP Sample
try
{
// db connection
$servername = DB_SERVER_NAME;
$username = DB_USERNAME;
$password = DB_PASSWORD;
$dbname = DB_NAME;
$cronName = 'datafeed';
$conn = new \mysqli($servername, $username, $password, $dbname);
//if connect to DB failed
if ($conn->connect_error)
{
error_log('connect_db_error');
exit;
}
$selectSQL = "SELECT last_start_time
FROM cron_status
WHERE cron_name = ?";
$stmt = $conn->prepare($selectSQL);
$stmt->bind_param("s", $cronName);
$stmt->execute();
$result = $stmt->get_result();
if ($result->num_rows > 0)
{
$row = $result->fetch_assoc();
$lastStartTime = $row['last_start_time'];
$startDateTime = date('Y-m-d\TH:i:00\Z', strtotime('-6 minutes', strtotime($lastStartTime)));
$endDateTime = date('Y-m-d\TH:i:59\Z', strtotime('-1 minutes', strtotime($lastStartTime)));
}
else
{
error_log('run_cron_error');
exit;
}
$hostName = KPLAYT_HOSTNAME; //Hostname
$token = KPLAYT_AG_TOKEN; //Token
$agent = KPLAYT_AG_CODE; //Code
$method = "feed/transaction?start_date=".$startDateTime.'&end_date='.$endDateTime;
$url = $hostName.$method;
$header = array('Content-Type: application/json',
'ag-code: '.$agent,
'ag-token:'.$token);
//post header&data via helper curl
$helper = new Helper;
$response = $helper->getData($url,$header);
$data = json_decode($response);
if($data->status == 1)
{
$data = $data->data;
foreach($data as $d)
{
$prdId = $d->prd_id;
$txnId = $d->txn_id;
$gameId = $d->game_id;
$memberId = $d->user_id;
$stake = $d->stake;
$payout = $d->payout; // win = stake + winloss, lose = 0, draw = stake
$betTime = $d->bet_time;
$settledTime = $d->settled_time;
$type = $d->type;
$jackpotAmt = $d->jackpot_amount;
$selectSQL = "SELECT user_id FROM kplayt_users WHERE kplayt_id = ?";
$statement = $conn->prepare($selectSQL);
$statement->bind_param("s", $memberId);
$statement->execute();
$result = $statement->get_result();
if ($result->num_rows > 0)
{
$row = $result->fetch_assoc();
$userId = $row['user_id'];
}
else
{
error_log('user not exist');
continue;
}
// Type 0 (normal)
// Type 1 (promotion) stake is 0 and it is a bonus (free spin, etc) so need to insert into debit and credit
// Type 2 (jackpot) bet come with normal bet which normal bet need to insert into debit and credit
if($type != 1)
{
// check if debit txn is exists
$selectSQL = "SELECT txn_id FROM kplayt_debit WHERE txn_id = ?";
$statement = $conn->prepare($selectSQL);
$statement->bind_param("s", $txnId);
$statement->execute();
$result = $statement->get_result();
// insert into debit table
if ($result->num_rows == 0)
{
//insert debit
$insertDebitSQL = "INSERT INTO kplayt_debit (txn_id, user_id, stake, bet_time, prd_id, game_id, type)
VALUES(?, ?, ?, ?, ?, ?, ?)";
$stmt = $conn->prepare($insertDebitSQL);
// Bind parameters
$stmt->bind_param("ssisiii", $txnId, $userId, $stake, $betTime, $prdId, $gameId, $type);
// Execute the statement
if (!$stmt->execute())
{
error_log("Error: " . $stmt->error);
}
$stmt->close();
}
// check if txn is exists
$selectSQL = "SELECT txn_id FROM kplayt_credit WHERE txn_id = ?";
$statement = $conn->prepare($selectSQL);
$statement->bind_param("s", $txnId);
$statement->execute();
$result = $statement->get_result();
// insert into credit table
if ($result->num_rows == 0)
{
$winLoss = $payout - $stake;
if ($winLoss < 0)
{
$outcome = 'l';
}
elseif ($winLoss > 0)
{
$outcome = 'w';
}
else
{
$outcome = 'd';
}
//insert credit
$insertCreditSQL = "INSERT INTO kplayt_credit (txn_id, type, payout, win_loss, outcome, settled_at)
VALUES(?, ?, ?, ?, ?, ?)";
$stmt = $conn->prepare($insertCreditSQL);
// Bind parameters
$stmt->bind_param("ssiiss", $txnId, $type, $payout, $winLoss, $outcome, $settledTime);
// Execute the statement
if (!$stmt->execute())
{
error_log("Error: " . $stmt->error);
}
$stmt->close();
}
}
if($type == 1 || $type == 2)
{
// check if txn is exists
$selectSQL = "SELECT txn_id FROM kplayt_bonus WHERE txn_id = ?";
$statement = $conn->prepare($selectSQL);
$statement->bind_param("s", $txnId);
$statement->execute();
$result = $statement->get_result();
$isJackpot = $type == 2 ? 1 : 0;
if ($type == 1)
{
$jackpotAmt = $payout;
}
if ($result->num_rows == 0)
{
$bonusSql = "INSERT INTO kplayt_bonus (txn_id, user_id, amount, prd_id, game_id, is_jackpot, type, settled_at)
VALUES(?, ?, ?, ?, ?, ?, ?, ?)";
$bonusParams = [$txnId, $userId, $jackpotAmt, $prdId, $gameId, $isJackpot, $type, $settledTime];
$bonusStatement = $conn->prepare($bonusSql);
$bonusStatement->execute($bonusParams);
}
}
}
}
else
{
error_log('call_data_feed_failed');
exit;
}
}
catch (Exception $e)
{
error_log('run_cron_error');
exit;
}
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.text.SimpleDateFormat;
import java.util.Calendar;
public class DataFeedCronJob {
public void executeCron() {
try {
String servername = Constants.DB_SERVER_NAME;
String username = Constants.DB_USERNAME;
String password = Constants.DB_PASSWORD;
String dbname = Constants.DB_NAME;
String cronName = "datafeed";
Connection conn = DriverManager.getConnection("jdbc:mysql://" + servername + "/" + dbname, username, password);
if (conn == null) {
System.out.println("connect_db_error");
return;
}
String selectSQL = "SELECT last_start_time FROM cron_status WHERE cron_name = ?";
PreparedStatement stmt = conn.prepareStatement(selectSQL);
stmt.setString(1, cronName);
ResultSet result = stmt.executeQuery();
if (result.next()) {
String lastStartTime = result.getString("last_start_time");
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'");
Calendar calendar = Calendar.getInstance();
calendar.setTime(dateFormat.parse(lastStartTime));
calendar.add(Calendar.MINUTE, -6);
String startDateTime = dateFormat.format(calendar.getTime());
calendar.add(Calendar.MINUTE, 5);
String endDateTime = dateFormat.format(calendar.getTime());
String hostName = Constants.KPLAYT_HOSTNAME;
String token = Constants.KPLAYT_AG_TOKEN;
String agent = Constants.KPLAYT_AG_CODE;
String method = "feed/transaction?start_date=" + startDateTime + "&end_date=" + endDateTime;
String url = hostName + method;
String[] header = {
"Content-Type: application/json",
"ag-code: " + agent,
"ag-token:" + token
};
Helper helper = new Helper();
String response = helper.getData(url, header);
// Assuming a Helper method to parse JSON response is available
Map data = Helper.parseJson(response);
if (data != null && data.containsKey("status") && (int) data.get("status") == 1) {
JSONArray dataArray = (JSONArray) data.get("data");
for (Object obj : dataArray) {
JSONObject d = (JSONObject) obj;
int prdId = d.getInt("prd_id");
int txnId = d.getInt("txn_id");
int gameId = d.getInt("game_id");
String memberId = d.getString("user_id");
double stake = d.getDouble("stake");
double payout = d.getDouble("payout");
String betTime = d.getString("bet_time");
String settledTime = d.getString("settled_time");
int type = d.getInt("type");
double jackpotAmt = d.getDouble("jackpot_amount");
PreparedStatement userStmt = conn.prepareStatement("SELECT user_id FROM kplayt_users WHERE kplayt_id = ?");
userStmt.setString(1, memberId);
ResultSet userResult = userStmt.executeQuery();
if (userResult.next()) {
int userId = userResult.getInt("user_id");
if (type != 1) {
PreparedStatement debitCheckStmt = conn.prepareStatement("SELECT txn_id FROM kplayt_debit WHERE txn_id = ?");
debitCheckStmt.setInt(1, txnId);
ResultSet debitCheckResult = debitCheckStmt.executeQuery();
if (!debitCheckResult.next()) {
//insert debit
PreparedStatement insertDebitStmt = conn.prepareStatement("INSERT INTO kplayt_debit (txn_id, user_id, stake, bet_time, prd_id, game_id, type) VALUES (?, ?, ?, ?, ?, ?, ?)");
insertDebitStmt.setInt(1, txnId);
insertDebitStmt.setInt(2, userId);
insertDebitStmt.setDouble(3, stake);
insertDebitStmt.setString(4, betTime);
insertDebitStmt.setInt(5, prdId);
insertDebitStmt.setInt(6, gameId);
insertDebitStmt.setInt(7, type);
insertDebitStmt.executeUpdate();
}
PreparedStatement creditCheckStmt = conn.prepareStatement("SELECT txn_id FROM kplayt_credit WHERE txn_id = ?");
creditCheckStmt.setInt(1, txnId);
ResultSet creditCheckResult = creditCheckStmt.executeQuery();
if (!creditCheckResult.next()) {
double winLoss = payout - stake;
String outcome = winLoss < 0 ? "l" : (winLoss > 0 ? "w" : "d");
PreparedStatement insertCreditStmt = conn.prepareStatement("INSERT INTO kplayt_credit (txn_id, type, payout, win_loss, outcome, settled_at) VALUES (?, ?, ?, ?, ?, ?)");
insertCreditStmt.setInt(1, txnId);
insertCreditStmt.setInt(2, type);
insertCreditStmt.setDouble(3, payout);
insertCreditStmt.setDouble(4, winLoss);
insertCreditStmt.setString(5, outcome);
insertCreditStmt.setString(6, settledTime);
insertCreditStmt.executeUpdate();
}
}
if (type == 1 || type == 2) {
PreparedStatement bonusCheckStmt = conn.prepareStatement("SELECT txn_id FROM kplayt_bonus WHERE txn_id = ?");
bonusCheckStmt.setInt(1, txnId);
ResultSet bonusCheckResult = bonusCheckStmt.executeQuery();
int isJackpot = type == 2 ? 1 : 0;
if (!bonusCheckResult.next()) {
PreparedStatement insertBonusStmt = conn.prepareStatement("INSERT INTO kplayt_bonus (txn_id, user_id, amount, prd_id, game_id, is_jackpot, type, settled_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?)");
insertBonusStmt.setInt(1, txnId);
insertBonusStmt.setInt(2, userId);
insertBonusStmt.setDouble(3, jackpotAmt);
insertBonusStmt.setInt(4, prdId);
insertBonusStmt.setInt(5, gameId);
insertBonusStmt.setInt(6, isJackpot);
insertBonusStmt.setInt(7, type);
insertBonusStmt.setString(8, settledTime);
insertBonusStmt.executeUpdate();
}
}
} else {
System.out.println("user not exist");
}
}
} else {
System.out.println("call_data_feed_failed");
return;
}
} else {
System.out.println("run_cron_error");
return;
}
} catch (Exception e) {
System.out.println("run_cron_error");
e.printStackTrace();
}
}
}
using System;
using System.Data.SqlClient;
using Newtonsoft.Json.Linq;
public class DataFeedCron
{
public static void RunCron()
{
try
{
// Replace these constants with actual values
string serverName = "YourServerName";
string username = "YourUsername";
string password = "YourPassword";
string dbName = "YourDBName";
string cronName = "datafeed";
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)
{
ErrorLog("connect_db_error");
return;
}
string selectSQL = "SELECT last_start_time FROM cron_status WHERE cron_name = @cronName";
using (SqlCommand stmt = new SqlCommand(selectSQL, conn))
{
stmt.Parameters.AddWithValue("@cronName", cronName);
using (SqlDataReader reader = stmt.ExecuteReader())
{
if (reader.Read())
{
DateTime lastStartTime = reader.GetDateTime(0);
DateTime startDateTime = lastStartTime.AddMinutes(-6);
DateTime endDateTime = lastStartTime.AddMinutes(-1);
string formattedStartDateTime = startDateTime.ToString("yyyy-MM-ddTHH:mm:00Z");
string formattedEndDateTime = endDateTime.ToString("yyyy-MM-ddTHH:mm:59Z");
}
else
{
ErrorLog("run_cron_error");
return;
}
}
}
string hostName = "YourKPLAYT_HOSTNAME"; // Hostname
string token = "YourKPLAYT_AG_TOKEN"; // Token
string agent = "YourKPLAYT_AG_CODE"; // Code
string method = $"feed/transaction?start_date={formattedStartDateTime}&end_date={formattedEndDateTime}";
string url = hostName + method;
string[] header = {
"Content-Type: application/json",
"ag-code: " + agent,
"ag-token: " + token
};
// Post header&data via helper curl
Helper helper = new Helper();
string response = helper.GetData(url, header);
dynamic responseData = JObject.Parse(response);
if (responseData.status == 1)
{
JArray data = responseData.data;
foreach (var d in data)
{
int prdId = d.prd_id;
long txnId = d.txn_id;
int gameId = d.game_id;
string memberId = d.user_id;
decimal stake = d.stake;
decimal payout = d.payout;
DateTime betTime = DateTime.Parse(d.bet_time);
DateTime settledTime = DateTime.Parse(d.settled_time);
int type = d.type;
decimal jackpotAmt = d.jackpot_amount;
string selectSQL = "SELECT user_id FROM kplayt_users WHERE kplayt_id = @memberId";
using (SqlCommand statement = new SqlCommand(selectSQL, conn))
{
statement.Parameters.AddWithValue("@memberId", memberId);
using (SqlDataReader result = statement.ExecuteReader())
{
if (result.Read())
{
int userId = result.GetInt32(0);
// Type 0 (normal)
// Type 1 (promotion) stake is 0 and it is a bonus (free spin, etc) so need to insert into debit and credit
// Type 2 (jackpot) bet come with normal bet which normal bet need to insert into debit and credit
if (type != 1)
{
// Check if debit txn is exists
string debitSelectSQL = "SELECT txn_id FROM kplayt_debit WHERE txn_id = @txnId";
using (SqlCommand debitStatement = new SqlCommand(debitSelectSQL, conn))
{
debitStatement.Parameters.AddWithValue("@txnId", txnId);
using (SqlDataReader debitResult = debitStatement.ExecuteReader())
{
// Insert into debit table
if (!debitResult.Read())
{
// Insert debit
string insertDebitSQL = "INSERT INTO kplayt_debit (txn_id, user_id, stake, bet_time, prd_id, game_id, type)
VALUES (@txnId, @userId, @stake, @betTime, @prdId, @gameId, @type)";
using (SqlCommand debitInsertStmt = new SqlCommand(insertDebitSQL, conn))
{
debitInsertStmt.Parameters.AddWithValue("@txnId", txnId);
debitInsertStmt.Parameters.AddWithValue("@userId", userId);
debitInsertStmt.Parameters.AddWithValue("@stake", stake);
debitInsertStmt.Parameters.AddWithValue("@betTime", betTime);
debitInsertStmt.Parameters.AddWithValue("@prdId", prdId);
debitInsertStmt.Parameters.AddWithValue("@gameId", gameId);
debitInsertStmt.Parameters.AddWithValue("@type", type);
// Execute the statement
if (debitInsertStmt.ExecuteNonQuery() == -1)
{
ErrorLog("Error: " + debitInsertStmt.Error);
}
}
}
}
}
// Check if txn is exists
string creditSelectSQL = "SELECT txn_id FROM kplayt_credit WHERE txn_id = @txnId";
using (SqlCommand creditStatement = new SqlCommand(creditSelectSQL, conn))
{
creditStatement.Parameters.AddWithValue("@txnId", txnId);
using (SqlDataReader creditResult = creditStatement.ExecuteReader())
{
// Insert into credit table
if (!creditResult.Read())
{
decimal winLoss = payout - stake;
string outcome;
if (winLoss < 0)
{
outcome = "l";
}
else if (winLoss > 0)
{
outcome = "w";
}
else
{
outcome = "d";
}
string insertCreditSQL = "INSERT INTO kplayt_credit (txn_id, type, payout, win_loss, outcome, settled_at)
VALUES (@txnId, @type, @payout, @winLoss, @outcome, @settledTime)";
using (SqlCommand creditInsertStmt = new SqlCommand(insertCreditSQL, conn))
{
creditInsertStmt.Parameters.AddWithValue("@txnId", txnId);
creditInsertStmt.Parameters.AddWithValue("@type", type);
creditInsertStmt.Parameters.AddWithValue("@payout", payout);
creditInsertStmt.Parameters.AddWithValue("@winLoss", winLoss);
creditInsertStmt.Parameters.AddWithValue("@outcome", outcome);
creditInsertStmt.Parameters.AddWithValue("@settledTime", settledTime);
// Execute the statement
if (creditInsertStmt.ExecuteNonQuery() == -1)
{
ErrorLog("Error: " + creditInsertStmt.Error);
}
}
}
}
}
}
if (type == 1 || type == 2)
{
// Check if txn is exists
string bonusSelectSQL = "SELECT txn_id FROM kplayt_bonus WHERE txn_id = @txnId";
using (SqlCommand bonusStatement = new SqlCommand(bonusSelectSQL, conn))
{
bonusStatement.Parameters.AddWithValue("@txnId", txnId);
using (SqlDataReader bonusResult = bonusStatement.ExecuteReader())
{
int isJackpot = type == 2 ? 1 : 0;
if (type == 1)
{
jackpotAmt = payout;
}
// Insert into bonus table
if (!bonusResult.Read())
{
string insertBonusSQL = "INSERT INTO kplayt_bonus (txn_id, user_id, amount, prd_id, game_id, is_jackpot,
type, settled_at) VALUES (@txnId, @userId, @jackpotAmt, @prdId,
@gameId, @isJackpot, @type, @settledTime)";
using (SqlCommand bonusInsertStmt = new SqlCommand(insertBonusSQL, conn))
{
bonusInsertStmt.Parameters.AddWithValue("@txnId", txnId);
bonusInsertStmt.Parameters.AddWithValue("@userId", userId);
bonusInsertStmt.Parameters.AddWithValue("@jackpotAmt", jackpotAmt);
bonusInsertStmt.Parameters.AddWithValue("@prdId", prdId);
bonusInsertStmt.Parameters.AddWithValue("@gameId", gameId);
bonusInsertStmt.Parameters.AddWithValue("@isJackpot", isJackpot);
bonusInsertStmt.Parameters.AddWithValue("@type", type);
bonusInsertStmt.Parameters.AddWithValue("@settledTime", settledTime);
bonusInsertStmt.ExecuteNonQuery();
}
}
}
}
}
}
else
{
ErrorLog("user not exist");
continue;
}
}
}
}
}
else
{
ErrorLog("call_data_feed_failed");
return;
}
}
}
catch (Exception e)
{
ErrorLog("run_cron_error");
}
}
private static void ErrorLog(string message)
{
// Implement error logging logic here, e.g., writing to log files or databases
Console.WriteLine(message);
}
}
<%
On Error Resume Next
Dim servername, username, password, dbname, cronName, conn, selectSQL, stmt, result, row, lastStartTime, startDateTime, endDateTime, hostName, token, agent, method, url, header, helper, responseText, data, d, prdId, txnId, gameId, memberId, stake, payout, betTime, settledTime, type, jackpotAmt, statement, userId, updateSQL, updateDB
servername = DB_SERVER_NAME
username = DB_USERNAME
password = DB_PASSWORD
dbname = DB_NAME
cronName = "datafeed"
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
selectSQL = "SELECT last_start_time FROM cron_status WHERE cron_name = ?"
Set stmt = conn.Prepare(selectSQL)
stmt.Parameters.Append stmt.CreateParameter("@cronName", 200, 1, 255, cronName)
stmt.Execute
Set result = stmt.GetResult
If Not result.EOF Then
lastStartTime = result.Fields.Item("last_start_time").Value
startDateTime = DateAdd("n", -6, CDate(lastStartTime))
endDateTime = DateAdd("n", -1, CDate(lastStartTime))
startDateTime = Year(startDateTime) & "-" & Right("0" & Month(startDateTime), 2) & "-" & Right("0" & Day(startDateTime), 2) & "T" & Right("0" & Hour(startDateTime), 2) & ":" & Right("0" & Minute(startDateTime), 2) & ":00Z"
endDateTime = Year(endDateTime) & "-" & Right("0" & Month(endDateTime), 2) & "-" & Right("0" & Day(endDateTime), 2) & "T" & Right("0" & Hour(endDateTime), 2) & ":" & Right("0" & Minute(endDateTime), 2) & ":59Z"
Else
Response.Write("run_cron_error")
Response.End
End If
hostName = KPLAYT_HOSTNAME ' Hostname
token = KPLAYT_AG_TOKEN ' Token
agent = KPLAYT_AG_CODE ' Code
method = "feed/transaction?start_date=" & Server.URLEncode(startDateTime) & "&end_date=" & Server.URLEncode(endDateTime)
url = hostName & method
Set header = Server.CreateObject("Scripting.Dictionary")
header.Add "Content-Type", "application/json"
header.Add "ag-code", agent
header.Add "ag-token", token
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 IsObject(data) And data("status") = 1 Then
For Each d In data("data")
prdId = d("prd_id")
txnId = d("txn_id")
gameId = d("game_id")
memberId = d("user_id")
stake = d("stake")
payout = d("payout")
betTime = d("bet_time")
settledTime = d("settled_time")
type = d("type")
jackpotAmt = d("jackpot_amount")
selectSQL = "SELECT user_id FROM kplayt_users WHERE kplayt_id = ?"
Set statement = conn.Prepare(selectSQL)
statement.Parameters.Append statement.CreateParameter("@memberId", 200, 1, 255, memberId)
statement.Execute
Set result = statement.GetResult
If Not result.EOF Then
userId = result.Fields.Item("user_id").Value
Else
Response.Write("user not exist")
Continue For
End If
If type <> 1 Then
selectSQL = "SELECT txn_id FROM kplayt_debit WHERE txn_id = ?"
Set statement = conn.Prepare(selectSQL)
statement.Parameters.Append statement.CreateParameter("@txnId", 200, 1, 255, txnId)
statement.Execute
Set result = statement.GetResult
If result.EOF Then
' insert into debit table
insertDebitSQL = "INSERT INTO kplayt_debit (txn_id, user_id, stake, bet_time, prd_id, game_id, type) VALUES (?, ?, ?, ?, ?, ?, ?)"
Set stmt = conn.Prepare(insertDebitSQL)
stmt.Parameters.Append stmt.CreateParameter("@txnId", 200, 1, 255, txnId)
stmt.Parameters.Append stmt.CreateParameter("@userId", 200, 1, 255, userId)
stmt.Parameters.Append stmt.CreateParameter("@stake", 3, 1, 255, stake)
stmt.Parameters.Append stmt.CreateParameter("@betTime", 135, 1, 255, betTime)
stmt.Parameters.Append stmt.CreateParameter("@prdId", 3, 1, 255, prdId)
stmt.Parameters.Append stmt.CreateParameter("@gameId", 3, 1, 255, gameId)
stmt.Parameters.Append stmt.CreateParameter("@type", 3, 1, 255, type)
stmt.Execute
End If
selectSQL = "SELECT txn_id FROM kplayt_credit WHERE txn_id = ?"
Set statement = conn.Prepare(selectSQL)
statement.Parameters.Append statement.CreateParameter("@txnId", 200, 1, 255, txnId)
statement.Execute
Set result = statement.GetResult
If result.EOF Then
winLoss = payout - stake
If winLoss < 0 Then
outcome = "l"
ElseIf winLoss > 0 Then
outcome = "w"
Else
outcome = "d"
End If
insertCreditSQL = "INSERT INTO kplayt_credit (txn_id, type, payout, win_loss, outcome, settled_at) VALUES (?, ?, ?, ?, ?, ?)"
Set stmt = conn.Prepare(insertCreditSQL)
stmt.Parameters.Append stmt.CreateParameter("@txnId", 200, 1, 255, txnId)
stmt.Parameters.Append stmt.CreateParameter("@type", 3, 1, 255, type)
stmt.Parameters.Append stmt.CreateParameter("@payout", 3, 1, 255, payout)
stmt.Parameters.Append stmt.CreateParameter("@winLoss", 3, 1, 255, winLoss)
stmt.Parameters.Append stmt.CreateParameter("@outcome", 200, 1, 255, outcome)
stmt.Parameters.Append stmt.CreateParameter("@settledTime", 135, 1, 255, settledTime)
stmt.Execute
End If
End If
If type = 1 Or type = 2 Then
selectSQL = "SELECT txn_id FROM kplayt_bonus WHERE txn_id = ?"
Set statement = conn.Prepare(selectSQL)
statement.Parameters.Append statement.CreateParameter("@txnId", 200, 1, 255, txnId)
statement.Execute
Set result = statement.GetResult
isJackpot = IIf(type = 2, 1, 0)
If result.EOF Then
bonusSql = "INSERT INTO kplayt_bonus (txn_id, user_id, amount, prd_id, game_id, is_jackpot, type, settled_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?)"
bonusParams = Array(txnId, userId, jackpotAmt, prdId, gameId, isJackpot, type, settledTime)
Set bonusStatement = conn.Prepare(bonusSql)
bonusStatement.Execute bonusParams
End If
End If
Next
Else
Response.Write("call_data_feed_failed")
Response.End
End If
%>
PHP Sample
Java Sample
.Net Sample
ASP Sample
function __construct()
{
try
{
$servername = DB_SERVER_NAME;
$username = DB_USERNAME;
$password = DB_PASSWORD;
$dbname = DB_NAME;
$conn = new \mysqli($servername, $username, $password, $dbname);
$conn->query("SET NAMES 'UTF8'");
//if connect to DB failed
if ($conn->connect_error)
{
var_dump("Connection failed: " . $conn->connect_error);
exit;
}
$hostName = KPLAY_HOSTNAME; //Hostname
$token = KPLAY_TOKEN; //AG Token
$agent = KPLAY_CODE; //AG Code
$method = '/gamelist';
$header = array('Content-Type: application/json',
'ag-code: '.$agent,
'ag-token:'.$token);
$data = array(
'language' => "en"
);
$url = $hostName.$method;
$helper = new Helper;
$response = $helper->postData($url,$data,$header);
error_log(json_encode($data));
error_log($response);
$data = json_decode($response);
if (!empty($data) && array_key_exists('game_list', $data))
{
if ($data->status == 1)
{
$gameList = (array) $data->game_list;
foreach ($gameList as $prdId => $gameInfo)
{
foreach ($gameInfo as $info)
{
$gameId = $info->game_id;
$gameName = $info->game_name;
$isEnabled = $info->game_status;
$stmt = $conn->prepare("SELECT prd_id, game_id, game_name_en, game_name_ko
FROM game_list
WHERE prd_id = ?
AND game_id = ?
");
$stmt->bind_param("ii", $prdId, $gameId);
$stmt->execute();
$result = $stmt->get_result();
$db = $result->fetch_all(MYSQLI_ASSOC);
$stmt->close();
if (sizeof($db) == 0)
{
$sql = "INSERT INTO game_list(prd_id, game_id, game_name_en, is_enabled)
VALUES(?, ?, ?, ?)";
$stmt = $conn->prepare($sql);
$stmt->bind_param("iisi", $prdId, $gameId, $gameName, $isEnabled);
$stmt->execute();
$stmt->close();
}
else
{
$dbGameNameEn = $db[0]['game_name_en'];
$dbGameNameKr = $db[0]['game_name_ko'];
if ($dbGameNameKr == null || $dbGameNameEn == null || $dbGameNameKr == 'N/A' || $dbGameNameEn == 'N/A')
{
$sql = "UPDATE KPLAY_game_list
SET prd_id = ?
,game_id = ?
,game_name_en = ?
,is_enabled = ?
,updated_at = ?
WHERE prd_id = ?
AND game_id = ?";
$stmt = $conn->prepare($sql);
$stmt->bind_param("iisisii", $prdId, $gameId, $gameName, $isEnabled, $updatedAt, $prdId, $gameId);
$updatedAt = date("Y-m-d H:i:s"); // Set the updated_at value
$stmt->execute();
$stmt->close();
}
}
}
}
}
}
else
{
var_dump("call_api_error");
exit;
}
}
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.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Map;
public class GameListConstructor {
public GameListConstructor() {
try {
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);
conn.createStatement().executeUpdate("SET NAMES 'UTF8'");
if (conn == null) {
System.out.println("Connection failed");
return;
}
String hostName = Constants.KPLAY_HOSTNAME;
String token = Constants.KPLAY_TOKEN;
String agent = Constants.KPLAY_CODE;
String method = "/gamelist";
String[] header = {
"Content-Type: application/json",
"ag-code: " + agent,
"ag-token:" + token
};
Map data = Map.of("language", "en");
String url = hostName + method;
Helper helper = new Helper();
String response = helper.postData(url, data, header);
System.out.println(data);
System.out.println(response);
// Assuming a Helper method to parse JSON response is available
Map jsonData = Helper.parseJson(response);
if (jsonData != null && jsonData.containsKey("game_list")) {
if ((int) jsonData.get("status") == 1) {
Map> gameList = (Map>) jsonData.get("game_list");
for (Map.Entry> entry : gameList.entrySet()) {
int prdId = entry.getKey();
Map gameInfo = entry.getValue();
for (Map.Entry gameEntry : gameInfo.entrySet()) {
Map info = (Map) gameEntry.getValue();
int gameId = (int) info.get("game_id");
String gameName = (String) info.get("game_name");
int isEnabled = (int) info.get("game_status");
PreparedStatement stmt = conn.prepareStatement("SELECT prd_id, game_id, game_name_en, game_name_ko FROM game_list WHERE prd_id = ? AND game_id = ?");
stmt.setInt(1, prdId);
stmt.setInt(2, gameId);
ResultSet result = stmt.executeQuery();
if (!result.next()) {
String sql = "INSERT INTO game_list(prd_id, game_id, game_name_en, is_enabled) VALUES (?, ?, ?, ?)";
PreparedStatement insertStmt = conn.prepareStatement(sql);
insertStmt.setInt(1, prdId);
insertStmt.setInt(2, gameId);
insertStmt.setString(3, gameName);
insertStmt.setInt(4, isEnabled);
insertStmt.executeUpdate();
insertStmt.close();
} else {
String dbGameNameEn = result.getString("game_name_en");
String dbGameNameKr = result.getString("game_name_ko");
if (dbGameNameKr == null || dbGameNameEn == null || dbGameNameKr.equals("N/A") || dbGameNameEn.equals("N/A")) {
String sql = "UPDATE KPLAY_game_list SET prd_id = ?, game_id = ?, game_name_en = ?, is_enabled = ?, updated_at = ? WHERE prd_id = ? AND game_id = ?";
PreparedStatement updateStmt = conn.prepareStatement(sql);
Calendar calendar = Calendar.getInstance();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String updatedAt = sdf.format(calendar.getTime());
updateStmt.setInt(1, prdId);
updateStmt.setInt(2, gameId);
updateStmt.setString(3, gameName);
updateStmt.setInt(4, isEnabled);
updateStmt.setString(5, updatedAt);
updateStmt.setInt(6, prdId);
updateStmt.setInt(7, gameId);
updateStmt.executeUpdate();
updateStmt.close();
}
}
stmt.close();
}
}
}
} else {
System.out.println("call_api_error");
return;
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
using System;
using System.Data.SqlClient;
using Newtonsoft.Json.Linq;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
public class GameListUpdater
{
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 KPLAY_HOSTNAME = "YourKPLAY_HOSTNAME";
private const string KPLAY_TOKEN = "YourKPLAY_TOKEN";
private const string KPLAY_CODE = "YourKPLAY_CODE";
public async Task UpdateGameList()
{
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 = KPLAY_HOSTNAME; // Hostname
string token = KPLAY_TOKEN; // Token
string agent = KPLAY_CODE; // Code
string method = "/gamelist";
string[] header = {
"Content-Type: application/json",
"ag-code: " + agent,
"ag-token: " + token
};
var data = new { language = "en" };
string jsonData = JsonConvert.SerializeObject(data);
string url = hostName + method;
HttpClient httpClient = new HttpClient();
var content = new StringContent(jsonData, Encoding.UTF8, "application/json");
HttpResponseMessage responseMessage = await httpClient.PostAsync(url, content);
string response = await responseMessage.Content.ReadAsStringAsync();
Console.WriteLine(JsonConvert.SerializeObject(data));
Console.WriteLine(response);
dynamic responseData = JObject.Parse(response);
if (responseData != null && responseData.game_list != null)
{
if (responseData.status == 1)
{
var gameList = (JObject)responseData.game_list;
foreach (var prdId in gameList.Properties())
{
var gameInfo = (JArray)gameList[prdId.Name];
foreach (var info in gameInfo)
{
int gameId = info["game_id"].Value();
string gameName = info["game_name"].Value();
int isEnabled = info["game_status"].Value();
string selectSQL = "SELECT prd_id, game_id, game_name_en, is_enabled FROM game_list WHERE prd_id = @prdId AND game_id = @gameId";
using (SqlCommand stmt = new SqlCommand(selectSQL, conn))
{
stmt.Parameters.AddWithValue("@prdId", prdId.Name);
stmt.Parameters.AddWithValue("@gameId", gameId);
using (SqlDataReader reader = stmt.ExecuteReader())
{
if (!reader.Read())
{
string insertSQL = "INSERT INTO game_list (prd_id, game_id, game_name_en, is_enabled) VALUES (@prdId, @gameId, @gameName, @isEnabled)";
using (SqlCommand insertStmt = new SqlCommand(insertSQL, conn))
{
insertStmt.Parameters.AddWithValue("@prdId", prdId.Name);
insertStmt.Parameters.AddWithValue("@gameId", gameId);
insertStmt.Parameters.AddWithValue("@gameName", gameName);
insertStmt.Parameters.AddWithValue("@isEnabled", isEnabled);
insertStmt.ExecuteNonQuery();
}
}
else
{
string dbGameNameEn = reader["game_name_en"].ToString();
string dbGameNameKr = reader["game_name_ko"].ToString();
if (string.IsNullOrEmpty(dbGameNameKr) || dbGameNameKr == "N/A" || string.IsNullOrEmpty(dbGameNameEn) || dbGameNameEn == "N/A")
{
string updateSQL = "UPDATE game_list SET game_name_en = @gameName, is_enabled = @isEnabled, updated_at = @updatedAt WHERE prd_id = @prdId AND game_id = @gameId";
using (SqlCommand updateStmt = new SqlCommand(updateSQL, conn))
{
updateStmt.Parameters.AddWithValue("@gameName", gameName);
updateStmt.Parameters.AddWithValue("@isEnabled", isEnabled);
updateStmt.Parameters.AddWithValue("@updatedAt", DateTime.Now);
updateStmt.Parameters.AddWithValue("@prdId", prdId.Name);
updateStmt.Parameters.AddWithValue("@gameId", gameId);
updateStmt.ExecuteNonQuery();
}
}
}
}
}
}
}
}
}
else
{
Console.WriteLine("call_api_error");
}
}
}
catch (Exception e)
{
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, gameList, prdId, gameId, gameName, isEnabled, db, sql, dbGameNameEn, dbGameNameKr, updatedAt
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
conn.Execute "SET NAMES 'UTF8'"
hostName = KPLAY_HOSTNAME ' Hostname
token = KPLAY_TOKEN ' Token
agent = KPLAY_CODE ' Code
method = "/gamelist"
Set header = Server.CreateObject("Scripting.Dictionary")
header.Add "Content-Type", "application/json"
header.Add "ag-code", agent
header.Add "ag-token", token
Set data = Server.CreateObject("Scripting.Dictionary")
data.Add "language", "en"
url = hostName & method
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(JSON.stringify(data))
responseText = helper.responseText
Set data = JSON.parse(responseText)
If IsObject(data) And data("game_list") <> "" Then
If data("status") = 1 Then
Set gameList = data("game_list")
For Each prdId In gameList.Keys
For Each gameInfo In gameList(prdId)
gameId = gameInfo("game_id")
gameName = gameInfo("game_name")
isEnabled = gameInfo("game_status")
selectSQL = "SELECT prd_id, game_id, game_name_en, game_name_ko FROM game_list WHERE prd_id = ? AND game_id = ?"
Set stmt = conn.Prepare(selectSQL)
stmt.Parameters.Append stmt.CreateParameter("@prdId", 200, 1, 255, prdId)
stmt.Parameters.Append stmt.CreateParameter("@gameId", 200, 1, 255, gameId)
stmt.Execute
Set result = stmt.GetResult
db = result.GetRows()
stmt.Close
If UBound(db, 2) = -1 Then
sql = "INSERT INTO game_list(prd_id, game_id, game_name_en, is_enabled) VALUES (?, ?, ?, ?)"
Set stmt = conn.Prepare(sql)
stmt.Parameters.Append stmt.CreateParameter("@prdId", 200, 1, 255, prdId)
stmt.Parameters.Append stmt.CreateParameter("@gameId", 200, 1, 255, gameId)
stmt.Parameters.Append stmt.CreateParameter("@gameName", 200, 1, 255, gameName)
stmt.Parameters.Append stmt.CreateParameter("@isEnabled", 200, 1, 255, isEnabled)
stmt.Execute
stmt.Close
Else
dbGameNameEn = db(2, 0)
dbGameNameKr = db(3, 0)
If IsNull(dbGameNameKr) Or IsNull(dbGameNameEn) Or dbGameNameKr = "N/A" Or dbGameNameEn = "N/A" Then
sql = "UPDATE KPLAY_game_list SET prd_id = ?, game_id = ?, game_name_en = ?, is_enabled = ?, updated_at = ? WHERE prd_id = ? AND game_id = ?"
Set stmt = conn.Prepare(sql)
stmt.Parameters.Append stmt.CreateParameter("@prdId", 200, 1, 255, prdId)
stmt.Parameters.Append stmt.CreateParameter("@gameId", 200, 1, 255, gameId)
stmt.Parameters.Append stmt.CreateParameter("@gameName", 200, 1, 255, gameName)
stmt.Parameters.Append stmt.CreateParameter("@isEnabled", 200, 1, 255, isEnabled)
stmt.Parameters.Append stmt.CreateParameter("@updatedAt", 200, 1, 255, Now())
stmt.Parameters.Append stmt.CreateParameter("@prdId2", 200, 1, 255, prdId)
stmt.Parameters.Append stmt.CreateParameter("@gameId2", 200, 1, 255, gameId)
stmt.Execute
stmt.Close
End If
End If
Next
Next
End If
Else
Response.Write("call_api_error")
Response.End
End If
%>
PHP Sample
Java Sample
.Net Sample
ASP Sample
function __construct()
{
try
{
$servername = DB_SERVER_NAME;
$username = DB_USERNAME;
$password = DB_PASSWORD;
$dbname = DB_NAME;
$conn = new \mysqli($servername, $username, $password, $dbname);
$conn->query("SET NAMES 'UTF8'");
//if connect to DB failed
if ($conn->connect_error)
{
var_dump("Connection failed: " . $conn->connect_error);
exit;
}
$hostName = KPLAY_HOSTNAME; //Hostname
$token = KPLAY_TOKEN; //AG Token
$agent = KPLAY_CODE; //AG Code
$method = '/gameinfo';
$header = array('Content-Type: application/json',
'ag-code: '.$agent,
'ag-token:'.$token);
$data = array(
'language' => "en"
);
$url = $hostName.$method;
$helper = new Helper;
$response = $helper->postData($url,$data,$header);
error_log(json_encode($data));
error_log($response);
$data = json_decode($response);
$status = $data->status;
$recommended = (array) $data->recommended;
$popular = (array) $data->popular;
$new_game = (array) $data->new_game;
if ($status == 1 && (!empty($recommended) || !empty($popular) || !empty($new_game)))
{
if (!empty($recommended))
{
$sql = "UPDATE game_list SET is_recommended = 0";
$stmt = $conn->prepare($sql);
$stmt->execute();
$stmt->close();
foreach ($recommended as $prdId => $gameInfos)
{
foreach($gameInfos as $gameInfo)
{
$gameId = $gameInfo->game_id;
$gameName = $gameInfo->game_name;
$sql = "UPDATE game_list
SET prd_id = ?
,game_id = ?
,game_name = ?
,is_recommended = 1
,updated_at = ?
WHERE prd_id = ?
AND game_id = ?";
$stmt = $conn->prepare($sql);
$updatedAt = date("Y-m-d H:i:s"); // Set the updated_at value
$stmt->bind_param("iissii", $prdId, $gameId, $gameName, $updatedAt, $prdId, $gameId);
$stmt->execute();
$stmt->close();
}
}
}
if (!empty($popular))
{
$sql = "UPDATE game_list SET is_popular = 0";
$stmt = $conn->prepare($sql);
$updatedAt = date("Y-m-d H:i:s"); // Set the updated_at value
$stmt->execute();
$stmt->close();
foreach ($popular as $prdId => $gameInfos)
{
foreach($gameInfos as $gameInfo)
{
$gameId = $gameInfo->game_id;
$gameName = $gameInfo->game_name;
$sql = "UPDATE game_list
SET prd_id = ?
,game_id = ?
,game_name = ?
,is_popular = 1
,updated_at = ?
WHERE prd_id = ?
AND game_id = ?";
$stmt = $conn->prepare($sql);
$updatedAt = date("Y-m-d H:i:s"); // Set the updated_at value
$stmt->bind_param("iissii", $prdId, $gameId, $gameName, $updatedAt, $prdId, $gameId);
$stmt->execute();
$stmt->close();
}
}
}
if (!empty($new_game))
{
$sql = "UPDATE game_list SET is_new = 0";
$stmt = $conn->prepare($sql);
$updatedAt = date("Y-m-d H:i:s"); // Set the updated_at value
$stmt->execute();
$stmt->close();
foreach ($new_game as $prdId => $gameInfos)
{
foreach($gameInfos as $gameInfo)
{
$gameId = $gameInfo->game_id;
$gameName = $gameInfo->game_name;
$sql = "UPDATE game_list
SET prd_id = ?
,game_id = ?
,game_name = ?
,is_new = 1
,updated_at = ?
WHERE prd_id = ?
AND game_id = ?";
$stmt = $conn->prepare($sql);
$updatedAt = date("Y-m-d H:i:s"); // Set the updated_at value
$stmt->bind_param("iissii", $prdId, $gameId, $gameName, $updatedAt, $prdId, $gameId);
$stmt->execute();
$stmt->close();
}
}
}
}
else if ($status == 0 )
{
$error = $data->error;
var_dump($error);
exit;
}
else
{
var_dump("call_api_error");
exit;
}
}
catch (Exception $e)
{
var_dump($e);
exit;
}
}
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.util.Map;
public class GameInfoConstructor {
public GameInfoConstructor() {
try {
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);
conn.createStatement().executeUpdate("SET NAMES 'UTF8'");
if (conn == null) {
System.out.println("Connection failed");
return;
}
String hostName = Constants.KPLAY_HOSTNAME;
String token = Constants.KPLAY_TOKEN;
String agent = Constants.KPLAY_CODE;
String method = "/gameinfo";
String[] header = {
"Content-Type: application/json",
"ag-code: " + agent,
"ag-token:" + token
};
Map data = Map.of("language", "en");
String url = hostName + method;
Helper helper = new Helper();
String response = helper.postData(url, data, header);
System.out.println(data);
System.out.println(response);
Map jsonData = Helper.parseJson(response);
int status = (int) jsonData.get("status");
Map recommended = (Map) jsonData.get("recommended");
Map popular = (Map) jsonData.get("popular");
Map newGame = (Map) jsonData.get("new_game");
if (status == 1 && (!recommended.isEmpty() || !popular.isEmpty() || !newGame.isEmpty())) {
if (!recommended.isEmpty()) {
PreparedStatement stmt = conn.prepareStatement("UPDATE game_list SET is_recommended = 0");
stmt.executeUpdate();
stmt.close();
for (Map.Entry entry : recommended.entrySet()) {
String prdId = entry.getKey();
Map gameInfos = (Map) entry.getValue();
for (Map.Entry gameInfo : gameInfos.entrySet()) {
int gameId = (int) gameInfo.getValue();
String gameName = (String) gameInfo.getKey();
String sql = "UPDATE game_list SET prd_id = ?, game_id = ?, game_name = ?, is_recommended = 1, updated_at = ? WHERE prd_id = ? AND game_id = ?";
PreparedStatement updateStmt = conn.prepareStatement(sql);
// Assuming updatedAt is available as a string in the desired format
String updatedAt = Helper.getCurrentDateTime();
updateStmt.setString(1, prdId);
updateStmt.setInt(2, gameId);
updateStmt.setString(3, gameName);
updateStmt.setInt(4, 1);
updateStmt.setString(5, updatedAt);
updateStmt.executeUpdate();
updateStmt.close();
}
}
}
// Similarly handle popular and new_game sections as per your logic
// (Not implemented due to space constraints)
} else if (status == 0) {
String error = (String) jsonData.get("error");
System.out.println(error);
return;
} else {
System.out.println("call_api_error");
return;
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
using System;
using System.Data.SqlClient;
using Newtonsoft.Json.Linq;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
public class GameInfoUpdater
{
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 KPLAY_HOSTNAME = "YourKPLAY_HOSTNAME";
private const string KPLAY_TOKEN = "YourKPLAY_TOKEN";
private const string KPLAY_CODE = "YourKPLAY_CODE";
public async Task UpdateGameInfo()
{
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 = KPLAY_HOSTNAME; // Hostname
string token = KPLAY_TOKEN; // Token
string agent = KPLAY_CODE; // Code
string method = "/gameinfo";
string[] header = {
"Content-Type: application/json",
"ag-code: " + agent,
"ag-token: " + token
};
var data = new { language = "en" };
string jsonData = JsonConvert.SerializeObject(data);
string url = hostName + method;
HttpClient httpClient = new HttpClient();
var content = new StringContent(jsonData, Encoding.UTF8, "application/json");
HttpResponseMessage responseMessage = await httpClient.PostAsync(url, content);
string response = await responseMessage.Content.ReadAsStringAsync();
Console.WriteLine(JsonConvert.SerializeObject(data));
Console.WriteLine(response);
dynamic responseData = JObject.Parse(response);
int status = responseData.status;
var recommended = (JObject)responseData.recommended;
var popular = (JObject)responseData.popular;
var new_game = (JObject)responseData.new_game;
if (status == 1 && (recommended.HasValues || popular.HasValues || new_game.HasValues))
{
if (recommended.HasValues)
{
string sql = "UPDATE game_list SET is_recommended = 0";
using (SqlCommand stmt = new SqlCommand(sql, conn))
{
stmt.ExecuteNonQuery();
}
foreach (var prdId in recommended.Properties())
{
foreach (var gameInfo in recommended[prdId.Name])
{
int gameId = gameInfo["game_id"].Value();
string gameName = gameInfo["game_name"].Value();
sql = "UPDATE game_list " +
"SET prd_id = @prdId, " +
" game_id = @gameId, " +
" game_name = @gameName, " +
" is_recommended = 1, " +
" updated_at = @updatedAt " +
"WHERE prd_id = @prdId AND game_id = @gameId";
using (SqlCommand updateStmt = new SqlCommand(sql, conn))
{
updateStmt.Parameters.AddWithValue("@prdId", prdId.Name);
updateStmt.Parameters.AddWithValue("@gameId", gameId);
updateStmt.Parameters.AddWithValue("@gameName", gameName);
updateStmt.Parameters.AddWithValue("@updatedAt", DateTime.Now);
updateStmt.ExecuteNonQuery();
}
}
}
}
if (popular.HasValues)
{
string sql = "UPDATE game_list SET is_popular = 0";
using (SqlCommand stmt = new SqlCommand(sql, conn))
{
stmt.ExecuteNonQuery();
}
foreach (var prdId in popular.Properties())
{
foreach (var gameInfo in popular[prdId.Name])
{
int gameId = gameInfo["game_id"].Value();
string gameName = gameInfo["game_name"].Value();
sql = "UPDATE game_list " +
"SET prd_id = @prdId, " +
" game_id = @gameId, " +
" game_name = @gameName, " +
" is_popular = 1, " +
" updated_at = @updatedAt " +
"WHERE prd_id = @prdId AND game_id = @gameId";
using (SqlCommand updateStmt = new SqlCommand(sql, conn))
{
updateStmt.Parameters.AddWithValue("@prdId", prdId.Name);
updateStmt.Parameters.AddWithValue("@gameId", gameId);
updateStmt.Parameters.AddWithValue("@gameName", gameName);
updateStmt.Parameters.AddWithValue("@updatedAt", DateTime.Now);
updateStmt.ExecuteNonQuery();
}
}
}
}
if (new_game.HasValues)
{
string sql = "UPDATE game_list SET is_new = 0";
using (SqlCommand stmt = new SqlCommand(sql, conn))
{
stmt.ExecuteNonQuery();
}
foreach (var prdId in new_game.Properties())
{
foreach (var gameInfo in new_game[prdId.Name])
{
int gameId = gameInfo["game_id"].Value();
string gameName = gameInfo["game_name"].Value();
sql = "UPDATE game_list " +
"SET prd_id = @prdId, " +
" game_id = @gameId, " +
" game_name = @gameName, " +
" is_new = 1, " +
" updated_at = @updatedAt " +
"WHERE prd_id = @prdId AND game_id = @gameId";
using (SqlCommand updateStmt = new SqlCommand(sql, conn))
{
updateStmt.Parameters.AddWithValue("@prdId", prdId.Name);
updateStmt.Parameters.AddWithValue("@gameId", gameId);
updateStmt.Parameters.AddWithValue("@gameName", gameName);
updateStmt.Parameters.AddWithValue("@updatedAt", DateTime.Now);
updateStmt.ExecuteNonQuery();
}
}
}
}
}
else if (status == 0)
{
string error = responseData.error;
Console.WriteLine(error);
}
else
{
Console.WriteLine("call_api_error");
}
}
}
catch (Exception e)
{
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, status, recommended, popular, new_game, prdId, gameId, gameName, sql, stmt
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
conn.Execute "SET NAMES 'UTF8'"
hostName = KPLAY_HOSTNAME ' Hostname
token = KPLAY_TOKEN ' Token
agent = KPLAY_CODE ' Code
method = "/gameinfo"
Set header = Server.CreateObject("Scripting.Dictionary")
header.Add "Content-Type", "application/json"
header.Add "ag-code", agent
header.Add "ag-token", token
Set data = Server.CreateObject("Scripting.Dictionary")
data.Add "language", "en"
url = hostName & method
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(JSON.stringify(data))
responseText = helper.responseText
Set data = JSON.parse(responseText)
status = data("status")
recommended = data("recommended")
popular = data("popular")
new_game = data("new_game")
If status = 1 And (Not IsEmpty(recommended) Or Not IsEmpty(popular) Or Not IsEmpty(new_game)) Then
If Not IsEmpty(recommended) Then
sql = "UPDATE game_list SET is_recommended = 0"
conn.Execute sql
For Each prdId In recommended.Keys
For Each gameInfo In recommended(prdId)
gameId = gameInfo("game_id")
gameName = gameInfo("game_name")
sql = "UPDATE game_list SET prd_id = ?, game_id = ?, game_name = ?, is_recommended = 1, updated_at = ? WHERE prd_id = ? AND game_id = ?"
Set stmt = conn.Prepare(sql)
stmt.Parameters.Append stmt.CreateParameter("@prdId", 200, 1, 255, prdId)
stmt.Parameters.Append stmt.CreateParameter("@gameId", 200, 1, 255, gameId)
stmt.Parameters.Append stmt.CreateParameter("@gameName", 200, 1, 255, gameName)
stmt.Parameters.Append stmt.CreateParameter("@updatedAt", 200, 1, 255, Now())
stmt.Parameters.Append stmt.CreateParameter("@prdId2", 200, 1, 255, prdId)
stmt.Parameters.Append stmt.CreateParameter("@gameId2", 200, 1, 255, gameId)
stmt.Execute
stmt.Close
Next
Next
End If
If Not IsEmpty(popular) Then
sql = "UPDATE game_list SET is_popular = 0"
conn.Execute sql
For Each prdId In popular.Keys
For Each gameInfo In popular(prdId)
gameId = gameInfo("game_id")
gameName = gameInfo("game_name")
sql = "UPDATE game_list SET prd_id = ?, game_id = ?, game_name = ?, is_popular = 1, updated_at = ? WHERE prd_id = ? AND game_id = ?"
Set stmt = conn.Prepare(sql)
stmt.Parameters.Append stmt.CreateParameter("@prdId", 200, 1, 255, prdId)
stmt.Parameters.Append stmt.CreateParameter("@gameId", 200, 1, 255, gameId)
stmt.Parameters.Append stmt.CreateParameter("@gameName", 200, 1, 255, gameName)
stmt.Parameters.Append stmt.CreateParameter("@updatedAt", 200, 1, 255, Now())
stmt.Parameters.Append stmt.CreateParameter("@prdId2", 200, 1, 255, prdId)
stmt.Parameters.Append stmt.CreateParameter("@gameId2", 200, 1, 255, gameId)
stmt.Execute
stmt.Close
Next
Next
End If
If Not IsEmpty(new_game) Then
sql = "UPDATE game_list SET is_new = 0"
conn.Execute sql
For Each prdId In new_game.Keys
For Each gameInfo In new_game(prdId)
gameId = gameInfo("game_id")
gameName = gameInfo("game_name")
sql = "UPDATE game_list SET prd_id = ?, game_id = ?, game_name = ?, is_new = 1, updated_at = ? WHERE prd_id = ? AND game_id = ?"
Set stmt = conn.Prepare(sql)
stmt.Parameters.Append stmt.CreateParameter("@prdId", 200, 1, 255, prdId)
stmt.Parameters.Append stmt.CreateParameter("@gameId", 200, 1, 255, gameId)
stmt.Parameters.Append stmt.CreateParameter("@gameName", 200, 1, 255, gameName)
stmt.Parameters.Append stmt.CreateParameter("@updatedAt", 200, 1, 255, Now())
stmt.Parameters.Append stmt.CreateParameter("@prdId2", 200, 1, 255, prdId)
stmt.Parameters.Append stmt.CreateParameter("@gameId2", 200, 1, 255, gameId)
stmt.Execute
stmt.Close
Next
Next
End If
ElseIf status = 0 Then
error = data("error")
Response.Write(error)
Response.End
Else
Response.Write("call_api_error")
Response.End
End If
%>
PHP Sample
Java Sample
.Net Sample
Asp Sample
function __construct()
{
$this->servername = DB_SERVER_NAME;
$this->username = DB_USERNAME;
$this->password = DB_PASSWORD;
$this->dbname = DB_NAME;
$this->hostName = KPLAY_HOSTNAME; //Hostname
$this->token = KPLAY_TOKEN; //AG Token
$this->agent = KPLAY_CODE; //AG Code
//prepare header
$this->header = [
'Content-Type: application/json',
'Ag-Code: '.KPLAY_CODE,
'Ag-Token:'.KPLAY_TOKEN,
];
}
public function getPushBet($prdId, $txnId)
{
try
{
$method = 'getpushbets'; //auth game method
$url = $this->hostName.$method;
//prepare data
$data = [
'prd_id' => $prdId,
'txn_id' => $txnId
];
$helper = new Helper;
$response = $helper->postData($url,$data,$this->header);
$data = json_decode($response);
if ($data->status == 1 && !empty($data->data))
{
$conn = new \mysqli($this->servername, $this->username, $this->password, $this->dbname);
$conn->query("SET NAMES 'UTF8'");
//if connect to DB failed
if ($conn->connect_error)
{
var_dump("Connection failed: " . $conn->connect_error);
exit;
}
$txnId = $data->data[0]->txn_id;
$pushedAmt = $data->data[0]->pushed_amount;
$pushedAmt1 = $data->data[0]->pushed_amount1;
$stmt = $conn->prepare("INSERT INTO pushed_txn
(txn_id, prd_id,pushed_amount,pushed_amount1)
VALUES(?,?,?,?)");
$prdId = 1;
$stmt->bind_param("siii", $txnId, $prdId ,$pushedAmt,$pushedAmt1);
$stmt->execute();
$stmt->close();
}
return $response;
}
catch(\Exception $e)
{
var_dump($e);
exit;
}
}
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
%>
PHP Sample
Java Sample
.Net Sample
ASP Sample
try
{
$servername = DB_SERVER_NAME;
$username = DB_USERNAME;
$password = DB_PASSWORD;
$dbname = DB_NAME;
$memberId = EXAMPLE_MEMBER_ID;
$conn = new \mysqli($servername, $username, $password, $dbname);
//if connect to DB failed
if ($conn->connect_error)
{
error_log('connect_db_error');
exit;
}
$hostName = KPLAYT_HOSTNAME; //Hostname
$token = KPLAYT_AG_TOKEN; //AG Token
$agent = KPLAYT_AG_CODE; //AG Code
$method = '/withdraw-all';
$header = array('Content-Type: application/json',
'ag-code: '.$agent,
'ag-token:'.$token);
$stmt = $conn->prepare("SELECT username FROM users WHERE id = ?");
$stmt->bind_param("s", $memberId);
$stmt->execute();
$result = $stmt->get_result();
$db = $result->fetch_all(MYSQLI_ASSOC);
$stmt->close();
if (count($db) == 0)
{
error_log('run_cron_error');
exit;
}
$username = $db[0]['username'];
$txnId = round(microtime(true)*1000);
(strlen($txnId) > 12) ? substr($txnId, 0, 12) : $txnId;
$data = [
'user' => [
'id' => $memberId,
'name' => $username,
'currency' => 'KRW'
],
'txn_id'=> $txnId
];
$url = $hostName.$method;
$helper = new Helper;
$response = $helper->postData($url,$data,$header);
$data = json_decode($response);
if (!empty($data) && array_key_exists('transaction', $data))
{
if ($data->status == 1)
{
$withdrawTxns = (array) $data->transaction;
foreach ($withdrawTxns as $withdrawtxn)
{
$prdId = $withdrawtxn->prd_id;
$txn_id = $withdrawtxn->internal_txn_id;
$amount = $withdrawtxn->amount;
$status = $withdrawtxn->status;
$sql = "INSERT INTO funds_transfer (user_id, amount, type, product, txn_id, txn_status) VALUES (?, ?, ?, ?, ?, ?)";
$type = 'w';
$stmt = $conn->prepare($sql);
$stmt->bind_param("iisiii", $memberId, $amount, $type, $prdId, $txnId, $status);
$stmt->execute();
$stmt->close();
}
}
}
else
{
error_log('call_api_error');
exit;
}
}
catch (Exception $e)
{
error_log('run_cron_error');
exit;
}
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
public class WithdrawProcess {
public void withdraw() {
try {
String servername = Constants.DB_SERVER_NAME;
String username = Constants.DB_USERNAME;
String password = Constants.DB_PASSWORD;
String dbname = Constants.DB_NAME;
String memberId = Constants.EXAMPLE_MEMBER_ID;
Connection conn = DriverManager.getConnection("jdbc:mysql://" + servername + "/" + dbname, username, password);
if (conn == null) {
System.out.println("Connection failed");
return;
}
String hostName = Constants.KPLAYT_HOSTNAME; //Hostname
String token = Constants.KPLAYT_AG_TOKEN; //AG Token
String agent = Constants.KPLAYT_AG_CODE; //AG Code
String method = "/withdraw-all";
String[] header = {
"Content-Type: application/json",
"ag-code: " + agent,
"ag-token:" + token
};
PreparedStatement stmt = conn.prepareStatement("SELECT username FROM users WHERE id = ?");
stmt.setString(1, memberId);
ResultSet result = stmt.executeQuery();
if (!result.next()) {
System.out.println("run_cron_error");
return;
}
String username = result.getString("username");
stmt.close();
long txnId = Math.round(System.currentTimeMillis());
if (String.valueOf(txnId).length() > 12) {
String.valueOf(txnId).substring(0, 12);
}
String jsonData = String.format(
"{\"user\":{\"id\":%s,\"name\":\"%s\",\"currency\":\"KRW\"},\"txn_id\":%d}",
memberId, username, txnId);
String url = hostName + method;
Helper helper = new Helper();
String response = helper.postData(url, jsonData, header);
Map data = Helper.parseJson(response);
if (data != null && data.containsKey("transaction")) {
int status = (int) data.get("status");
if (status == 1) {
List> withdrawTxns = (List>) data.get("transaction");
for (Map withdrawTxn : withdrawTxns) {
int prdId = (int) withdrawTxn.get("prd_id");
int internalTxnId = (int) withdrawTxn.get("internal_txn_id");
double amount = (double) withdrawTxn.get("amount");
int txnStatus = (int) withdrawTxn.get("status");
String sql = "INSERT INTO funds_transfer (user_id, amount, type, product, txn_id, txn_status) VALUES (?, ?, ?, ?, ?, ?)";
String type = "w";
PreparedStatement insertStmt = conn.prepareStatement(sql);
insertStmt.setString(1, memberId);
insertStmt.setDouble(2, amount);
insertStmt.setString(3, type);
insertStmt.setInt(4, prdId);
insertStmt.setInt(5, internalTxnId);
insertStmt.setInt(6, txnStatus);
insertStmt.executeUpdate();
insertStmt.close();
}
}
} else {
System.out.println("call_api_error");
return;
}
} catch (Exception e) {
e.printStackTrace();
System.out.println("run_cron_error");
}
}
}
using System;
using System.Data.SqlClient;
using Newtonsoft.Json.Linq;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
public class WithdrawProcessor
{
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 = 12345;
public async Task ProcessWithdraw()
{
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 method = "/withdraw-all";
string[] header = {
"Content-Type: application/json",
"ag-code: " + agent,
"ag-token: " + token
};
using (SqlCommand stmt = new SqlCommand("SELECT username FROM users WHERE id = @memberId", conn))
{
stmt.Parameters.AddWithValue("@memberId", memberId);
using (SqlDataReader reader = stmt.ExecuteReader())
{
if (!reader.HasRows)
{
Console.WriteLine("run_cron_error");
return;
}
reader.Read();
string username = reader.GetString(0);
long txnId = (long)(DateTime.UtcNow.Subtract(new DateTime(1970, 1, 1))).TotalMilliseconds;
string data = "{\"user\": {\"id\": " + memberId + ", \"name\": \"" + username + "\", \"currency\": \"KRW\"}, \"txn_id\": " + txnId + "}";
string url = hostName + method;
HttpClient httpClient = new HttpClient();
var content = new StringContent(data, Encoding.UTF8, "application/json");
HttpResponseMessage responseMessage = await httpClient.PostAsync(url, content);
string response = await responseMessage.Content.ReadAsStringAsync();
dynamic responseData = JObject.Parse(response);
if (responseData != null && responseData.transaction != null)
{
if (responseData.status == 1)
{
var withdrawTxns = (JArray)responseData.transaction;
foreach (var withdrawTxn in withdrawTxns)
{
int prdId = withdrawTxn["prd_id"].Value();
int internalTxnId = withdrawTxn["internal_txn_id"].Value();
decimal amount = withdrawTxn["amount"].Value();
int status = withdrawTxn["status"].Value();
string sql = "INSERT INTO funds_transfer (user_id, amount, type, product, txn_id, txn_status) VALUES (@memberId, @amount, @type, @prdId, @txnId, @status)";
string type = "w";
using (SqlCommand insertStmt = new SqlCommand(sql, conn))
{
insertStmt.Parameters.AddWithValue("@memberId", memberId);
insertStmt.Parameters.AddWithValue("@amount", amount);
insertStmt.Parameters.AddWithValue("@type", type);
insertStmt.Parameters.AddWithValue("@prdId", prdId);
insertStmt.Parameters.AddWithValue("@txnId", txnId);
insertStmt.Parameters.AddWithValue("@status", status);
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, memberId, username, txnId, withdrawTxns, prdId, amount, status, sql
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
method = "/withdraw-all"
Set header = Server.CreateObject("Scripting.Dictionary")
header.Add "Content-Type", "application/json"
header.Add "ag-code", agent
header.Add "ag-token", token
Set stmt = conn.Prepare("SELECT username FROM users WHERE id = ?")
stmt.Parameters.Append stmt.CreateParameter("@memberId", 200, 1, 255, memberId)
stmt.Execute
Set result = stmt.resultSet
If result.EOF Then
Response.Write("run_cron_error")
Response.End
End If
username = result.Fields.Item("username").Value
stmt.Close
txnId = Round(Timer() * 1000)
If Len(txnId) > 12 Then
txnId = Left(txnId, 12)
End If
Set data = Server.CreateObject("Scripting.Dictionary")
data.Add "user", Server.CreateObject("Scripting.Dictionary")
data("user").Add "id", memberId
data("user").Add "name", username
data("user").Add "currency", "KRW"
data.Add "txn_id", txnId
url = hostName & method
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(JSON.stringify(data))
responseText = helper.responseText
Set data = JSON.parse(responseText)
If Not IsEmpty(data) And IsObject(data) And data.Exists("transaction") Then
If data("status") = 1 Then
Set withdrawTxns = data("transaction")
For Each withdrawtxn In withdrawTxns
prdId = withdrawtxn("prd_id")
txn_id = withdrawtxn("internal_txn_id")
amount = withdrawtxn("amount")
status = withdrawtxn("status")
sql = "INSERT INTO funds_transfer (user_id, amount, type, product, txn_id, txn_status) VALUES (?, ?, ?, ?, ?, ?)"
Set stmt = conn.Prepare(sql)
stmt.Parameters.Append stmt.CreateParameter("@memberId", 200, 1, 255, memberId)
stmt.Parameters.Append stmt.CreateParameter("@amount", 200, 1, 255, amount)
stmt.Parameters.Append stmt.CreateParameter("@type", 200, 1, 255, "w")
stmt.Parameters.Append stmt.CreateParameter("@prdId", 200, 1, 255, prdId)
stmt.Parameters.Append stmt.CreateParameter("@txnId", 200, 1, 255, txnId)
stmt.Parameters.Append stmt.CreateParameter("@status", 200, 1, 255, status)
stmt.Execute
stmt.Close
Next
End If
Else
Response.Write("call_api_error")
Response.End
End If
%>
PHP Sample
Java Sample
.Net Sample
ASP Sample
try
{
$servername = DB_SERVER_NAME;
$username = DB_USERNAME;
$password = DB_PASSWORD;
$dbname = DB_NAME;
$memberId = EXAMPLE_MEMBER_ID;
$conn = new \mysqli($servername, $username, $password, $dbname);
//if connect to DB failed
if ($conn->connect_error)
{
error_log('connect_db_error');
exit;
}
$hostName = KPLAYT_HOSTNAME; //Hostname
$token = KPLAYT_AG_TOKEN; //AG Token
$agent = KPLAYT_AG_CODE; //AG Code
$header = array('Content-Type: application/json',
'ag-code: '.$agent,
'ag-token:'.$token);
$method = '/remainingdeposit';
$url = $hostName.$method;
$helper = new Helper;
$response = $helper->getData($url,$header);
$data = json_decode($response);
if (!empty($data))
{
if ($data->status == 1)
{
$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 = ?";
$stmt = $conn->prepare($sql);
$stmt->bind_param("iiii", $givenDeposit, $availableDeposit, $givenDeposit, $availableDeposit);
$stmt->execute();
$stmt->close();
}
}
else
{
error_log('call_api_error');
exit;
}
}
catch (Exception $e)
{
error_log('run_cron_error');
exit;
}
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
public class RemainingDeposit {
public void updateRemainingDeposit() {
try {
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;
}
int memberId = Constants.EXAMPLE_MEMBER_ID;
String hostName = Constants.KPLAYT_HOSTNAME; // Hostname
String token = Constants.KPLAYT_AG_TOKEN; // AG Token
String agent = Constants.KPLAYT_AG_CODE; // AG Code
String[] header = {
"Content-Type: application/json",
"ag-code: " + agent,
"ag-token:" + token
};
String method = "/remainingdeposit";
String url = hostName + method;
Helper helper = new Helper();
String response = helper.getData(url, header);
// Assuming Helper class is handling JSON parsing
JSONParser parser = new JSONParser();
JSONObject data = (JSONObject) parser.parse(response);
if (data != null) {
if (data.get("status").equals(1)) {
int givenDeposit = Integer.parseInt(data.get("given_deposit").toString());
int availableDeposit = Integer.parseInt(data.get("available_deposit").toString());
String sql = "INSERT INTO remaining_deposit (given_deposit, available_deposit) " +
"VALUES (?, ?) " +
"ON DUPLICATE KEY UPDATE " +
"given_deposit = ?, " +
"available_deposit = ?";
PreparedStatement stmt = conn.prepareStatement(sql);
stmt.setInt(1, givenDeposit);
stmt.setInt(2, availableDeposit);
stmt.setInt(3, givenDeposit);
stmt.setInt(4, availableDeposit);
stmt.execute();
stmt.close();
}
} else {
System.out.println("call_api_error");
return;
}
} catch (Exception e) {
e.printStackTrace();
System.out.println("run_cron_error");
}
}
}
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
%>