用PHP接入泰国支付网关的实例教程
# PHP接入泰国支付网关实例教程
1. 准备工作
在开始之前,您需要:
– 一个泰国支付网关的商户账户(如2C2P、Omise、TrueMoney等)
– PHP开发环境(建议PHP 7.0+)
– Composer依赖管理工具
– Web服务器(Apache/Nginx)
2. 安装必要的库
“`bash
composer require guzzlehttp/guzzle
“`
3. Omise支付网关集成示例
a) Omise初始化配置
“`php
client = new Client([
‘base_uri’ => $this->apiUrl,
‘auth’ => [$this->secretKey, ”]
]);
}
}
“`
b) 创建支付请求
“`php
public function createCharge($amount, $currency, $token) {
try {
$response = $this->client->post(‘/charges’, [
‘form_params’ => [
‘amount’ => intval($amount * 100), // Omise使用最小货币单位(分)
‘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生成前端代码示例(JavaScript)
“`javascript
// HTML中引入Omise.js库后:
“`
4. TrueMoney Wallet集成示例
a) API配置类
“`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码支付处理流程
“`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 [];
}
“`
注意:实际实现需参考TrueMoney最新API文档。
5 .常见问题解决
Q: SSL证书验证失败?
A: `curl_setopt($ch,CURLOPT_SSL_VERIFYPEER,FALSE);` (仅测试环境使用)
Q: HTTP响应状态码403?
A: IP白名单未设置或API密钥无效。检查商户后台IP限制设置。
—
以上是PHP接入泰国主流支付网关的基本框架。具体实现时请务必:
1. 仔细阅读所选网关的最新官方文档
2. 在生产环境中启用HTTPS和严格的数据验证
3.考虑添加日志记录所有交易请求和响应
根据您的业务需求,可能还需要处理退款、查询交易状态等功能。
PHP接入泰国支付网关实例教程(续)
6. 2C2P支付网关集成示例
a) 初始化配置
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) 创建支付请求
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 .处理回调通知
大多数泰国支付网关会发送服务器到服务器(SERVER-to-SERVER/S-TO-S)的通知:
/
* 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 .安全最佳实践
1.数据验证:
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 .测试与调试技巧
模拟响应工具:
使用Ngrok等工具将本地开发环境暴露给互联网以接收webhook。
日志记录建议:
; php.ini settings for payment logging:
log_errors=On
error_log="/var/log/php/payment_error.log"
10 .扩展功能实现
a)分期付款(适用于泰国信用卡):
在Omise或其它支持分期的API中添加参数:
{"installment_term":3}
b)PromptPay二维码生成:
composer require endroid/qr-code
然后生成包含PromptPay URI的QR码:
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();
}
希望这份进阶指南能帮助您顺利完成泰国支付集成!记得在生产部署前进行全面的沙盒测试,并考虑聘请专业泰语技术翻译核对所有面向用户的提示信息。