Skip to content

Instantly share code, notes, and snippets.

@likecyber
Last active June 2, 2019 02:23
Show Gist options
  • Save likecyber/8191b601ce4d4e5b4545d06ffa907b71 to your computer and use it in GitHub Desktop.
Save likecyber/8191b601ce4d4e5b4545d06ffa907b71 to your computer and use it in GitHub Desktop.
Build/Extract PromptPay QR Code Payload in PHP for convenience payment.
<?php
class PromptPay_QR_Payload {
public function Generate ($ewallet_id, $amount = null, $one_time = false) {
switch (strlen($ewallet_id)) {
case 10:
$ewallet_type = "01"; // Phone Number
$ewallet_id = "0066".substr($ewallet_id, 1, 9);
break;
case 13:
$ewallet_type = "02"; // ID Card
break;
default:
$ewallet_type = "03"; // e-Wallet
break;
}
$data = array(
"01" => $one_time ? "12" : "11", // Point of Initiation
"29" => array( // Merchant Account Information
"00" => "A000000677010111", // Globally Unique Identifier
$ewallet_type => $ewallet_id // Payment network specific
),
"53" => "764", // Transaction Currency
"54" => number_format($amount, 2, ".", ""), // Transaction Amount
"58" => "TH", // Country Code
);
if (is_null($amount)) unset($data["54"]);
return self::Build($data);
}
public function Build ($data, $object = false) {
if (!$object) $data = array("00" => "01") + $data + array("63" => str_repeat(" ", 4));
$payload = "";
foreach ($data as $key => $value) {
if (is_array($value)) {
$value = self::Build($value, true);
}
$payload .= $key;
$payload .= sprintf("%02d", strlen($value));
$payload .= $value;
}
if (!$object) $payload = trim($payload).self::GetCRC(trim($payload));
return $payload;
}
public function Extract ($payload, $object = false) {
$data = array();
$pointer = 0;
while ($pointer < strlen($payload)) {
$key = substr($payload, $pointer, 2);
$value = substr($payload, $pointer + 4, intval(substr($payload, $pointer + 2, 2)));
if (!$object && intval($key) >= 26 && intval($key) <= 51) {
$value = self::Extract($value, true);
}
$data[$key] = $value;
$pointer += 4 + intval(substr($payload, $pointer + 2, 2));
}
return $data;
}
public function GetCRC ($data) {
$crc = 0xFFFF;
for ($i = 0; $i < strlen($data); $i++) {
$x = (($crc >> 8) ^ ord($data[$i])) & 0xFF;
$x ^= $x >> 4;
$crc = (($crc << 8) ^ ($x << 12) ^ ($x << 5) ^ $x) & 0xFFFF;
}
return strtoupper(dechex($crc));
}
}
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment