Access Token
For system security purposes, there are two steps you need to fulfillment before sending transaction requests.
Step 1. Fetch random code
At the beginning of the request process, you should fetch a random code from our service.
Request
API URL: /merchant/random_code
✅ Required ⭕ Optional ❌ Not used
Header | Content |
---|---|
Content-Type | application/json |
Param | Type | Required | Description |
---|---|---|---|
user_id | String | ✅ | Merchant identification |
- PHP
- Java
- Python
function get_random_code()
{
global $user_id, $base_url;
$url = "{$base_url}/merchant/random_code";
$params = json_encode(['user_id' => $user_id]);
$header = ['Content-Type: application/json'];
$response = send_curl_request($url, $params, $header);
$response = json_decode($response, true);
return $response['data']['code'];
}
function send_curl_request($url, $body, $header): string
{
$curl = curl_init();
curl_setopt_array($curl, [
CURLOPT_URL => $url,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => 'utf-8',
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 0,
CURLOPT_FOLLOWLOCATION => true,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => 'POST',
CURLOPT_POSTFIELDS => $body,
CURLOPT_HTTPHEADER => $header,
CURLOPT_USERAGENT => 'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:38.0) Gecko/20100101 Firefox/38.0',
]);
$response = curl_exec($curl);
curl_close($curl);
return $response;
}
public static String getRandomCode() throws UnirestException {
Map<String, String> params = new HashMap<>();
params.put("user_id", userId);
JSONObject jsonObject = new JSONObject();
SortedSet<String> parameter = new TreeSet<>(params.keySet());
for (String key : parameter) {
jsonObject.put(key, params.get(key));
}
Unirest.setTimeouts(0, 0);
HttpResponse<JsonNode> jsonResponse = Unirest.post(requestUrl + "/merchant/random_code")
.header("Content-Type", "application/json")
.body(jsonObject.toString())
.asJson();
System.out.println("getRandomCode response:: " + jsonResponse.getBody());
return jsonResponse.getBody().getObject().getJSONObject("data").getString("code");
}
def get_random_code():
response = requests.post(url=(url + '/merchant/random_code'), json={'user_id': user_id})
print(response.text)
if response.status_code == 200:
dict_obj = json.loads(response.text)
return dict_obj.get('data')['code']
else:
return None
Response
Param | Type | Required | Description |
---|---|---|---|
code | String | ✅ | The random code to fetch access token. Please note it only alive for 5 minutes |
expires_in | Interger | ✅ | random code expire time in second |
expires_at | Interger | ✅ | random code expire time at timestamp |
{
"code": "1000",
"message": "Accepted",
"data": {
"code": "VL4hrMLmM3THd2iQDNOoa45cGZhx2zH7", // here is the random code
"expires_in": 300,
"expires_at": 1704699776
}
}
Step 2. Get access token
After getting random code, then you need to send second request to get access token which should be put in each transaction request you send to PTS. The access token will keep living until expire time provided in response reached. That means you should cache the access token in your service and do the two steps request again when access token expired.
You should implement some mechanism to keep the access token and detect if it is expired or not before sending your transaction request.
Request
API URL: /merchant/token
Header | Content |
---|---|
Content-Type | application/json |
Param | Type | Required | Description |
---|---|---|---|
user_id | String | ✅ | Merchant identification |
hash | String | ✅ | Please follow the tip below to generate. |
Please concat random_code
+ user_id
+ safecode
in given order without any separator or whitespace. Then put the concatenated string into SHA256
hash function to get the hash code.
- PHP
- Java
- Python
function get_token(): string
{
global $user_id, $safecode, $base_url;
$url = "{$base_url}/merchant/token";
$params = json_encode([
'user_id' => $user_id,
'hash' => hash('SHA256', get_random_code().$user_id.$safecode)
]);
$header = ['Content-Type: application/json'];
$response = send_curl_request($url, $params, $header);
$response = json_decode($response, true);
$data = $response['data'];
return $data['token_type'].' '.$data['access_token'];
}
function send_curl_request($url, $body, $header): string
{
$curl = curl_init();
curl_setopt_array($curl, [
CURLOPT_URL => $url,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => 'utf-8',
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 0,
CURLOPT_FOLLOWLOCATION => true,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => 'POST',
CURLOPT_POSTFIELDS => $body,
CURLOPT_HTTPHEADER => $header,
CURLOPT_USERAGENT => 'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:38.0) Gecko/20100101 Firefox/38.0',
]);
$response = curl_exec($curl);
curl_close($curl);
return $response;
}
public static String getToken() {
try {
String randomCode = getRandomCode();
String originalString = randomCode + userId + safecode;
System.out.println("getToken originalString::" + originalString);
String sha256hex = DigestUtils.sha256Hex(originalString);
Map<String, String> params = new HashMap<>();
params.put("user_id", userId);
params.put("hash", sha256hex);
JSONObject jsonObject = new JSONObject();
SortedSet<String> parameter = new TreeSet<>(params.keySet());
for (String key : parameter) {
jsonObject.put(key, params.get(key));
}
Unirest.setTimeouts(0, 0);
HttpResponse<JsonNode> jsonResponse = Unirest.post(requestUrl + "/merchant/token")
.header("Content-Type", "application/json")
.body(jsonObject.toString())
.asJson();
System.out.println("getToken response:: " + jsonResponse.getBody());
String tokenType = jsonResponse.getBody().getObject().getJSONObject("data").getString("token_type");
String accessToken = jsonResponse.getBody().getObject().getJSONObject("data").getString("access_token");
return tokenType + " " + accessToken;
} catch (Exception e) {
e.printStackTrace();
}
return "";
}
def get_token():
random_code = get_random_code()
s = hashlib.sha256()
before_hash_string = (random_code + user_id + safecode).encode('utf-8')
s.update(before_hash_string)
hash_value = s.hexdigest()
response = requests.post(url=(url + '/merchant/token'), json={'user_id': user_id, 'hash': hash_value})
print(response.text)
if response.status_code == 200:
dict_obj = json.loads(response.text)
return dict_obj.get('data')['token_type'] + ' ' + dict_obj.get('data')['access_token']
else:
return None
Response
Param | Type | Required | Description |
---|---|---|---|
access_token | String | ✅ | the token to put into your request header. Please note it only alive for 60 minutes |
token_type | String | ✅ | the type of token |
expires_in | Interger | ✅ | token expire time in second |
expires_at | Interger | ✅ | token expire time at timestamp |
// Example
{
"code": "1000",
"message": "Accepted",
"data": {
"access_token": "cyJacasxzxc...",
"token_type": "bearer",
"expires_in": 300,
"expires_at": 1704699776
}
}