PHP code example of cable8mm / portone-php
1. Go to this page and download the library: Download cable8mm/portone-php library . Choose the download type require .
2. Extract the ZIP file and open the index.php.
3. Add this code to the index.php.
<?php
require_once('vendor/autoload.php');
/* Start to develop here. Best regards https://php-download.com/ */
cable8mm / portone-php example snippets
able8mm\PortonePhp\Client\PortOneClient;
$apiSecret = $config['apiSecret'];
$client = new PortOneClient($apiSecret);
$payment = $client->payment->getPayment($paymentId);
var_dump($payment->data);
$future = $client->payment->getPaymentsAsync([
'number' => 0,
'size' => 10,
]);
if (! $future->isComplete()) {
// 다른 애플리케이션 작업을 수행할 수 있습니다.
}
$payments = $future->wait();
$body = file_get_contents('php://input');
$headers = getallheaders();
$verifier = new \Cable8mm\PortonePhp\Webhook\WebhookVerifier($webhookSecret);
$webhook = $verifier->verify(
$body,
$headers['webhook-id'] ?? null,
$headers['webhook-signature'] ?? null,
$headers['webhook-timestamp'] ?? null,
);
if ($webhook instanceof \Cable8mm\PortonePhp\Webhook\WebhookTransaction) {
$paymentId = $webhook->data->paymentId;
}
use Cable8mm\PortonePhp\Webhook\WebhookSigner;
use Cable8mm\PortonePhp\Webhook\WebhookVerifier;
$signer = new WebhookSigner($webhookSecret);
// webhook-id, webhook-signature, webhook-timestamp 헤더를 반환합니다.
// msgId를 생략하면 "msg-{UUID}"를 만들고, timestamp를 생략하면 현재 시각을 씁니다.
$headers = $signer->headers($body);
$webhook = (new WebhookVerifier($webhookSecret))->verify(
$body,
$headers[WebhookVerifier::HEADER_ID],
$headers[WebhookVerifier::HEADER_SIGNATURE],
$headers[WebhookVerifier::HEADER_TIMESTAMP],
);
// webhook-signature 헤더 값("v1,<Base64 서명>")만 필요하면 sign()을 사용합니다.
$signature = $signer->sign('msg-example', time(), $body);
use Cable8mm\PortonePhp\Browser\BrowserPaymentRequest;
use Cable8mm\PortonePhp\Browser\RedirectResult;
use Cable8mm\PortonePhp\Client\PaymentClient;
// 1. 결제창에 넘길 값 만들기. redirectUrl은 필수이며 절대 http(s) URL이어야 합니다.
$request = new BrowserPaymentRequest(
storeId: $storeId,
channelKey: $channelKey,
paymentId: $paymentId, // 가맹점이 채번한 고유 ID
orderName: $orderName,
totalAmount: $totalAmount, // minor unit 정수 (KRW 1배, USD 100배)
redirectUrl: 'https://example.com/payment-redirect',
customerId: $customerId,
customerName: $customerName, // customer.fullName (KCP 영수증 조회의 구매자명)
payMethod: 'CARD',
currency: 'KRW',
forceRedirect: true, // PC·모바일 단일 리다이렉트 흐름
extra: ['customData' => ['item' => $itemId]], // 객체로 넘기면 그대로 저장됩니다
);
$parameters = $request->toArray(); // JSON으로 내려 브라우저에서 requestPayment(parameters) 호출
// 2. 리다이렉트 복귀 파싱. 실패 복귀는 PortOne에 묻지 않습니다.
$redirect = RedirectResult::fromQuery($_GET);
if ($redirect->isFailure()) {
// $redirect->code, $redirect->message, $redirect->pgCode, $redirect->pgMessage
}
if ($redirect->paymentId !== $paymentId) {
throw new RuntimeException('The redirect did not return the expected payment.');
}
// 3. lookup으로 상태와 금액을 대조합니다. null은 "정보 없음"이며 0으로 읽지 않습니다.
$payment = (new PaymentClient($apiSecret))->getPayment($redirect->paymentId);
if ($payment->variant !== 'PAID' || $payment->totalAmount() !== $totalAmount) {
throw new RuntimeException('The payment is not complete.');
}
$request = new BrowserPaymentRequest(
// ... 위와 같은 필수 값
payMethod: 'EASY_PAY',
easyPay: ['easyPayProvider' => 'KAKAOPAY', 'availablePayMethods' => ['CARD', 'MONEY']],
);
$receiptUrl = $payment->receiptUrl(); // string|null
use Cable8mm\PortonePhp\Browser\BillingKeyRedirectResult;
use Cable8mm\PortonePhp\Browser\BrowserBillingKeyRequest;
use Cable8mm\PortonePhp\Client\BillingKeyClient;
// 1. 발급창에 넘길 값 만들기. customerId는 customer.customerId로 들어갑니다.
$request = new BrowserBillingKeyRequest(
storeId: $storeId,
channelKey: $channelKey,
billingKeyMethod: 'CARD', // CARD, MOBILE, EASY_PAY, PAYPAL
issueId: $issueId, // 가맹점이 채번한 고유 ID
issueName: $issueName,
redirectUrl: 'https://example.com/billing-key-redirect',
customerId: $customerId,
forceRedirect: true,
// card: [...], easyPay: [...] // 발급 수단별 값은 그대로 전달됩니다
);
$parameters = $request->toArray(); // 브라우저에서 requestIssueBillingKey(parameters) 호출
// 2. 리다이렉트 복귀 파싱. 실패 복귀에 담긴 billingKey는 발급되지 않은 값이므로 billingKey는 null입니다.
$redirect = BillingKeyRedirectResult::fromQuery($_GET);
if ($redirect->isFailure()) {
// $redirect->code, $redirect->message, $redirect->pgCode, $redirect->pgMessage
return;
}
// 3. lookup으로 발급 상태를 확인한 뒤 빌링키를 서버에 저장합니다.
$info = (new BillingKeyClient($apiSecret))->getBillingKeyInfo($redirect->billingKey);
if ($info->variant !== 'ISSUED') {
throw new RuntimeException('The billing key is not issued.');
}
try {
$client->payInstantly(paymentId: $paymentId, ...);
} catch (TransportException $e) {
// SDK는 재시도하지 않음. getPayment로 상태를 확인합니다.
try {
$payment = $client->getPayment($paymentId);
if ($payment->variant === 'PAID') {
// 결제가 실제로 완료됨 → 취소하거나 완료 처리합니다.
}
} catch (UnknownException $getErr) {
if ($getErr->errorType === 'PAYMENT_NOT_FOUND') {
// 결제가 존재하지 않음 → 새로운 paymentId로 재시도할 수 있습니다.
}
}
}
try {
$client->payInstantly(paymentId: $sameId, ...);
} catch (UnknownException $e) {
if ($e->errorType === 'ALREADY_PAID') {
// 이미 결제 완료 — getPayment로 결제 상태를 확인합니다.
$payment = $client->getPayment($sameId);
}
}
sh
git clone https://github.com/cable8mm/portone-php.git
cd portone-php
composer install --no-interaction --prefer-dist
text
https://<ngrok-domain>/webhook-capture.php
sh
php tools/portone_webhook_probe.php
php tools/portone_boundary_probe.php
text
https://<ngrok-domain>/webhook-capture.php
sh
php tools/portone_payment_schedule_probe.php
sh
php tools/portone_payment_schedule_probe.php https://<ngrok-domain>/webhook-capture.php
text
POST /api/payment/webhook