PHP access to Thailand's payment gateway example tutorials

# PHP Access to Thailand Payment Gateway Tutorial Example

1. Preparatory work

Before you start, you need to:
- A merchant account with a Thai payment gateway (e.g. 2C2P, Omise, TrueMoney, etc.)
- PHP development environment (PHP 7.0+ recommended)
- Composer Dependency Management Tool
- Web server (Apache/Nginx)

2. Installation of necessary libraries

"`bash
composer require guzzlehttp/guzzle
“`

3. Omise Payment Gateway Integration Example

a) Omise initialisation configuration

"`php
client = new Client([
'base_uri' => $this->apiUrl,
'auth' => [$this->secretKey, "]
]);
}
}
“`

b) Create payment requests

"`php
public function createCharge($amount, $currency, $token) {
try {
$response = $this->client->post('/charges', [
'form_params' => [
'amount' => intval($amount * 100), // Omise uses the smallest currency unit (cents)
'currency' => strtolower($currency),
'card' => $token.
// Thailand specific parameters if needed
// …
]
]);

return json_decode($response->getBody(), true);

} catch (Exception $e) {
error_log('Omise charge error: '.$e->getMessage());
return ['error' => true];
}
}
“`

c) Token Generation Front-end Code Example (JavaScript)

"`javascript
// After introducing the Omise.js library in HTML.

“`

4. Example of TrueMoney Wallet integration

a) API Configuration Classes

"`php
class TrueMoneyWalletPayment {
private const BASE_URL_SANDBOX = "https://sandbox.truemoney.com/api/v1″;
private const BASE_URL_PRODUCTION = "https://tmn-prod.apigee.net/api/v1";

public function __construct(private string|bool|null $_isSandbox=true){}

protected function getBaseURL():string{
return ($this->_isSandbox)?self::BASE_URL_SANDBOX:self::BASE_URL_PRODUCTION;
}

protected static array $_headers=[
"Content-Type"=>"application/json".
"Accept"=>"application/json"
];

public static array $_requiredFields=["username", "password"];

}
“`

b) QR Code Payment Processing Flow

"`php
/
* @param float|int|string amount - payment amount in THB (฿)
* @param string merchantRef - unique reference ID for transaction tracking
*/
public static async generateQRCode(
float|int|string amount=null ,
string merchantRef="" ,
bool isSandBox=false):array{

try{

# Validate required fields and amounts...

# Prepare request data for TrueMoney API
$_requestData=[
"paymentAmount"=>floatval(number_format(floatval(str_replace(","," ",$amount)),2,"." , "")),
"merchantReferenceId"=>strtoupper(substr(preg_replace("/[^A-Za-z0-9]+/i ","",trim((empty($_merchantReference))?uniqid():$_merchantReference)),0 ,20)),
... # other required params per TMN docs
];

}catch(\Throwable|\Exception|\ErrorException$exception){
throw new \RuntimeException(sprintf("%s:%s ",__METHOD__,$exception));;
}

return [];
}
“`
Note: For actual implementation, please refer to the latest TrueMoney API documentation.

5 . Solving common problems

Q: SSL certificate validation failed?
A: `curl_setopt($ch,CURLOPT_SSL_VERIFYPEER,FALSE);` (test environment only)

Q: HTTP response status code 403?
A: IP whitelist is not set or API key is invalid. Check the merchant backend IP restriction settings.

The above is the basic framework of PHP access to the mainstream payment gateways in Thailand. Please be sure to implement it exactly:

1. Carefully read the latest official documentation of the selected gateway.
2. Enabling HTTPS and strict data validation in production environments
3. Consider adding logs to record all transaction requests and responses

Depending on your business needs, you may also need to process refunds, check transaction status, and other functions.

PHP access to Thailand payment gateway example tutorial (continued)

6. 2C2P Payment Gateway Integration Example

a) Initialising the configuration

class Payment2C2P {
private $merchantID = 'your_merchant_id';
private $secretKey = 'your_secret_key';
private $apiUrl = 'https://demo2.2c2p.com/'; // Sandbox URL

public function __construct() {
$this->client = new Client([)
'base_uri' => $this->apiUrl,
'headers' => [
'Content-Type' => 'application/json',
'Accept' => 'application/json'
]
]);
}
}

b) Create payment requests

public function createPayment($orderId, $amount, $currency, array $customerInfo) {
try {
// Prepare payload according to 2C2P API specs
$payload = [
"merchantID" => $this->merchantID,
"invoiceNo" => str_pad($orderId, 12, "0", STR_PAD_LEFT),
"description" => "Order Payment",
"amount" => number_format($amount, 2),
"currencyCode" => ($currency === "THB") ? "764" : "", // ISO numeric code for THB is 764
// Thailand specific parameters:
"paymentChannel" => ["CC", ""], // Credit Card and other available channels in Thailand
...$customerInfo,
];

// Generate HMAC signature as required by 2C2P
ksort($payload);
foreach ($payload as &$value) {
if (is_array($value)) continue;
if (is_bool($value)) {
continue;
} else {
trim((string)$value);
}
}

$_signatureData=implode("",array_values(array_filter($_requestPayload)));

$_hashSignature=hash_hmac('sha256',$_signatureData,$this->_secretKey);

$_requestPayload['signature']=$_hashSignature;

return json_encode($_requestPayload);

} catch (\Exception|\Throwable$exception){
throw new \RuntimeException(sprintf("%s:%s ",__METHOD__,$exception));
}
}

/
* @param string|int orderId - unique identifier for transaction
*/
public static async verifyTransaction(string|int$_orderReference=""):bool{
# Implementation per API docs...
return false;
}

7 . Handling callback notifications

Most Thai payment gateways send server-to-server (SERVER-to-SERVER/S-TO-S) notifications:


/
* :: Example callback handler for Omise webhook notifications
*/
function handleOmiseWebhook(){

file_put_contents(__DIR__." /... /logs/webhooks.log",
sprintf("[%s] %s\n",
date("Y-m-d H:i:s"),
print_r($_POST?????????????????????????????? [],true)),
FILE_APPEND).

try{

if(!isset($_SERVER["HTTP_X_SIGNATURE"])){
throw new \InvalidArgumentException("Missing X-Signature header");;
}

list(/*algo*/,/*timestamp*/,$expectedSig)=explode(",",trim(str_replace(["v1=", "t="],"",$_SERVER["HTTP_X_SIGNATURE"]));


/* Verify the signature using your endpoint secret */
/* See: https://www.omise.co/webhook-signatures */


}catch(\Throwable|\Exception$e){

http_response_code(400).

} finally{

exit();// Always terminate script after handling webhooks!

}
}

8 . Security Best Practices

1.Data validation:


function sanitizeThaiInput(string|null$_input=""):?string{

if(is_null($_input))return null;

$_cleaned=preg_replace("/[^ก-๙\w\-\. @ ]+/u","".

strip_tags(

htmlspecialchars_decode(

filter_var(trim((string)$input),

FILTER_UNSAFE_Raw.

["flags"=>FILTER_FLAG_NO_ENCODE_QUTES])

)

));

return (!empty(_cleaned)?mb_substr(_cleaneded,,255):null;

}

9 . Testing and debugging techniques

Analogue Response Tool:
Expose your local development environment to the Internet to receive webhooks using tools such as Ngrok.

Logging recommendations:

; php.ini settings for payment logging.
log_errors=On
error_log="/var/log/php/payment_error.log"

10 . Extended functionality implementation

a) Instalments (for Thai credit cards).

Add parameters to Omise or other APIs that support staging:

{"installment_term":3}   

b) PromptPay QR code generation.

composer require endroid/qr-code    

Then generate a QR code containing the PromptPay URI:

use Endroid\QrCode\QrCode;     
use Endroid\QrCode\Writer\PngWriter;

function generatePromptPayQR(float$amount,int|string$target){

/ Format per Thai banking standards */
promptpayUri=sprintf("00020101021129370016A000000677010111%s530376454%02d%s6304%s",...);

qrcode=new Qrcode(promptpayUri);

writer=new PngWriter();

result=$writer->write(qrcodE);

header ("Content-Type:"".result->getMimeType().""") ;

echo result-getString(); exit();

}

We hope this step-by-step guide will help you get your Thai payment integration up and running smoothly! Remember to conduct thorough sandbox testing before production deployment and consider hiring a professional Thai technical translator to check all user-facing prompts.