태국 결제 게이트웨이 예제 튜토리얼에 대한 PHP 액세스

태국 결제 게이트웨이에 대한 # PHP 액세스 튜토리얼 예제

1. 준비 작업

시작하기 전에 먼저 해야 할 일이 있습니다:
- 태국 결제 게이트웨이가 있는 판매자 계정(예: 2C2P, Omise, TrueMoney 등)
- PHP 개발 환경(PHP 7.0 이상 권장)
- 컴포저 종속성 관리 도구
- 웹 서버(Apache/Nginx)

2. 필요한 라이브러리 설치

"`bash
작곡가 필요 GUZZLEHTTP/GUZZLE
“`

Omise 결제 게이트웨이 통합 예시 3.

a) Omise 초기화 구성

"`php
client = 새 클라이언트([
'base_uri' => $this->apiUrl,
'auth' => [$this->secretKey, "]
]);
}
}
“`

b) 결제 요청 생성

"`php
public function createCharge($amount, $currency, $token) {
시도 {
$response = $this->client->post('/charges', [ [
'form_params' => [
'amount' => intval($amount * 100), // Omise는 가장 작은 통화 단위(센트)를 사용합니다.
'currency' => strtolower($currency),
'카드' => 1TP4토큰.
// 필요한 경우 태국 특정 매개 변수
// …
]
]);

반환 json_decode($response->getBody(), true);

} catch (예외 $e) {
error_log('Omise 충전 오류: '.$e->getMessage()');
반환 ['error' => true];
}
}
“`

c) 토큰 생성 프런트엔드 코드 예시(자바스크립트)

"`javascript
// HTML에 Omise.js 라이브러리를 도입한 후.

“`

트루머니 월렛 통합 예시 4.

a) API 구성 클래스

"`php
트루머니월렛결제 클래스 {
private const BASE_URL_SANDBOX = "https://sandbox.truemoney.com/api/v1″;
private const BASE_URL_PRODUCTION = "https://tmn-prod.apigee.net/api/v1";

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

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

보호된 정적 배열 $_headers=[
"콘텐츠 유형"=>"application/json".
"수락"=>"application/json"
];

공용 정적 배열 $_requiredFields=["사용자 이름", "비밀번호"];

}
“`

b) QR코드 결제 처리 흐름

"`php
/
* @param float|int|string 금액 - 결제 금액(THB(฿))
* @param 문자열 merchantRef - 거래 추적을 위한 고유 참조 ID
*/
공용 정적 비동기 생성QRCode(
float|int|string amount=null ,
문자열 merchantRef="" ,
bool isSandBox=false):array{

try{

# 필수 필드 및 금액 유효성 검사...

# 트루머니 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)),
... # TMN 문서별 기타 필수 매개변수
];

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

반환 [];
}
“`
참고: 실제 구현에 대해서는 최신 TrueMoney API 설명서를 참조하세요.

5 . 일반적인 문제 해결

Q: SSL 인증서 유효성 검사에 실패했나요?
A: `curl_setopt($ch,CURLOPT_SSL_VERIFYPEER,FALSE);` (테스트 환경 전용)

질문: HTTP 응답 상태 코드 403은 무엇인가요?
A: IP 화이트리스트가 설정되지 않았거나 API 키가 유효하지 않습니다. 판매자 백엔드 IP 제한 설정을 확인하세요.

위는 태국의 주요 결제 게이트웨이에 대한 PHP 액세스의 기본 프레임워크입니다. 정확하게 구현하시기 바랍니다:

1. 선택한 게이트웨이의 최신 공식 문서를 주의 깊게 읽습니다.
2. 프로덕션 환경에서 HTTPS 및 엄격한 데이터 유효성 검사 활성화
3. 모든 트랜잭션 요청과 응답을 기록하기 위해 로그를 추가하는 것을 고려합니다.

비즈니스 요구 사항에 따라 환불 처리, 거래 상태 확인 및 기타 기능도 필요할 수 있습니다.

태국 결제 게이트웨이에 대한 PHP 액세스 예제 튜토리얼(계속)

6. 2C2P 결제 게이트웨이 통합 예시

a) 구성 초기화하기

클래스 Payment2C2P {
private $merchantID = 'your_merchant_id';
비공개 $secretKey = 'your_secret_key';
private $apiUrl = 'https://demo2.2c2p.com/'; // 샌드박스 URL

공용 함수 __construct() {
$this->client = 새 클라이언트([)
'base_uri' => $this->apiUrl,
'headers' => [
'콘텐츠 유형' => '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 . 콜백 알림 처리하기

대부분의 태국 결제 게이트웨이는 서버 대 서버(서버 간/S-TO-S) 알림을 전송합니다:


/
* :: Omise 웹훅 알림을 위한 콜백 핸들러 예시
*/
함수 handleOmiseWebhook(){

file_put_contents(__DIR__." /... /로그/웹훅스.로그",
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("누락된 X-서명 헤더");;
}

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


/* 엔드포인트 비밀을 사용하여 서명 확인 */
/* 참조: https://www.omise.co/webhook-signatures */


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

http_response_code(400).

} 마지막으로{

exit();// 웹훅 처리 후 항상 스크립트를 종료하세요!

}
}

8 . 보안 모범 사례

1.데이터 유효성 검사:


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

if(is_null($_input))은 null을 반환합니다;

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

strip_tags(

htmlspecialchars_decode(

filter_var(trim((문자열)$input),

FILTER_UNSAFE_Raw.

["flags"=>FILTER_FLAG_NO_ENCODE_QUTES])

)

));

반환 (!empty(_cleaned)?mb_substr(_cleaned,,255):null;

}

9 . 테스트 및 디버깅 기술

아날로그 응답 도구:
로컬 개발 환경을 인터넷에 노출하여 Ngrok과 같은 도구를 사용하여 웹훅을 수신하세요.

로깅 권장 사항:

결제 로깅을 위한 php.ini 설정.
로그 오류 = 켜짐
error_log="/var/log/php/payment_error.log"

10 . 확장 기능 구현

a) 할부(태국 신용 카드의 경우).

Omise 또는 스테이징을 지원하는 다른 API에 매개 변수를 추가하세요:

{"installment_term":3}   

b) PromptPay QR코드 생성.

작곡가에게 엔드로이드/QR 코드 필요    

그런 다음 PromptPay URI가 포함된 QR 코드를 생성합니다:

Endroid\QrCode\QrCode를 사용합니다;     
Endroid\QrCode\Writer\PngWriter를 사용합니다;

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

/ 태국 은행 표준에 따른 형식 */
promptpayUri=sprintf("00020101021129370016A000000677010111%s530376454%02d%s6304%s",...);

qrcode=새 Qrcode(promptpayUri);

writer=new PngWriter();

결과=$라이터->쓰기(qrcodE);

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

echo result-getString(); exit();

}

이 단계별 가이드가 태국 결제 통합을 원활하게 실행하는 데 도움이 되길 바랍니다. 프로덕션 배포 전에 샌드박스 테스트를 철저히 수행하고 태국어 전문 기술 번역사를 고용하여 모든 사용자 대면 프롬프트를 확인하는 것을 고려하세요.