v7.0.0 release

This commit is contained in:
HeuJung committed 2026-07-01 10:30:32 +09:00
1 parent 0e7fa04b03
commit c4ea9a6cd1
3582 files changed
+626189 -160151

No files matched your search

@@ -0,0 +1,210 @@
<?php
declare(strict_types=1);
namespace Plugins\Sirsoft\PayKginicis\Controllers;
use App\Helpers\ResponseHelper;
use App\Http\Controllers\Api\Base\AdminBaseController;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Plugins\Sirsoft\PayKginicis\Concerns\SanitizesPgResponse;
use Plugins\Sirsoft\PayKginicis\Services\KgInicisApiService;
/**
* KG 이니시스 현금영수증 별도발행 관리자 컨트롤러
*
* 메뉴얼: https://manual.inicis.com/pay/etc-receipt.html
*/
class AdminCashReceiptController extends AdminBaseController
{
use SanitizesPgResponse;
/** 현금영수증 발행 PG 응답 저장/반환 허용 필드 */
private const CASH_RECEIPT_RESPONSE_KEYS = [
'resultCode',
'resultMsg',
'tid',
'TID',
'cashReceiptNo',
'cashReceiptTid',
'applNum',
'applDate',
'applTime',
'mid',
'MID',
];
public function __construct(
private readonly KgInicisApiService $apiService,
) {
parent::__construct();
}
/**
* issue
*
* @param Request $request
* @param string $orderNumber
* @return JsonResponse
*/
public function issue(Request $request, string $orderNumber): JsonResponse
{
$issueType = (string) $request->input('issue_type', '0');
$issueNumber = trim((string) $request->input('issue_number', ''));
if (! in_array($issueType, ['0', '1'], true)) {
return ResponseHelper::error('messages.failed', 422, ['issue_type' => [__('sirsoft-pay_kginicis::messages.errors.cash_receipt_invalid_issue_type')]]);
}
if ($issueNumber === '') {
return ResponseHelper::error('messages.failed', 422, ['issue_number' => [__('sirsoft-pay_kginicis::messages.errors.cash_receipt_missing_issue_number')]]);
}
$payment = DB::table('ecommerce_order_payments as p')
->join('ecommerce_orders as o', 'o.id', '=', 'p.order_id')
->leftJoin('ecommerce_order_addresses as oa', function ($join) {
$join->on('oa.order_id', '=', 'o.id')
->where('oa.address_type', '=', 'shipping');
})
->where('o.order_number', $orderNumber)
->where('p.pg_provider', 'kginicis')
->whereNotNull('p.transaction_id')
->select([
'p.id',
'p.transaction_id',
'p.paid_amount_local',
'p.vat_amount',
'p.buyer_name',
'p.buyer_email',
'p.buyer_phone',
'p.payment_name',
'p.payment_meta',
'p.is_cash_receipt_issued',
'oa.orderer_name as address_orderer_name',
'oa.orderer_email as address_orderer_email',
'oa.orderer_phone as address_orderer_phone',
])
->first();
if (! $payment) {
return ResponseHelper::error('messages.failed', 404, null);
}
if ($payment->is_cash_receipt_issued) {
return ResponseHelper::error('messages.failed', 409, ['message' => [__('sirsoft-pay_kginicis::messages.errors.cash_receipt_already_issued')]]);
}
// 구매자 정보는 결제 테이블 → 주문 배송지 순서로 사용한다. PG raw 응답은
// 민감정보 최소화를 위해 구매자 연락처 fallback 에 사용하지 않는다.
$meta = $payment->payment_meta ? json_decode($payment->payment_meta, true) : [];
$rawResponse = $meta['pg_raw_response'] ?? [];
$buyerName = $payment->buyer_name ?? $payment->address_orderer_name ?? '';
$buyerEmail = $payment->buyer_email ?? $payment->address_orderer_email ?? '';
$buyerTel = $payment->buyer_phone ?? $payment->address_orderer_phone ?? '';
$goodName = $payment->payment_name ?? $rawResponse['goodName'] ?? $rawResponse['goodsName'] ?? __('sirsoft-pay_kginicis::messages.defaults.good_name');
$price = (int) round((float) $payment->paid_amount_local);
// 부가세: DB에 저장된 값 우선, 없으면 총액의 10/110 으로 계산
$vatAmount = (int) round((float) $payment->vat_amount);
if ($vatAmount <= 0) {
$vatAmount = (int) round($price / 11);
}
$supplyPrice = $price - $vatAmount;
Log::info('KG Inicis: cash receipt issue requested', [
'order_number' => $orderNumber,
'tid' => $payment->transaction_id,
'issue_type' => $issueType,
'price' => $price,
]);
try {
$pgResponse = $this->apiService->issueCashReceipt([
'issueType' => $issueType,
'issueNumber' => $issueNumber,
'price' => $price,
'supplyPrice' => $supplyPrice,
'tax' => $vatAmount,
'goodName' => $goodName,
'buyerName' => $buyerName,
'buyerEmail' => $buyerEmail,
'buyerTel' => $buyerTel,
]);
$resultCode = $pgResponse['resultCode'] ?? '';
if ($resultCode !== '00') {
Log::warning('KG Inicis: cash receipt issue failed', [
'order_number' => $orderNumber,
'result_code' => $resultCode,
'result_msg' => $pgResponse['resultMsg'] ?? '',
]);
return ResponseHelper::error('messages.failed', 502, [
'message' => [$pgResponse['resultMsg'] ?? __('sirsoft-pay_kginicis::messages.errors.cash_receipt_issue_failed')],
]);
}
$sanitizedPgResponse = $this->sanitizePgResponse($pgResponse, self::CASH_RECEIPT_RESPONSE_KEYS);
// DB 업데이트
DB::table('ecommerce_order_payments')
->where('id', $payment->id)
->update([
'is_cash_receipt_issued' => true,
'cash_receipt_type' => $issueType === '0' ? 'income_deduction' : 'expenditure_proof',
'cash_receipt_identifier' => $this->maskCashReceiptIdentifier($issueNumber),
'cash_receipt_issued_at' => now(),
'updated_at' => now(),
]);
Log::info('KG Inicis: cash receipt issued', [
'order_number' => $orderNumber,
'tid' => $payment->transaction_id,
'issue_type' => $issueType,
]);
return ResponseHelper::success('messages.success', [
'result_code' => $resultCode,
'result_msg' => $pgResponse['resultMsg'] ?? 'OK',
'pg_response' => $sanitizedPgResponse,
]);
} catch (\Exception $e) {
Log::error('KG Inicis: cash receipt issue exception', [
'order_number' => $orderNumber,
'error' => $e->getMessage(),
]);
return ResponseHelper::error('messages.failed', 500, [
'message' => [$e->getMessage()],
]);
}
}
/**
* 현금영수증 발행 식별번호를 저장용 마스킹 값으로 변환합니다.
*
* @param string $identifier PG 발행 요청에 사용한 원본 식별번호
* @return string 끝 4자리만 남긴 마스킹 값
*/
private function maskCashReceiptIdentifier(string $identifier): string
{
$digits = preg_replace('/\D+/', '', $identifier) ?? '';
if ($digits === '') {
return str_repeat('*', max(1, mb_strlen($identifier)));
}
$length = strlen($digits);
if ($length <= 4) {
return str_repeat('*', $length);
}
return str_repeat('*', $length - 4) . substr($digits, -4);
}
}
@@ -0,0 +1,206 @@
<?php
declare(strict_types=1);
namespace Plugins\Sirsoft\PayKginicis\Controllers;
use App\Helpers\ResponseHelper;
use App\Http\Controllers\Api\Base\AdminBaseController;
use Illuminate\Http\JsonResponse;
use Illuminate\Support\Facades\Log;
/**
* KG 이니시스 일본 결제 (DEVCBT, 테스트 모드) 호스트 연결 진단 컨트롤러
*
* 진단 대상:
* - devcbt.inicis.com (개발계 / 테스트 모드) — KG 이니시스가 별도로 머천트
* 서버 IP 를 화이트리스트 등록해야 접근 가능
*
* 운영계 cbt.inicis.com 은 IP 화이트리스트 제약이 없어 진단 대상에서 제외.
*
* 반환 정보:
* - 서버 egress IP (외부 통신 시 사용되는 IP, 화이트리스트 등록 대상)
* - DNS 해석 결과 + TCP 443 연결 가능 여부 (3초 timeout)
*
* 운영자가 KG 이니시스 측에 IP 등록 요청 시 어느 IP 를 알려줘야 하는지,
* 그리고 등록 후 실제로 통신이 가능해졌는지 확인하는 셀프 진단 도구.
*/
class AdminCbtConnectivityCheckController extends AdminBaseController
{
/** TCP 연결 timeout 초 — KG 이니시스 서버가 응답 안 하는 경우 화면 차단 방지 */
private const TCP_TIMEOUT_SECONDS = 3;
/** Egress IP 조회 외부 서비스 timeout */
private const EGRESS_LOOKUP_TIMEOUT = 3;
/**
* 진단 대상 호스트 목록 — devcbt 만 포함.
*
* cbt.inicis.com (운영계) 은 IP 화이트리스트 제약이 없어 화이트리스트
* 진단의 의미가 없음. 운영계 도달성은 일반 결제 흐름 자체로 검증됨.
*/
private const TARGET_HOSTS = [
['name' => 'devcbt.inicis.com', 'env' => 'test'],
];
/** Egress IP 조회용 외부 서비스 (순차 시도) */
private const EGRESS_LOOKUP_URLS = [
'https://api.ipify.org',
'https://ifconfig.me/ip',
'https://icanhazip.com',
];
/**
* 진단 실행 — 서버 IP + 호스트별 DNS / TCP 443 결과 반환
*
* @return JsonResponse
*/
public function check(): JsonResponse
{
try {
$egressIp = $this->detectEgressIp();
$serverIp = (string) ($_SERVER['SERVER_ADDR'] ?? '');
$hosts = [];
foreach (self::TARGET_HOSTS as $target) {
$hostname = $target['name'];
$dns = @gethostbyname($hostname);
$resolved = ($dns !== $hostname) ? $dns : null;
$tcpResult = $this->checkTcp443($hostname);
$hosts[] = [
'name' => $hostname,
'env' => $target['env'],
'dns_resolved_ip' => $resolved,
'tcp_443_reachable' => $tcpResult['reachable'],
'tcp_443_error' => $tcpResult['error'],
'tcp_443_latency_ms' => $tcpResult['latency_ms'],
];
}
return ResponseHelper::success(
'sirsoft-pay_kginicis::messages.cbt_connectivity.checked',
[
'egress_ip' => $egressIp,
'server_ip' => $serverIp,
'hosts' => $hosts,
'callback' => $this->buildCallbackDiagnostics(),
]
);
} catch (\Throwable $e) {
Log::error('KG Inicis CBT connectivity check failed', [
'message' => $e->getMessage(),
]);
return ResponseHelper::moduleError(
'sirsoft-pay_kginicis',
'messages.cbt_connectivity.check_failed',
500
);
}
}
/**
* 서버 egress IP 조회. 외부 echo 서비스를 순차 시도.
*
* @return string|null IP 또는 null (모든 서비스 실패 시)
*/
private function detectEgressIp(): ?string
{
foreach (self::EGRESS_LOOKUP_URLS as $url) {
$ip = $this->fetchEgressIpFrom($url);
if ($ip !== null) {
return $ip;
}
}
return null;
}
private function fetchEgressIpFrom(string $url): ?string
{
$ch = curl_init($url);
if ($ch === false) {
return null;
}
curl_setopt_array($ch, [
CURLOPT_RETURNTRANSFER => true,
CURLOPT_CONNECTTIMEOUT => self::EGRESS_LOOKUP_TIMEOUT,
CURLOPT_TIMEOUT => self::EGRESS_LOOKUP_TIMEOUT,
CURLOPT_FOLLOWLOCATION => false,
]);
$body = curl_exec($ch);
curl_close($ch);
if (! is_string($body)) {
return null;
}
$body = trim($body);
return filter_var($body, FILTER_VALIDATE_IP) !== false ? $body : null;
}
/**
* TCP 443 연결 가능 여부 확인.
*
* @return array{reachable: bool, error: ?string, latency_ms: ?int}
*/
private function checkTcp443(string $host): array
{
$start = microtime(true);
$errno = 0;
$errstr = '';
$fp = @fsockopen($host, 443, $errno, $errstr, self::TCP_TIMEOUT_SECONDS);
$latencyMs = (int) round((microtime(true) - $start) * 1000);
if ($fp === false) {
return [
'reachable' => false,
'error' => $errstr !== '' ? $errstr : 'connect failed',
'latency_ms' => $latencyMs,
];
}
fclose($fp);
return [
'reachable' => true,
'error' => null,
'latency_ms' => $latencyMs,
];
}
private function buildCallbackDiagnostics(): array
{
$appUrl = rtrim((string) config('app.url'), '/');
$callbackUrl = url('/plugins/sirsoft-pay_kginicis/payment/cbt/callback');
$appHost = parse_url($appUrl, PHP_URL_HOST);
$callbackHost = parse_url($callbackUrl, PHP_URL_HOST);
return [
'app_url' => $appUrl,
'callback_url' => $callbackUrl,
'app_url_https' => parse_url($appUrl, PHP_URL_SCHEME) === 'https',
'callback_url_https' => parse_url($callbackUrl, PHP_URL_SCHEME) === 'https',
'app_url_public' => $this->isPublicHostname(is_string($appHost) ? $appHost : ''),
'callback_url_public' => $this->isPublicHostname(is_string($callbackHost) ? $callbackHost : ''),
'host_matches_app_url' => $appHost !== null && $callbackHost !== null && $appHost === $callbackHost,
];
}
private function isPublicHostname(string $host): bool
{
$host = strtolower(trim($host));
if ($host === '' || $host === 'localhost') {
return false;
}
if (filter_var($host, FILTER_VALIDATE_IP) !== false) {
return filter_var(
$host,
FILTER_VALIDATE_IP,
FILTER_FLAG_NO_PRIV_RANGE | FILTER_FLAG_NO_RES_RANGE,
) !== false;
}
return ! str_ends_with($host, '.local');
}
}
@@ -0,0 +1,113 @@
<?php
declare(strict_types=1);
namespace Plugins\Sirsoft\PayKginicis\Controllers;
use App\Helpers\ResponseHelper;
use App\Http\Controllers\Api\Base\AdminBaseController;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Plugins\Sirsoft\PayKginicis\Services\CbtCvsOperationsService;
class AdminCbtCvsOperationsController extends AdminBaseController
{
public function __construct(
private readonly CbtCvsOperationsService $operationsService,
) {
parent::__construct();
}
/**
* CBT 편의점 입금 운영 요약을 조회합니다.
*
* @param string $orderNumber 주문번호
* @return JsonResponse 응답
*/
public function show(string $orderNumber): JsonResponse
{
$summary = $this->operationsService->summary($orderNumber);
if ($summary === null) {
return ResponseHelper::pluginError(
'sirsoft-pay_kginicis',
'messages.errors.order_not_found',
404,
);
}
return ResponseHelper::success('messages.success', $summary);
}
/**
* 테스트 모드 CBT 편의점 입금 완료 NOTI 를 시뮬레이션합니다.
*
* @param Request $request 요청
* @param string $orderNumber 주문번호
* @return JsonResponse 응답
*/
public function simulateNotify(Request $request, string $orderNumber): JsonResponse
{
$result = $this->operationsService->simulatePaidNotify($orderNumber, $request->ip());
if (! ($result['ok'] ?? false)) {
return $this->operationError($result);
}
return ResponseHelper::pluginSuccess(
'sirsoft-pay_kginicis',
'messages.cbt_cvs.simulate_success',
$result['summary'] ?? null,
);
}
/**
* 입금 기한이 지난 CBT 편의점 결제를 만료 처리합니다.
*
* @param string $orderNumber 주문번호
* @return JsonResponse 응답
*/
public function expire(string $orderNumber): JsonResponse
{
$result = $this->operationsService->expireOverdue($orderNumber);
if (! ($result['ok'] ?? false)) {
return $this->operationError($result);
}
return ResponseHelper::pluginSuccess(
'sirsoft-pay_kginicis',
'messages.cbt_cvs.expire_success',
$result['summary'] ?? null,
);
}
/**
* CBT 편의점 결제의 로컬 상태 재확인 시각을 기록합니다.
*
* @param string $orderNumber 주문번호
* @return JsonResponse 응답
*/
public function recheck(string $orderNumber): JsonResponse
{
$result = $this->operationsService->markRechecked($orderNumber);
if (! ($result['ok'] ?? false)) {
return $this->operationError($result);
}
return ResponseHelper::pluginSuccess(
'sirsoft-pay_kginicis',
'messages.cbt_cvs.recheck_success',
$result['summary'] ?? null,
);
}
private function operationError(array $result): JsonResponse
{
return ResponseHelper::pluginError(
'sirsoft-pay_kginicis',
(string) ($result['message_key'] ?? 'messages.errors.cbt_failed'),
(int) ($result['status'] ?? 422),
);
}
}
@@ -0,0 +1,120 @@
<?php
declare(strict_types=1);
namespace Plugins\Sirsoft\PayKginicis\Controllers;
use App\Helpers\ResponseHelper;
use App\Http\Controllers\Api\Base\AdminBaseController;
use Illuminate\Http\JsonResponse;
use Illuminate\Support\Facades\Log;
use Plugins\Sirsoft\PayKginicis\Services\CbtReconciliationService;
use Plugins\Sirsoft\PayKginicis\Services\KgInicisApiService;
class AdminCbtReconciliationController extends AdminBaseController
{
public function __construct(
private readonly CbtReconciliationService $reconciliationService,
private readonly KgInicisApiService $apiService,
) {
parent::__construct();
}
/**
* CBT 조정 레코드를 조회합니다.
*
* @param string $orderNumber 주문번호
* @return JsonResponse 조정 레코드 응답
*/
public function show(string $orderNumber): JsonResponse
{
return ResponseHelper::success('messages.success', $this->reconciliationService->get($orderNumber));
}
/**
* CBT 자동환불 재시도를 수행합니다.
*
* @param string $orderNumber 주문번호
* @return JsonResponse 재시도 결과 응답
*/
public function retryRefund(string $orderNumber): JsonResponse
{
$record = $this->reconciliationService->claimRefundRetry($orderNumber);
if (! $record) {
return ResponseHelper::pluginError(
'sirsoft-pay_kginicis',
'messages.cbt_reconciliation.not_retryable',
422,
);
}
$tid = (string) $record['tid'];
$amount = (int) ($record['amount'] ?? 0);
$retryCount = (int) ($record['retry_count'] ?? 0);
$reason = '관리자 CBT 자동환불 재시도';
try {
$this->apiService->useStoredCbtCredentials(
(bool) ($record['is_test_mode'] ?? true),
(string) ($record['cbt_mid'] ?? ''),
);
$refundResult = $this->apiService->refundCbtPayment($tid, null, $reason);
$updated = $this->reconciliationService->record($orderNumber, [
'status' => CbtReconciliationService::STATUS_AUTO_REFUNDED,
'manual_action_required' => false,
'tid' => $tid,
'amount' => $amount,
'reason' => (string) ($record['reason'] ?? ''),
'refund_error' => null,
'refund_result' => $this->sanitizeRefundResponse($refundResult),
'last_retry_at' => now()->toIso8601String(),
'last_retry_error' => null,
'retry_count' => $retryCount,
]);
return ResponseHelper::pluginSuccess(
'sirsoft-pay_kginicis',
'messages.cbt_reconciliation.retry_success',
$updated,
);
} catch (\Throwable $e) {
Log::error('KG Inicis CBT admin refund retry failed', [
'order_number' => $orderNumber,
'tid' => $tid,
'error' => $e->getMessage(),
]);
$this->reconciliationService->record($orderNumber, [
'status' => CbtReconciliationService::STATUS_MANUAL_REFUND_REQUIRED,
'manual_action_required' => true,
'tid' => $tid,
'amount' => $amount,
'refund_error' => $e->getMessage(),
'last_retry_at' => now()->toIso8601String(),
'last_retry_error' => $e->getMessage(),
'retry_count' => $retryCount,
]);
return ResponseHelper::pluginError(
'sirsoft-pay_kginicis',
'messages.cbt_reconciliation.retry_failed',
502,
);
}
}
private function sanitizeRefundResponse(array $response): array
{
return array_intersect_key($response, array_flip([
'resultCode',
'resultMsg',
'tid',
'cancelDate',
'cancelTime',
'prtcCode',
]));
}
}
@@ -0,0 +1,94 @@
<?php
declare(strict_types=1);
namespace Plugins\Sirsoft\PayKginicis\Controllers;
use App\Helpers\ResponseHelper;
use App\Http\Controllers\Api\Base\AdminBaseController;
use Illuminate\Http\JsonResponse;
use Illuminate\Support\Facades\Log;
use Modules\Sirsoft\Ecommerce\Services\ProductService;
/**
* KG 이니시스 CBT (일본 결제) 테스트용 상품 자동 생성 컨트롤러
*
* Japan 결제 (CBT, JPPG) 검증을 위해 JPY 가격이 설정된 샘플 상품을
* 한 번에 생성한다. 운영자가 admin 상품 폼에서 JPY 가격 필드를 일일이
* 채울 필요를 줄여 CBT 테스트 진입 장벽을 낮춘다.
*/
class AdminCbtTestProductController extends AdminBaseController
{
public function __construct(
private readonly ProductService $productService,
) {
parent::__construct();
}
/**
* CBT 테스트용 JPY 상품 생성
*
* @return JsonResponse 생성 결과 (성공 시 product_id / slug 반환)
*/
public function create(): JsonResponse
{
try {
$timestamp = now()->format('YmdHis');
$productCode = 'CBT-TEST-' . $timestamp;
// ProductService 가 currency_code 를 모듈 default_currency 로 자동 설정.
// 운영 환경의 default_currency 가 JPY 이면 selling_price 가 JPY 로 해석됨.
// name/description 은 AsUnicodeJson 캐스트 — 배열로 전달 (ko/en/ja 다국어)
// options 배열은 옵션 없는 상품도 default 1행 필수 — CartService 가 default option 을
// 못 찾으면 "존재하지 않는 옵션입니다" 예외를 던져 장바구니 담기가 실패한다.
$product = $this->productService->create([
'name' => [
'ko' => '[테스트] CBT 일본 결제',
'en' => '[Test] CBT Japan Payment',
'ja' => '[テスト] CBT 日本決済',
],
'product_code' => $productCode,
'sku' => 'KGINICIS-' . $productCode,
'selling_price' => 100, // 100엔 — CBT 테스트 최소 단위
'list_price' => 100,
'stock_quantity' => 9999,
'description' => [
'ko' => 'KG 이니시스 일본 결제(CBT, JPPG) 테스트 전용 상품입니다.',
'en' => 'KG Inicis Japan Payment (CBT, JPPG) test product.',
'ja' => 'KG イニシス 日本決済 (CBT, JPPG) テスト用商品です。',
],
'sales_status' => 'on_sale',
'display_status' => 'visible',
'options' => [
[
'option_code' => 'default',
'option_values' => [],
'option_name' => ['ko' => '기본', 'en' => 'Default', 'ja' => 'デフォルト'],
'stock_quantity' => 9999,
'is_default' => true,
'is_active' => true,
],
],
]);
Log::info('KG Inicis CBT: test product created', [
'product_id' => $product->id,
'product_code' => $product->product_code,
]);
return ResponseHelper::success('messages.success', [
'product_id' => $product->id,
'product_code' => $product->product_code,
'admin_url' => '/admin/ecommerce/products/' . $product->id . '/edit',
'shop_url' => '/shop/products/' . $product->id . '?locale=ja',
]);
} catch (\Throwable $e) {
Log::error('KG Inicis CBT: test product creation failed', [
'error' => $e->getMessage(),
'trace' => $e->getTraceAsString(),
]);
return ResponseHelper::error('messages.failed', 500, ['detail' => $e->getMessage()]);
}
}
}
@@ -0,0 +1,278 @@
<?php
declare(strict_types=1);
namespace Plugins\Sirsoft\PayKginicis\Controllers;
use App\Helpers\ResponseHelper;
use App\Http\Controllers\Api\Base\AdminBaseController;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Plugins\Sirsoft\PayKginicis\Concerns\SanitizesPgResponse;
use Plugins\Sirsoft\PayKginicis\Services\KgInicisApiService;
/**
* KG 이니시스 에스크로 배송등록 관리자 컨트롤러
*
* PC/모바일 공통 엔드포인트 사용 (INIAPI v1 /api/v1/escrow)
* 메뉴얼: https://manual.inicis.com/pay/escrow_pc.html#dlv
*/
class AdminEscrowDeliveryController extends AdminBaseController
{
use SanitizesPgResponse;
/** 택배사 코드 → 택배사명 매핑 (KG 이니시스 공식 코드표) */
private const COURIER_CODES = [
'hanjin' => '한진택배',
'cjgls' => 'CJ대한통운',
'loge' => '롯데택배',
'epost' => '우체국택배',
'lotte' => '롯데글로벌로지스',
'kdexp' => '경동택배',
'cvs' => '편의점택배',
'ilyang' => '일양로지스',
'chunil' => '천일택배',
'cvsnet' => 'CVSnet편의점',
'daesin' => '대신택배',
'kunyoung' => '건영택배',
'gsilogis' => 'GSI Express',
'etc' => '기타',
];
/** 에스크로 배송등록 PG 응답 저장 허용 필드 */
private const ESCROW_DELIVERY_RESPONSE_KEYS = [
'resultCode',
'resultMsg',
'tid',
'TID',
'oid',
'OID',
'mid',
'MID',
'type',
'report',
];
public function __construct(
private readonly KgInicisApiService $apiService,
) {
parent::__construct();
}
/**
* formData
*
* @param string $orderNumber
* @return JsonResponse
*/
public function formData(string $orderNumber): JsonResponse
{
$payment = $this->findEscrowPayment($orderNumber);
if (! $payment) {
return ResponseHelper::success('messages.success', null);
}
$address = DB::table('ecommerce_order_addresses as a')
->join('ecommerce_orders as o', 'o.id', '=', 'a.order_id')
->where('o.order_number', $orderNumber)
->where('a.address_type', 'shipping')
->select([
'a.recipient_name',
'a.recipient_phone',
'a.zipcode',
'a.address',
'a.address_detail',
])
->first();
// payment_meta에서 이력 추출
$meta = $payment->payment_meta ? json_decode($payment->payment_meta, true) : [];
$escrowDelivery = $meta['escrow_delivery'] ?? null;
$escrowConfirm = $meta['escrow_confirm'] ?? null;
$denyConfirmed = isset($meta['escrow_deny_confirm']);
return ResponseHelper::success('messages.success', [
'has_escrow_payment' => true,
'tid' => $payment->transaction_id,
'price' => (int) round((float) $payment->paid_amount_local),
'courier_codes' => self::COURIER_CODES,
'prefill' => [
'recvName' => $address?->recipient_name ?? '',
'recvTel' => $address?->recipient_phone ?? '',
'recvPost' => $address?->zipcode ?? '',
'recvAddr' => trim(($address?->address ?? '') . ' ' . ($address?->address_detail ?? '')),
],
'registered_delivery' => $escrowDelivery,
'escrow_confirm' => $escrowConfirm,
'deny_confirmed' => $denyConfirmed,
]);
}
/**
* register
*
* @param Request $request
* @param string $orderNumber
* @return JsonResponse
*/
public function register(Request $request, string $orderNumber): JsonResponse
{
$invoice = trim((string) $request->input('invoice', ''));
$exCode = trim((string) $request->input('ex_code', ''));
if ($invoice === '') {
return ResponseHelper::error('messages.failed', 422, ['invoice' => ['운송장번호를 입력해주세요.']]);
}
if ($exCode === '' || ! array_key_exists($exCode, self::COURIER_CODES)) {
return ResponseHelper::error('messages.failed', 422, ['ex_code' => ['택배사를 선택해주세요.']]);
}
$payment = $this->findEscrowPayment($orderNumber);
if (! $payment) {
return ResponseHelper::error('messages.failed', 404, null);
}
$report = in_array($request->input('report'), ['I', 'U'], true) ? $request->input('report') : 'I';
$charge = in_array($request->input('charge'), ['SH', 'BH'], true) ? $request->input('charge') : 'SH';
$price = (int) round((float) $payment->paid_amount_local);
$exName = self::COURIER_CODES[$exCode];
// 수신자 주소: 요청 우선, 없으면 DB 조회
$recvName = trim((string) $request->input('recv_name', ''));
$recvTel = trim((string) $request->input('recv_tel', ''));
$recvPost = trim((string) $request->input('recv_post', ''));
$recvAddr = trim((string) $request->input('recv_addr', ''));
if ($recvName === '' || $recvTel === '' || $recvAddr === '') {
$address = DB::table('ecommerce_order_addresses as a')
->join('ecommerce_orders as o', 'o.id', '=', 'a.order_id')
->where('o.order_number', $orderNumber)
->where('a.address_type', 'shipping')
->select(['a.recipient_name', 'a.recipient_phone', 'a.zipcode', 'a.address', 'a.address_detail'])
->first();
$recvName = $recvName ?: ($address?->recipient_name ?? '');
$recvTel = $recvTel ?: ($address?->recipient_phone ?? '');
$recvPost = $recvPost ?: ($address?->zipcode ?? '');
$recvAddr = $recvAddr ?: trim(($address?->address ?? '') . ' ' . ($address?->address_detail ?? ''));
}
Log::info('KG Inicis: escrow delivery register requested', [
'order_number' => $orderNumber,
'tid' => $payment->transaction_id,
'invoice' => $invoice,
'ex_code' => $exCode,
'report' => $report,
]);
try {
// 에스크로 결제는 반드시 에스크로 MID/키 사용
$this->apiService->useEscrowCredentials(true);
$pgResponse = $this->apiService->registerEscrowDelivery([
'tid' => $payment->transaction_id,
'oid' => $orderNumber,
'price' => $price,
'report' => $report,
'invoice' => $invoice,
'registName' => trim((string) $request->input('regist_name', '')),
'exCode' => $exCode,
'exName' => $exName,
'charge' => $charge,
'invoiceDay' => date('Y-m-d H:i:s'),
'sendName' => trim((string) $request->input('send_name', '')),
'sendTel' => trim((string) $request->input('send_tel', '')),
'sendPost' => trim((string) $request->input('send_post', '')),
'sendAddr1' => trim((string) $request->input('send_addr', '')),
'recvName' => $recvName,
'recvTel' => $recvTel,
'recvPost' => $recvPost,
'recvAddr' => $recvAddr,
]);
$resultCode = $pgResponse['resultCode'] ?? '';
$sanitizedPgResponse = $this->sanitizePgResponse($pgResponse, self::ESCROW_DELIVERY_RESPONSE_KEYS);
if ($resultCode !== '00') {
Log::warning('KG Inicis: escrow delivery register failed', [
'order_number' => $orderNumber,
'result_code' => $resultCode,
'result_msg' => $pgResponse['resultMsg'] ?? '',
'pg_response' => $sanitizedPgResponse,
]);
return ResponseHelper::error('messages.failed', 502, [
'message' => [$pgResponse['resultMsg'] ?? '배송등록에 실패했습니다.'],
]);
}
// payment_meta에 배송등록 정보 저장
$meta = $payment->payment_meta ? json_decode($payment->payment_meta, true) : [];
$meta['pg_response_sanitized'] = true;
$meta['escrow_delivery'] = [
'registered_at' => now()->toDateTimeString(),
'report' => $report,
'invoice' => $invoice,
'ex_code' => $exCode,
'ex_name' => $exName,
'charge' => $charge,
'recv_name' => $recvName,
'recv_addr' => $recvAddr,
'pg_response' => $sanitizedPgResponse,
];
DB::table('ecommerce_order_payments')
->where('id', $payment->id)
->update([
'payment_meta' => json_encode($meta, JSON_UNESCAPED_UNICODE),
'updated_at' => now(),
]);
Log::info('KG Inicis: escrow delivery registered', [
'order_number' => $orderNumber,
'tid' => $payment->transaction_id,
'invoice' => $invoice,
'ex_name' => $exName,
]);
return ResponseHelper::success('messages.success', [
'result_code' => $resultCode,
'result_msg' => $pgResponse['resultMsg'] ?? 'OK',
'invoice' => $invoice,
'ex_name' => $exName,
]);
} catch (\Exception $e) {
Log::error('KG Inicis: escrow delivery register exception', [
'order_number' => $orderNumber,
'error' => $e->getMessage(),
]);
return ResponseHelper::error('messages.failed', 500, [
'message' => [$e->getMessage()],
]);
}
}
private function findEscrowPayment(string $orderNumber): ?object
{
return DB::table('ecommerce_order_payments as p')
->join('ecommerce_orders as o', 'o.id', '=', 'p.order_id')
->where('o.order_number', $orderNumber)
->where('p.pg_provider', 'kginicis')
->where('p.is_escrow', true)
->whereNotNull('p.transaction_id')
->select([
'p.id',
'p.transaction_id',
'p.paid_amount_local',
'p.payment_meta',
])
->first();
}
}
@@ -0,0 +1,151 @@
<?php
declare(strict_types=1);
namespace Plugins\Sirsoft\PayKginicis\Controllers;
use App\Helpers\ResponseHelper;
use App\Http\Controllers\Api\Base\AdminBaseController;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Plugins\Sirsoft\PayKginicis\Concerns\SanitizesPgResponse;
use Plugins\Sirsoft\PayKginicis\Services\KgInicisApiService;
/**
* KG 이니시스 에스크로 구매거절확인 관리자 컨트롤러
*
* 구매자가 구매거절 선택 후 판매자(관리자)가 INIAPI v1 type=Dncf로 거절 확인 처리.
* 메뉴얼: https://manual.inicis.com/pay/escrow_pc.html#dncf
*/
class AdminEscrowDenyConfirmController extends AdminBaseController
{
use SanitizesPgResponse;
/** 에스크로 구매거절확인 PG 응답 저장 허용 필드 */
private const ESCROW_DENY_CONFIRM_RESPONSE_KEYS = [
'resultCode',
'resultMsg',
'tid',
'TID',
'originalTid',
'mid',
'MID',
'type',
];
public function __construct(
private readonly KgInicisApiService $apiService,
) {
parent::__construct();
}
/**
* confirm
*
* @param Request $request
* @param string $orderNumber
* @return JsonResponse
*/
public function confirm(Request $request, string $orderNumber): JsonResponse
{
$payment = $this->findEscrowPayment($orderNumber);
if (! $payment) {
return ResponseHelper::error('messages.failed', 404, null);
}
$meta = $payment->payment_meta ? json_decode($payment->payment_meta, true) : [];
// 이미 구매거절확인 완료된 경우
if (isset($meta['escrow_deny_confirm'])) {
return ResponseHelper::error('messages.failed', 422, [
'message' => ['이미 구매거절확인이 완료되었습니다.'],
]);
}
$dcnfName = trim((string) $request->input('dcnf_name', '관리자'));
Log::info('KG Inicis: escrow deny confirm requested', [
'order_number' => $orderNumber,
'tid' => $payment->transaction_id,
]);
try {
$this->apiService->useEscrowCredentials(true);
$pgResponse = $this->apiService->denyConfirmEscrow([
'originalTid' => $payment->transaction_id,
'dcnfName' => $dcnfName,
]);
$resultCode = $pgResponse['resultCode'] ?? '';
$sanitizedPgResponse = $this->sanitizePgResponse($pgResponse, self::ESCROW_DENY_CONFIRM_RESPONSE_KEYS);
if ($resultCode !== '00') {
Log::warning('KG Inicis: escrow deny confirm failed', [
'order_number' => $orderNumber,
'result_code' => $resultCode,
'result_msg' => $pgResponse['resultMsg'] ?? '',
'pg_response' => $sanitizedPgResponse,
]);
return ResponseHelper::error('messages.failed', 502, [
'message' => [$pgResponse['resultMsg'] ?? '구매거절확인에 실패했습니다.'],
]);
}
// payment_meta에 구매거절확인 이력 저장
$meta['pg_response_sanitized'] = true;
$meta['escrow_deny_confirm'] = [
'confirmed_at' => now()->toDateTimeString(),
'dcnf_name' => $dcnfName,
'pg_response' => $sanitizedPgResponse,
];
DB::table('ecommerce_order_payments')
->where('id', $payment->id)
->update([
'payment_meta' => json_encode($meta, JSON_UNESCAPED_UNICODE),
'updated_at' => now(),
]);
Log::info('KG Inicis: escrow deny confirm completed', [
'order_number' => $orderNumber,
'tid' => $payment->transaction_id,
]);
return ResponseHelper::success('messages.success', [
'result_code' => $resultCode,
'result_msg' => $pgResponse['resultMsg'] ?? 'OK',
]);
} catch (\Exception $e) {
Log::error('KG Inicis: escrow deny confirm exception', [
'order_number' => $orderNumber,
'error' => $e->getMessage(),
]);
return ResponseHelper::error('messages.failed', 500, [
'message' => [$e->getMessage()],
]);
}
}
private function findEscrowPayment(string $orderNumber): ?object
{
return DB::table('ecommerce_order_payments as p')
->join('ecommerce_orders as o', 'o.id', '=', 'p.order_id')
->where('o.order_number', $orderNumber)
->where('p.pg_provider', 'kginicis')
->where('p.is_escrow', true)
->whereNotNull('p.transaction_id')
->select([
'p.id',
'p.transaction_id',
'p.payment_meta',
])
->first();
}
}
@@ -0,0 +1,88 @@
<?php
declare(strict_types=1);
namespace Plugins\Sirsoft\PayKginicis\Controllers;
use App\Helpers\ResponseHelper;
use App\Http\Controllers\Api\Base\AdminBaseController;
use Illuminate\Http\JsonResponse;
use Illuminate\Support\Facades\DB;
class AdminOrderListController extends AdminBaseController
{
public function __construct()
{
parent::__construct();
}
/**
* KG 이니시스 테스트 모드 주문 맵 반환
*
* 최근 6 개월 이내 kginicis 결제 주문 중 테스트 결제 건을 { "order_number": true, ... }
* 형태로 반환한다. 어드민 주문 목록의 결제수단 셀 하단에 "(테스트 결제)" 배지를 표시할
* 때 사용한다.
*
* 판별 우선순위:
* 1) payment_meta.is_test_mode === true (콜백에서 저장된 경우)
* 2) transaction_id 에 "Test" 문자열 포함 (KG 이니시스 테스트 TID 패턴)
*
* @return JsonResponse 테스트 모드 주문 맵
*/
public function testModeMap(): JsonResponse
{
$rows = DB::table('ecommerce_orders as o')
->join('ecommerce_order_payments as p', 'p.order_id', '=', 'o.id')
->where('p.pg_provider', 'kginicis')
->where('p.created_at', '>=', now()->subMonths(6))
->select(['o.order_number', 'p.transaction_id', 'p.payment_meta'])
->get();
$map = [];
foreach ($rows as $row) {
if ($this->isTestPayment($row->transaction_id, $row->payment_meta)) {
$map[$row->order_number] = true;
}
}
return ResponseHelper::success('messages.success', $map);
}
/**
* 결제 건이 테스트 모드 결제인지 판별
*
* 판별 우선순위:
* 1) payment_meta.is_test_mode === true (콜백에서 명시 저장된 경우)
* 2) payment_meta.pg_raw_response.mid 가 'SIR' prefix 가 아님
* → KG 이니시스 Live MID 는 항상 'SIR' prefix. test MID 는 INIpayTest/iniescrow0 등
* 3) transaction_id 에 "Test" 문자열 포함 (구식 보조 패턴)
*
* @param string|null $transactionId KG 이니시스 TID
* @param string|null $paymentMeta payment_meta JSON 문자열
* @return bool 테스트 결제 여부
*/
private function isTestPayment(?string $transactionId, ?string $paymentMeta): bool
{
if ($paymentMeta !== null && $paymentMeta !== '') {
$meta = json_decode($paymentMeta, true) ?? [];
if (isset($meta['is_test_mode']) && $meta['is_test_mode'] === true) {
return true;
}
$raw = $meta['pg_raw_response'] ?? [];
if (is_array($raw)) {
$mid = (string) ($raw['mid'] ?? $raw['MID'] ?? '');
if ($mid !== '' && ! str_starts_with($mid, 'SIR')) {
return true;
}
}
}
if ($transactionId !== null && $transactionId !== '' && stripos($transactionId, 'Test') !== false) {
return true;
}
return false;
}
}
@@ -0,0 +1,699 @@
<?php
declare(strict_types=1);
namespace Plugins\Sirsoft\PayKginicis\Controllers;
use App\Helpers\ResponseHelper;
use App\Http\Controllers\Api\Base\AdminBaseController;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Plugins\Sirsoft\PayKginicis\Services\KgInicisApiService;
class AdminTransactionController extends AdminBaseController
{
public function __construct(
private readonly KgInicisApiService $apiService,
) {
parent::__construct();
}
/**
* TID 직접 조회
*
* @param Request $request
* @return JsonResponse
*/
public function query(Request $request): JsonResponse
{
$tid = trim((string) $request->input('tid', ''));
if ($tid === '') {
return ResponseHelper::error('messages.failed', 422, ['tid' => ['TID를 입력하세요.']]);
}
return $this->queryByTid($tid);
}
/**
* 주문번호로 거래 조회
*
* @param string $orderNumber
* @return JsonResponse
*/
public function queryByOrder(string $orderNumber): JsonResponse
{
$payment = DB::table('ecommerce_order_payments')
->join('ecommerce_orders', 'ecommerce_orders.id', '=', 'ecommerce_order_payments.order_id')
->where('ecommerce_orders.order_number', $orderNumber)
->whereNotNull('ecommerce_order_payments.transaction_id')
->where('ecommerce_order_payments.transaction_id', '!=', '')
->where('ecommerce_order_payments.pg_provider', 'kginicis')
->select(['ecommerce_order_payments.transaction_id', 'ecommerce_order_payments.payment_meta'])
->first();
if (! $payment) {
return ResponseHelper::success('messages.success', null);
}
return $this->queryByTid($payment->transaction_id);
}
private function queryByTid(string $tid): JsonResponse
{
try {
$localPayment = DB::table('ecommerce_order_payments')
->leftJoin('ecommerce_orders', 'ecommerce_orders.id', '=', 'ecommerce_order_payments.order_id')
->where('ecommerce_order_payments.transaction_id', $tid)
->select([
'ecommerce_order_payments.transaction_id',
'ecommerce_order_payments.payment_status',
'ecommerce_order_payments.is_escrow',
'ecommerce_order_payments.payment_meta',
'ecommerce_order_payments.embedded_pg_provider',
'ecommerce_order_payments.paid_amount_local',
'ecommerce_order_payments.currency',
'ecommerce_order_payments.card_name',
'ecommerce_order_payments.card_number_masked',
'ecommerce_order_payments.card_approval_number',
'ecommerce_order_payments.card_installment_months',
'ecommerce_order_payments.vbank_code',
'ecommerce_order_payments.vbank_name',
'ecommerce_order_payments.vbank_number',
'ecommerce_order_payments.vbank_holder',
'ecommerce_order_payments.vbank_due_at',
'ecommerce_order_payments.buyer_name',
'ecommerce_order_payments.buyer_email',
'ecommerce_order_payments.buyer_phone',
'ecommerce_order_payments.payment_name',
'ecommerce_order_payments.paid_at',
'ecommerce_orders.order_number',
'ecommerce_orders.order_status',
'ecommerce_orders.currency as order_currency',
'ecommerce_orders.total_due_amount',
])
->first();
$localMeta = [];
$localRaw = [];
if ($localPayment?->payment_meta) {
$localMeta = json_decode($localPayment->payment_meta, true) ?: [];
$localRaw = $localMeta['pg_raw_response'] ?? [];
}
$localRaw = $this->mergeLocalPaymentFallback($localRaw, $localPayment);
$paymentMid = $this->resolvePaymentMid($localMeta, $localRaw, $tid);
$embeddedPgProvider = $localPayment?->embedded_pg_provider
?: ($localMeta['embedded_pg_provider'] ?? null);
if ($this->isCbtLocalPayment($localPayment, $localMeta, $localRaw, $tid)) {
$result = $this->buildLocalCbtTransactionResult(
$tid,
$localPayment,
$localMeta,
$localRaw,
is_string($embeddedPgProvider) ? $embeddedPgProvider : null,
);
return ResponseHelper::success('messages.success', $result);
}
// 결제 시점 모드(payment_meta.is_test_mode) 가 있으면 그 모드의 inapi 자격증명으로 조회.
// 누락 시 MID prefix 로 추정 ('SIR' = live, 그 외 = test).
if ($paymentMid !== null) {
$isTestMode = $localMeta['is_test_mode']
?? ! str_starts_with($paymentMid, 'SIR');
$this->apiService->useStoredCredentials((bool) $isTestMode, $paymentMid);
} else {
$this->apiService->useEscrowCredentials((bool) ($localPayment?->is_escrow ?? false));
}
$result = $this->apiService->queryTransaction($tid, $paymentMid);
$result = $this->enrichResult(
$result,
$localRaw,
(bool) ($localPayment?->is_escrow ?? false),
$localPayment?->vbank_due_at,
is_string($embeddedPgProvider) ? $embeddedPgProvider : null,
);
return ResponseHelper::success('messages.success', $result);
} catch (\Exception $e) {
Log::error('KG Inicis queryTransaction failed', [
'tid' => $tid,
'error' => $e->getMessage(),
]);
return ResponseHelper::error('messages.failed', 502, null);
}
}
/**
* 결제 시점에 사용된 가맹점 ID(MID) 를 해결한다.
*
* 해결 우선순위:
* 1) payment_meta.mid (콜백에서 명시 저장된 MID — 신규 주문 표준 경로)
* 2) payment_meta.pg_raw_response.mid 또는 .MID (예전 콜백 응답 raw 값)
* 3) TID 의 char 10–20 추출 (KG 이니시스 TID 포맷: prefix(10) + MID(10) + timestamp/seq)
* 4) null 반환 → 호출자가 fallback 으로 현재 설정 MID 사용
*
* @param array $localMeta payment_meta 전체
* @param array $localRaw payment_meta.pg_raw_response
* @param string $tid 거래번호
* @return string|null 해결된 MID 또는 null
*/
private function resolvePaymentMid(array $localMeta, array $localRaw, string $tid): ?string
{
if (! empty($localMeta['mid']) && is_string($localMeta['mid'])) {
return $localMeta['mid'];
}
foreach (['mid', 'MID'] as $key) {
if (! empty($localRaw[$key]) && is_string($localRaw[$key])) {
return $localRaw[$key];
}
}
// KG 이니시스 TID 포맷: 10자 prefix (INIMX_CARD / StdpayCARD / ININPGVBNK 등)
// + 10자 MID + timestamp/sequence.
if (strlen($tid) >= 20) {
$candidate = substr($tid, 10, 10);
// MID 후보 검증: 영숫자만 (KG 이니시스 MID 명세)
if (preg_match('/^[A-Za-z0-9]{10}$/', $candidate) === 1) {
return $candidate;
}
}
return null;
}
private function mergeLocalPaymentFallback(array $localRaw, mixed $localPayment): array
{
if (! $localPayment) {
return $localRaw;
}
$fallbacks = [
'approvedAmount' => $localPayment->paid_amount_local ?? null,
'currency' => $localPayment->currency ?? null,
'applNum' => $localPayment->card_approval_number ?? null,
'cardName' => $localPayment->card_name ?? null,
'cardNum' => $localPayment->card_number_masked ?? null,
'cardQuota' => $localPayment->card_installment_months ?? null,
'VACT_BankCode' => $localPayment->vbank_code ?? null,
'VACT_BankName' => $localPayment->vbank_name ?? null,
'VACT_Num' => $localPayment->vbank_number ?? null,
'VACT_Name' => $localPayment->vbank_holder ?? null,
'buyerName' => $localPayment->buyer_name ?? null,
'buyerEmail' => $localPayment->buyer_email ?? null,
'buyerTel' => $localPayment->buyer_phone ?? null,
'goodName' => $localPayment->payment_name ?? null,
];
foreach ($fallbacks as $key => $value) {
if (($localRaw[$key] ?? null) === null && $value !== null && $value !== '') {
$localRaw[$key] = $value;
}
}
return $localRaw;
}
private function isCbtLocalPayment(mixed $localPayment, array $localMeta, array $localRaw, string $tid): bool
{
if (($localMeta['is_cbt'] ?? false) === true || ($localMeta['cbt_type'] ?? '') !== '') {
return true;
}
if (str_starts_with($tid, 'INIJPG')) {
return true;
}
$currency = strtoupper((string) (
$localMeta['currency']
?? $localRaw['currencyCd']
?? $localRaw['currency']
?? $localPayment?->currency
?? $localPayment?->order_currency
?? ''
));
return $currency === 'JPY' && str_starts_with($tid, 'INIJPG');
}
private function buildLocalCbtTransactionResult(
string $tid,
mixed $localPayment,
array $localMeta,
array $localRaw,
?string $embeddedPgProvider,
): array {
$pick = function (string ...$keys) use ($localMeta, $localRaw, $localPayment): ?string {
foreach ($keys as $key) {
if (isset($localRaw[$key]) && $localRaw[$key] !== '') {
return (string) $localRaw[$key];
}
if (isset($localMeta[$key]) && $localMeta[$key] !== '') {
return (string) $localMeta[$key];
}
}
$fallbacks = [
'tid' => $localPayment?->transaction_id ?? null,
'order_number' => $localPayment?->order_number ?? null,
'payment_status' => $localPayment?->payment_status ?? null,
'paid_amount_local' => $localPayment?->paid_amount_local ?? null,
'currency' => $localPayment?->currency ?? $localPayment?->order_currency ?? null,
'paid_at' => $localPayment?->paid_at ?? null,
];
foreach ($keys as $key) {
if (isset($fallbacks[$key]) && $fallbacks[$key] !== '') {
return (string) $fallbacks[$key];
}
}
return null;
};
$payMethod = $this->normalizeCbtPayMethod($pick('pay_method', 'paymethod', 'payMethod') ?? '');
$basePayMethodLabel = $this->payMethodLabel($payMethod);
$embeddedPgProviderLabel = $this->embeddedPgProviderLabel($embeddedPgProvider);
$currency = strtoupper($pick('currencyCd', 'currencyCode', 'currency') ?? 'JPY');
$result = [
'resultCode' => $pick('resultCode', 'result_code', 'code') ?? 'LOCAL_CBT',
'resultMsg' => $pick('resultMsg', 'message') ?? 'CBT 거래는 로컬 결제 확인 정보로 표시됩니다.',
'tid' => $tid,
'_is_cbt' => true,
'_is_local_confirmation' => true,
'_is_test_mode' => (bool) ($localMeta['is_test_mode'] ?? $this->apiService->isTestMode()),
'_local_is_escrow' => (bool) ($localPayment?->is_escrow ?? false),
'_pay_method' => $payMethod,
'_base_pay_method_label' => $basePayMethodLabel,
'_embedded_pg_provider' => $embeddedPgProvider,
'_embedded_pg_provider_label' => $embeddedPgProviderLabel,
'_pay_method_label' => $embeddedPgProviderLabel
? $embeddedPgProviderLabel . ' (' . $basePayMethodLabel . ')'
: $basePayMethodLabel,
'_auth_code' => $pick('approve', 'applNo', 'approvalNo', 'authCode', 'confNo', 'receiptNo'),
'_auth_date' => $this->formatCbtDateTime(
$pick('auth_date', 'applDate', 'applDt'),
$pick('applTime', 'applTm'),
) ?? $this->formatTimestamp((string) ($localPayment?->paid_at ?? '')),
'_total_price' => $pick('amount', 'price', 'cvs_amount', 'paid_amount_local'),
'_currency' => $currency !== '' ? $currency : 'JPY',
'_moid' => $pick('orderId', 'orderID', 'oid', 'order_number'),
'_buyer_name' => $pick('buyerName', 'buyer_name'),
'_buyer_email' => $pick('buyerEmail', 'buyer_email'),
'_buyer_tel' => $pick('buyerTel', 'buyer_phone'),
'_status' => $pick('payment_status', 'cvs_status', 'status'),
'_cancel_price' => $pick('cancelPrice', 'cancel_price'),
'_cancel_date' => $this->formatCbtDateTime($pick('cancelDate'), $pick('cancelTime')),
'_part_cancel_list' => $this->normalizePartCancelList(is_array($localRaw['partCancelList'] ?? null) ? $localRaw['partCancelList'] : []),
'_card_name' => $pick('cardName', 'card_name'),
'_card_num' => $pick('cardNum', 'card_number_masked'),
'_card_code' => $pick('cardCode'),
'_card_quota' => $this->formatQuota($pick('installMonth', 'cardQuota', 'card_installment_months')),
'_card_interest' => null,
'_vbank_num' => $pick('confNo', 'receiptNo', 'vbank_number'),
'_vbank_bank_code' => $pick('convenience', 'vbank_code'),
'_vbank_bank_name' => $pick('vbank_name') ?? ($payMethod === 'CVS' ? 'CVS' : null),
'_vbank_holder' => $pick('vbank_holder'),
'_vbank_expire_date' => $this->formatCompactDateTime($pick('paymentTerm', 'cvs_payment_term'))
?? $this->formatTimestamp((string) ($localPayment?->vbank_due_at ?? '')),
'_vbank_status' => $pick('cvs_status'),
'_vbank_paid_at' => $this->formatCbtDateTime($pick('applDt'), $pick('applTm')),
'_bank_code' => null,
'_bank_name' => null,
'_bank_acnt_num' => null,
'_hpp_num' => null,
'_hpp_corp' => null,
'_escrow_status' => null,
'_escrow_confirm' => null,
'_inquiry_at' => date('Y-m-d H:i:s'),
'_local_notice' => 'CBT 거래는 한국 INIAPI 거래조회 대상이 아니므로 저장된 승인/입금 확인 정보로 표시됩니다.',
'_cbt_cvs' => $payMethod === 'CVS' ? [
'status' => (string) ($localMeta['cvs_status'] ?? ''),
'last_notify_at' => (string) ($localMeta['cvs_last_notify_at'] ?? ''),
'last_notify_result' => (string) ($localMeta['cvs_last_notify_result'] ?? ''),
'last_notify_reason' => (string) ($localMeta['cvs_last_notify_reason'] ?? ''),
'last_recheck_at' => (string) ($localMeta['cvs_last_recheck_at'] ?? ''),
'last_recheck_result' => (string) ($localMeta['cvs_last_recheck_result'] ?? ''),
'expired_at' => (string) ($localMeta['cvs_expired_at'] ?? ''),
'expiry_reason' => (string) ($localMeta['cvs_expiry_reason'] ?? ''),
'notify_history' => is_array($localMeta['cvs_notify_history'] ?? null)
? array_slice($localMeta['cvs_notify_history'], 0, 10)
: [],
] : null,
];
return $result;
}
private function normalizeCbtPayMethod(string $code): string
{
return strtoupper(trim($code));
}
private function formatCbtDateTime(?string $date, ?string $time): ?string
{
if ($date === null || $date === '') {
return null;
}
if (strlen($date) === 14 && preg_match('/^\d{14}$/', $date) === 1) {
return $this->formatCompactDateTime($date);
}
return $this->formatDateTime($date, $time);
}
private function formatCompactDateTime(?string $value): ?string
{
if ($value === null || preg_match('/^\d{14}$/', $value) !== 1) {
return null;
}
return substr($value, 0, 4) . '-'
. substr($value, 4, 2) . '-'
. substr($value, 6, 2) . ' '
. substr($value, 8, 2) . ':'
. substr($value, 10, 2) . ':'
. substr($value, 12, 2);
}
private function formatTimestamp(string $value): ?string
{
if ($value === '') {
return null;
}
try {
return \Carbon\Carbon::parse($value)->format('Y-m-d H:i:s');
} catch (\Throwable) {
return null;
}
}
/**
* inquiry 응답을 화면 표시용 필드로 보강한다.
*
* 우선순위: inquiry 응답값 → 로컬 콜백 응답 fallback → null
*
* @param array $result inquiry API 응답
* @param array $localRaw 결제 콜백 시 저장한 raw 응답
* @param bool $isEscrow 로컬 결제 레코드의 에스크로 여부
* @param string|null $localVbankDueAt 로컬 DB 의 vbank_due_at (정확한 cutoff timestamp)
* @return array 보강된 응답
*/
private function enrichResult(
array $result,
array $localRaw,
bool $isEscrow,
?string $localVbankDueAt = null,
?string $embeddedPgProvider = null,
): array
{
$cardInfo = is_array($result['cardInfo'] ?? null) ? $result['cardInfo'] : [];
$pick = function (string ...$keys) use ($result, $localRaw, $cardInfo): ?string {
foreach ($keys as $key) {
if (isset($result[$key]) && $result[$key] !== '') {
return (string) $result[$key];
}
if (isset($cardInfo[$key]) && $cardInfo[$key] !== '') {
return (string) $cardInfo[$key];
}
}
foreach ($keys as $key) {
if (isset($localRaw[$key]) && $localRaw[$key] !== '') {
return (string) $localRaw[$key];
}
}
return null;
};
$payMethod = $pick('payMethod', 'PayMethod', 'paymethod') ?? '';
$basePayMethodLabel = $this->payMethodLabel($payMethod);
$embeddedPgProviderLabel = $this->embeddedPgProviderLabel($embeddedPgProvider);
$result['_is_test_mode'] = $this->apiService->isTestMode();
$result['_local_is_escrow'] = $isEscrow;
$result['_pay_method'] = $payMethod;
$result['_base_pay_method_label'] = $basePayMethodLabel;
$result['_embedded_pg_provider'] = $embeddedPgProvider;
$result['_embedded_pg_provider_label'] = $embeddedPgProviderLabel;
$result['_pay_method_label'] = $embeddedPgProviderLabel
? $embeddedPgProviderLabel.' ('.$basePayMethodLabel.')'
: $basePayMethodLabel;
$result['_auth_code'] = $pick('applNum', 'approvedNumber', 'authCode', 'AuthCode');
$result['_auth_date'] = $this->formatDateTime(
$pick('applDate', 'approvedDate', 'AuthDate'),
$pick('applTime', 'approvedTime', 'AuthTime'),
);
$result['_total_price'] = $pick('TotPrice', 'totalPrice', 'price', 'Amt', 'approvedAmount');
$result['_currency'] = $pick('currency', 'Currency', 'currencyCode') ?? 'WON';
$result['_moid'] = $pick('MOID', 'moid', 'Moid', 'oid');
$result['_buyer_name'] = $pick('buyerName', 'BuyerName');
$result['_buyer_email'] = $pick('buyerEmail', 'BuyerEmail', 'buyerMail');
$result['_buyer_tel'] = $pick('buyerTel', 'BuyerTel');
$result['_status'] = $pick('status', 'Status', 'transactionStatus');
// 취소이력
$result['_cancel_price'] = $pick('cancelPrice', 'CancelPrice', 'cancelAmount');
$result['_cancel_date'] = $this->formatDateTime($pick('cancelDate', 'CancelDate'), $pick('cancelTime', 'CancelTime'));
$partCancelRaw = $result['partCancelList'] ?? $localRaw['partCancelList'] ?? [];
$result['_part_cancel_list'] = $this->normalizePartCancelList(is_array($partCancelRaw) ? $partCancelRaw : []);
// 결제수단별 상세 (신구 응답 포맷 호환: 평탄 키 + cardInfo 중첩)
$result['_card_name'] = $pick('cardName', 'CardName', 'issuerName');
$result['_card_num'] = $pick('cardNum', 'CardNum', 'CARD_Num', 'cardNumber');
$result['_card_code'] = $pick('cardCode', 'CardCode');
$result['_card_quota'] = $this->formatQuota($pick('cardQuota', 'CardQuota', 'quota'));
$result['_card_interest'] = $pick('cardInterest', 'CardInterest', 'isInterestFree');
$result['_vbank_num'] = $pick('VACT_Num', 'vactNum', 'vbank_num');
$result['_vbank_bank_code'] = $pick('VACT_BankCode', 'vactBankCode', 'vbank_bank_code');
$result['_vbank_bank_name'] = $pick('VACT_BankName', 'vactBankName', 'vbank_bank_name') ?? $this->bankNameByCode($result['_vbank_bank_code'] ?? null);
$result['_vbank_holder'] = $pick('VACT_Name', 'vactName', 'vbank_holder');
// 가상계좌 입금기한:
// 로컬 vbank_due_at 이 있으면 KST 로 변환해 사용 — 결제 발급 시 KG 이니시스가 보낸
// VACT_Date(=다음 영업일) + VACT_Time(=08:59:59) 으로 만든 정확한 cutoff timestamp.
// DB 는 UTC 로 저장되므로 표시 시 Asia/Seoul 로 변환해야 주문 상세 화면(KST 표시) 과 일치.
// 조회 응답의 vacctInfo.validDate 는 "마지막 입금 가능일" convention 이라 1일 일찍 표시되어
// 로컬 timestamp 가 더 정확.
$result['_vbank_expire_date'] = $localVbankDueAt !== null
? \Carbon\Carbon::parse($localVbankDueAt, 'UTC')->setTimezone('Asia/Seoul')->format('Y-m-d H:i:s')
: $this->formatDate($pick('VACT_Date', 'vactDate', 'vbank_expire_date', 'validDate'));
$vbankStatus = $pick('VACT_Status', 'vactStatus', 'vbank_status');
$result['_vbank_status'] = $vbankStatus;
$result['_vbank_paid_at'] = $this->formatDateTime($pick('VACT_InputDate', 'VACT_InputTime') ? $pick('VACT_InputDate') : null, $pick('VACT_InputTime'));
$result['_bank_code'] = $pick('acntBankCode', 'BankCode');
$result['_bank_name'] = $pick('acntBankName', 'BankName') ?? $this->bankNameByCode($result['_bank_code'] ?? null);
$result['_bank_acnt_num'] = $pick('acntNum', 'AcntNum');
$result['_hpp_num'] = $pick('HPP_Num', 'hppNum', 'phoneNum');
$result['_hpp_corp'] = $pick('HPP_Corp', 'hppCorp', 'mobileCarrier');
$result['_escrow_status'] = $pick('escrowStatus', 'EscrowStatus');
$result['_escrow_confirm'] = $this->formatDateTime($pick('escrowConfirmDate'), $pick('escrowConfirmTime'));
// 환경 정보
$result['_inquiry_at'] = date('Y-m-d H:i:s');
return $result;
}
/**
* KG 이니시스 payMethod 코드를 한국어 라벨로 매핑한다.
*
* 플러그인 JSON lang 의 중첩 키는 Laravel `__()` 의 flat lookup 으로 해석되지 않으므로
* 한국어 어드민 UX 전제하에 PHP 직접 매핑. 다국어가 필요해질 경우 레이아웃 측
* `$t:` 보간으로 처리하거나 lang/ko/pay_method.php 같은 PHP 배열 파일로 분리한다.
*
* @param string $code KG 이니시스 결제수단 코드
* @return string 표시용 라벨
*/
private function payMethodLabel(string $code): string
{
if ($code === '') {
return '-';
}
return match (strtolower($code)) {
'card' => '신용카드',
'wcard' => '해외카드',
'vbank' => '가상계좌',
'directbank', 'inibank', 'banktransfer' => '계좌이체',
'hpp', 'mobile' => '휴대폰',
'easypay' => '간편결제',
'point' => '포인트',
'gift' => '상품권',
'paybook' => '도서문화상품권',
'billing', 'billingpay' => '정기결제',
'samsungpay' => '삼성페이',
'kakaopay' => '카카오페이',
'lpay' => 'L.pay',
'payco' => '페이코',
'naverpay' => '네이버페이',
'tosspay', 'toss' => '토스페이',
'ssgpay' => 'SSG페이',
'paypay' => 'PayPay',
'cvs' => '일본 편의점결제',
default => $code,
};
}
private function embeddedPgProviderLabel(?string $provider): ?string
{
if ($provider === null || $provider === '') {
return null;
}
return match (strtolower($provider)) {
'samsungpay' => '삼성페이',
'kakaopay' => '카카오페이',
'lpay' => 'L.pay',
'payco' => '페이코',
'naverpay' => '네이버페이',
'tosspay', 'toss' => '토스페이',
'ssgpay' => 'SSG페이',
default => $provider,
};
}
/**
* KG 이니시스 표준 은행 코드 → 은행명 매핑.
*
* @param string|null $code 표준 은행 코드
* @return string|null 은행명 또는 null
*/
private function bankNameByCode(?string $code): ?string
{
if ($code === null || $code === '') {
return null;
}
$map = [
'03' => '기업은행',
'04' => '국민은행',
'05' => '하나(외환)은행',
'07' => '수협',
'11' => '농협',
'12' => '단위농협',
'20' => '우리은행',
'21' => '구.조흥은행',
'22' => '구.상업은행',
'23' => 'SC제일은행',
'26' => '구.신한은행',
'27' => '한국씨티은행',
'31' => '대구은행',
'32' => '부산은행',
'34' => '광주은행',
'35' => '제주은행',
'37' => '전북은행',
'39' => '경남은행',
'45' => '새마을금고',
'48' => '신협',
'50' => '상호저축은행',
'54' => 'HSBC',
'57' => '도이치은행',
'60' => 'BOA',
'64' => '산림조합',
'71' => '우체국',
'81' => '하나은행',
'83' => '신한은행',
'88' => '신한(통합)은행',
'89' => '케이뱅크',
'90' => '카카오뱅크',
'92' => '토스뱅크',
];
return $map[$code] ?? null;
}
/**
* 카드 할부 코드를 한국어로 변환한다.
*
* @param string|null $quota KG 이니시스 할부 개월 코드
* @return string|null 표시용 라벨
*/
private function formatQuota(?string $quota): ?string
{
if ($quota === null || $quota === '') {
return null;
}
$months = (int) $quota;
return $months === 0 ? '일시불' : "{$months}개월";
}
/**
* YYYYMMDD + HHMMSS 형식을 YYYY-MM-DD HH:MM:SS 로 변환한다.
*
* @param string|null $date YYYYMMDD
* @param string|null $time HHMMSS
* @return string|null 사람이 읽을 수 있는 형식
*/
private function formatDateTime(?string $date, ?string $time): ?string
{
if ($date === null || $date === '') {
return null;
}
$datePart = $this->formatDate($date) ?? $date;
$timePart = '';
if ($time !== null && $time !== '' && strlen($time) >= 6) {
$timePart = ' ' . substr($time, 0, 2) . ':' . substr($time, 2, 2) . ':' . substr($time, 4, 2);
}
return $datePart . $timePart;
}
/**
* YYYYMMDD 형식을 YYYY-MM-DD 로 변환한다.
*
* @param string|null $date YYYYMMDD
* @return string|null 변환된 날짜
*/
private function formatDate(?string $date): ?string
{
if ($date === null || $date === '' || strlen($date) < 8) {
return $date;
}
return substr($date, 0, 4) . '-' . substr($date, 4, 2) . '-' . substr($date, 6, 2);
}
/**
* 부분취소 이력을 화면 표시용으로 정규화한다.
*
* @param array $list KG 이니시스 partCancelList
* @return array 정규화된 부분취소 이력
*/
private function normalizePartCancelList(array $list): array
{
$normalized = [];
foreach ($list as $item) {
if (! is_array($item)) {
continue;
}
$normalized[] = [
'price' => $item['price'] ?? $item['cancelPrice'] ?? null,
'date' => $this->formatDateTime($item['cancelDate'] ?? null, $item['cancelTime'] ?? null),
'msg' => $item['cancelMsg'] ?? $item['msg'] ?? null,
'tid' => $item['cancelTid'] ?? $item['tid'] ?? null,
];
}
return $normalized;
}
}
@@ -0,0 +1,724 @@
<?php
declare(strict_types=1);
namespace Plugins\Sirsoft\PayKginicis\Controllers;
use App\Services\PluginSettingsService;
use Carbon\Carbon;
use Illuminate\Http\RedirectResponse;
use Illuminate\Support\Facades\Log;
use Modules\Sirsoft\Ecommerce\Enums\PaymentStatusEnum;
use Modules\Sirsoft\Ecommerce\Models\Order;
use Modules\Sirsoft\Ecommerce\Services\CurrencyConversionService;
use Modules\Sirsoft\Ecommerce\Services\OrderProcessingService;
use Plugins\Sirsoft\PayKginicis\Concerns\IssuesReceiptCookie;
use Plugins\Sirsoft\PayKginicis\Concerns\PreventsReplayCallback;
use Plugins\Sirsoft\PayKginicis\Http\Requests\CbtCallbackRequest;
use Plugins\Sirsoft\PayKginicis\Services\CbtReconciliationService;
use Plugins\Sirsoft\PayKginicis\Services\KgInicisApiService;
/**
* KG 이니시스 CBT (Cross Border Trade) 일본 결제 콜백 컨트롤러
*
* CBT 결제 흐름:
* 1. 브라우저가 /cbtauth 로 POST 폼 전송
* 2. KG 이니시스가 returnUrl 로 sid 를 붙여 리다이렉트 → 이 컨트롤러
* 3. 서버가 /cbtapprove 로 mid + sid 전송하여 최종 승인
* 4. 성공 시 주문 완료 처리 후 결제 완료 페이지로 리다이렉트
*/
class CbtCallbackController
{
use IssuesReceiptCookie;
use PreventsReplayCallback;
private const PLUGIN_IDENTIFIER = 'sirsoft-pay_kginicis';
private const CBT_USER_CANCEL_RESULT_CODES = ['2001', '0021', '0022'];
private const CBT_USER_CANCEL_MESSAGE_PATTERNS = [
'ユーザーキャンセル',
'キャンセル',
'사용자가 결제를 취소',
'결제를 취소',
'사용자가 취소',
'사용자 취소',
'취소',
];
private const CBT_PAYPAY_PROCESSING_FAILURE_MESSAGE = 'PayPay 결제를 완료하지 못했습니다. 다시 시도하거나 다른 결제수단을 선택해 주세요.';
private const CBT_AUTH_RESPONSE_KEYS = [
'resultCode',
'resultMsg',
'orderID',
'orderId',
'oid',
'mid',
'sid',
'paymethod',
'selectedPaymentMethod',
];
private const CBT_APPROVE_RESPONSE_KEYS = [
'resultCode',
'resultMsg',
'code',
'message',
'tid',
'transactionId',
'paymethod',
'payMethod',
'amount',
'price',
'currency',
'approve',
'applDate',
'applTime',
'installMonth',
'cardCode',
'cardName',
'applNo',
'convenience',
'confNo',
'receiptNo',
'paymentTerm',
'currencyCd',
'currencyCode',
'mid',
'MID',
'oid',
'orderId',
'orderID',
];
private const CBT_REFUND_RESPONSE_KEYS = [
'resultCode',
'resultMsg',
'tid',
'cancelDate',
'cancelTime',
'prtcCode',
];
public function __construct(
private readonly OrderProcessingService $orderService,
private readonly PluginSettingsService $pluginSettingsService,
private readonly KgInicisApiService $apiService,
private readonly CbtReconciliationService $reconciliationService,
) {}
/**
* CBT(일본 엔화) 결제 인증 콜백을 받아 승인 처리 후 결과 페이지로 리다이렉트합니다.
*
* @param CbtCallbackRequest $request CBT 인증 콜백 요청
* @return RedirectResponse 성공/실패 결과 페이지 리다이렉트
*/
public function handle(CbtCallbackRequest $request): RedirectResponse
{
$sid = (string) $request->input('sid', '');
$oid = $this->resolveOrderId($request);
$authResultCode = (string) $request->input('resultCode', '');
$authResultMsg = (string) $request->input('resultMsg', '');
$authMid = (string) $request->input('mid', '');
if ($authResultCode !== '' && $authResultCode !== 'OK' && $this->isCbtAuthUserCancel($authResultCode, $authResultMsg)) {
Log::info('KG Inicis CBT: auth cancelled by user', [
'oid' => $oid,
'result_code' => $authResultCode,
'result_msg' => $authResultMsg,
]);
return redirect($this->resolveFailUrl());
}
if ($sid === '' || $oid === '') {
Log::warning('KG Inicis CBT: missing sid or oid', ['oid' => $oid, 'sid' => $sid]);
return redirect($this->resolveFailUrl(['error' => 'invalid_params', 'orderId' => $oid]));
}
if ($authResultCode !== '' && $authResultCode !== 'OK') {
// 브라우저가 전달한 CBT 인증 실패값은 무인증 콜백이므로 주문 상태 변경에는 사용하지 않는다.
Log::warning('KG Inicis CBT: auth failed', [
'oid' => $oid,
'result_code' => $authResultCode,
'result_msg' => $authResultMsg,
]);
return redirect($this->resolveFailUrl($this->buildCbtFailureRedirectParams(
$authResultCode !== '' ? $authResultCode : 'cbt_auth_failed',
$authResultMsg,
(string) $request->input('paymethod', ''),
$oid,
)));
}
if ($authMid !== '' && $authMid !== $this->apiService->getJapanMid()) {
Log::warning('KG Inicis CBT: callback MID mismatch', [
'oid' => $oid,
'received_mid' => $authMid,
'expected_mid' => $this->apiService->getJapanMid(),
]);
return redirect($this->resolveFailUrl(['error' => 'mid_mismatch', 'orderId' => $oid]));
}
// Approve 성공 후 후속 처리 실패 시 PG 자동 cancel 추적 변수.
$approvedTid = null;
$approvedAmount = 0;
try {
$order = $this->orderService->findByOrderNumber($oid);
if (! $order) {
Log::error('KG Inicis CBT: order not found', ['oid' => $oid]);
return redirect($this->resolveFailUrl(['error' => 'order_not_found', 'orderId' => $oid]));
}
$this->assertPayableCbtOrder($order);
$pgResponse = $this->apiService->approveCbtPayment($sid);
$resultCode = $pgResponse['resultCode'] ?? ($pgResponse['code'] ?? '');
if (! $this->isCbtSuccessCode((string) $resultCode)) {
$resultMsg = $pgResponse['resultMsg'] ?? ($pgResponse['message'] ?? 'CBT approve failed');
Log::warning('KG Inicis CBT: approve failed', [
'oid' => $oid,
'result_code' => $resultCode,
'result_msg' => $resultMsg,
]);
$this->orderService->failPayment($order, $resultCode, $resultMsg);
return redirect($this->resolveFailUrl($this->buildCbtFailureRedirectParams(
(string) $resultCode,
(string) $resultMsg,
(string) ($pgResponse['paymethod'] ?? $request->input('paymethod', '')),
$oid,
)));
}
$tid = $pgResponse['tid'] ?? ($pgResponse['transactionId'] ?? '');
if ($tid === '') {
throw new \RuntimeException('KG Inicis CBT approve response missing tid.');
}
// Replay 가드: 동일 tid 가 이미 paid 상태면 중복 처리하지 않고 성공 페이지로 복귀
if ($this->wasAlreadyPaid($tid)) {
$this->logReplayDetected($tid, $oid, 'CBT authCallback');
$this->queueReceiptCookie($oid);
return redirect($this->resolveSuccessUrl($oid));
}
$payMethod = (string) ($pgResponse['paymethod'] ?? $request->input('paymethod', 'CBT'));
if (! $this->isCbtCvsPayMethod($payMethod)) {
// PG 승인이 확정된 직후부터는 어떤 후속 예외라도 자동 취소 대상이다.
$approvedTid = $tid;
}
$this->assertCbtApproveResponseMatchesOrder($order, $pgResponse, $request, $payMethod);
// PG 승인금액이 누락되어 검증 예외가 발생해도 자동환불 대사 레코드에는 결제 통화 청구액을 남긴다
// (buildPgPaymentData 와 동일 SSoT — base≠결제 통화에서도 PG 청구 통화와 단위 일치).
$approvedAmount = app(CurrencyConversionService::class)->resolveOrderPaymentChargeAmount($order);
$approvedAmount = $this->resolveApprovedAmount($pgResponse, $order);
$authResponse = $this->sanitizePgResponse($request->except(['_token']), self::CBT_AUTH_RESPONSE_KEYS);
$approveResponse = $this->sanitizePgResponse($pgResponse, self::CBT_APPROVE_RESPONSE_KEYS);
$selectedPaymentMethod = $this->resolveSelectedCbtPaymentMethod($request, $payMethod);
$selectionMeta = $this->buildCbtSelectionPaymentMeta($selectedPaymentMethod);
if ($this->isCbtCvsPayMethod($payMethod)) {
$this->handleCbtCvsIssued($order, $pgResponse, $tid, $sid, $approvedAmount, $authResponse, $approveResponse, $selectedPaymentMethod);
$this->queueReceiptCookie($oid);
Log::info('KG Inicis CBT: CVS payment issued', ['oid' => $oid, 'tid' => $tid]);
return redirect($this->resolveSuccessUrl($oid));
}
$this->orderService->completePayment($order, [
'transaction_id' => $tid,
'card_approval_number' => $pgResponse['approve'] ?? null,
'card_installment_months' => $this->normalizeInstallmentMonths($pgResponse['installMonth'] ?? null),
'payment_meta' => array_merge([
'result_code' => $resultCode,
'pay_method' => $payMethod,
'cbt_type' => 'JPPG',
'cbt_mid' => $this->apiService->getJapanMid(),
'cbt_sid' => $sid,
'mid' => $this->apiService->getJapanMid(),
'currency' => 'JPY',
'is_cbt' => true,
'is_test_mode' => $this->apiService->isTestMode(),
'pg_response_sanitized' => true,
'pg_auth_response' => $authResponse,
'pg_approve_response' => $approveResponse,
'pg_raw_response' => $approveResponse,
], $selectionMeta),
], $approvedAmount);
$this->queueReceiptCookie($oid);
Log::info('KG Inicis CBT: payment completed', ['oid' => $oid, 'tid' => $tid]);
return redirect($this->resolveSuccessUrl($oid));
} catch (\Exception $e) {
Log::error('KG Inicis CBT: callback exception', [
'oid' => $oid,
'tid' => $approvedTid,
'error' => $e->getMessage(),
]);
if ($this->wasAlreadyPaid($approvedTid)) {
Log::warning('KG Inicis CBT: local payment already completed, auto-refund skipped after exception', [
'oid' => $oid,
'tid' => $approvedTid,
'error' => $e->getMessage(),
]);
$this->queueReceiptCookie($oid);
return redirect($this->resolveSuccessUrl($oid));
}
$this->refundApprovedCbtPaymentOrFlagManualReconciliation(
$approvedTid,
$oid,
$approvedAmount,
$e->getMessage(),
);
return redirect($this->resolveFailUrl(['error' => 'cbt_failed', 'orderId' => $oid]));
}
}
private function resolveOrderId(CbtCallbackRequest $request): string
{
return (string) (
$request->input('orderID')
?: $request->input('orderId')
?: $request->input('oid')
?: ''
);
}
private function isCbtSuccessCode(string $resultCode): bool
{
return in_array($resultCode, ['OK', '00', '0000'], true);
}
private function isCbtAuthUserCancel(string $resultCode, string $resultMsg): bool
{
if (in_array($resultCode, self::CBT_USER_CANCEL_RESULT_CODES, true)) {
return true;
}
foreach (self::CBT_USER_CANCEL_MESSAGE_PATTERNS as $pattern) {
if ($resultMsg !== '' && str_contains($resultMsg, $pattern)) {
return true;
}
}
return false;
}
private function buildCbtFailureRedirectParams(
string $resultCode,
string $resultMsg,
string $payMethod,
string $orderId,
): array {
if ($this->isPayPayProcessingFailure($resultCode, $resultMsg, $payMethod)) {
return [
'error' => 'paypay_processing_failed',
'message' => self::CBT_PAYPAY_PROCESSING_FAILURE_MESSAGE,
'orderId' => $orderId,
];
}
return [
'error' => $resultCode,
'message' => $resultMsg,
'orderId' => $orderId,
];
}
private function isPayPayProcessingFailure(string $resultCode, string $resultMsg, string $payMethod): bool
{
$normalizedPayMethod = strtoupper($payMethod);
$normalizedResultCode = strtolower($resultCode);
$normalizedResultMsg = strtolower($resultMsg);
$isPayPay = str_contains($normalizedPayMethod, 'PAYPAY');
return $isPayPay
&& (
$normalizedResultCode === 'processing_failure'
|| str_contains($normalizedResultMsg, 'processing failed upstream')
);
}
private function assertPayableCbtOrder(Order $order): void
{
if (! $order->order_status->isBeforePayment()) {
throw new \RuntimeException('Order is not payable.');
}
if ((string) $order->currency !== 'JPY') {
throw new \RuntimeException('CBT payment is only available for JPY orders.');
}
}
/**
* CBT 승인액을 확정합니다.
*
* KG 이니시스 일본 CBT 승인 응답(/cbtapprove)에는 신뢰할 금액 필드가 없다.
* 공식 매뉴얼(manual.inicis.com/jppay) 기준 승인 응답 파라미터는 결제수단별로
* - 신용카드: cardCode/approve/payType/installMonth (금액 없음)
* - 편의점(CVS): convenience/confNo/receiptNo/paymentTerm (금액 없음)
* - PayPay(BOKU): bokuApplPrice/bokuApplCurrency (모두 "일본결제 미사용" → 항상 공란)
* 이며 amount/price 키 자체가 존재하지 않는다. 금액의 권위는 인증요청(cbtauth)
* 시 가맹점이 보낸 금액(= 주문 결제예정액)과 NOTI(입금통보)의 amount 뿐이다.
*
* 따라서 승인 응답에 금액 필드가 채워져 오면 그 값으로 위변조를 검증하고,
* 비어 있으면(일본 CBT 정상 동작) 주문 결제예정액(order_currency=JPY 환산액)을
* 승인액으로 신뢰한다.
*
* @param array<string,mixed> $pgResponse CBT 승인 응답
* @param Order $order 결제 대상 주문
* @return int 확정된 승인 금액 (결제 통화 단위)
*/
private function resolveApprovedAmount(array $pgResponse, Order $order): int
{
// 결제 청구액 SSoT = 결제 통화(order_currency) 환산액 (buildPgPaymentData 와 동일 기준).
// CBT 는 order_currency=JPY 강제이나 base 통화는 다를 수 있어(예: base KRW, 결제 JPY)
// total_due_amount(base) 직접 비교 시 PG 승인액(JPY)과 단위가 어긋난다.
$expectedAmount = app(CurrencyConversionService::class)->resolveOrderPaymentChargeAmount($order);
$pgAmount = $this->firstNonEmptyString($pgResponse, ['amount', 'price', 'bokuApplPrice', 'bokuLocalApplPrice']);
// 일본 CBT 승인 응답은 금액 필드가 비어 온다(매뉴얼상 미사용). 금액이 없으면
// 주문 결제예정액을 승인액으로 신뢰한다(승인 권위 = resultCode OK + tid).
if ($pgAmount === null) {
return $expectedAmount;
}
// 라이브/타 결제수단에서 금액이 채워져 오면 위변조 검증을 유지한다.
$approvedAmount = (int) $pgAmount;
if ($approvedAmount !== $expectedAmount) {
throw new \RuntimeException('KG Inicis CBT approved amount mismatch.');
}
return $approvedAmount;
}
private function assertCbtApproveResponseMatchesOrder(
Order $order,
array $pgResponse,
CbtCallbackRequest $request,
string $approvedPayMethod,
): void {
$receivedOrderId = $this->firstNonEmptyString($pgResponse, ['orderId', 'orderID', 'oid']);
if ($receivedOrderId !== null && $receivedOrderId !== (string) $order->order_number) {
throw new \RuntimeException('KG Inicis CBT approved order id mismatch.');
}
$receivedMid = $this->firstNonEmptyString($pgResponse, ['mid', 'MID']);
$expectedMid = $this->apiService->getJapanMid();
if ($receivedMid !== null && $receivedMid !== $expectedMid) {
throw new \RuntimeException('KG Inicis CBT approved MID mismatch.');
}
$receivedCurrency = strtoupper((string) $this->firstNonEmptyString($pgResponse, ['currencyCd', 'currencyCode', 'currency']));
if ($receivedCurrency !== '' && $receivedCurrency !== 'JPY') {
throw new \RuntimeException('KG Inicis CBT approved currency mismatch.');
}
$expectedPayMethod = $this->resolveExpectedCbtPayMethod($request);
$receivedPayMethod = $this->normalizeCbtPayMethod($approvedPayMethod);
if ($expectedPayMethod !== null && $receivedPayMethod !== '' && $receivedPayMethod !== $expectedPayMethod) {
throw new \RuntimeException('KG Inicis CBT approved paymethod mismatch.');
}
}
/**
* @param array<string,mixed> $source
* @param array<int,string> $keys
*/
private function firstNonEmptyString(array $source, array $keys): ?string
{
foreach ($keys as $key) {
if (! array_key_exists($key, $source)) {
continue;
}
$value = trim((string) $source[$key]);
if ($value !== '') {
return $value;
}
}
return null;
}
private function resolveExpectedCbtPayMethod(CbtCallbackRequest $request): ?string
{
$selectedPaymentMethod = (string) $request->input('selectedPaymentMethod', '');
$expectedBySelectedMethod = [
'card' => 'CARD',
'kginicis_japan_paypay' => 'PAYPAY',
'kginicis_japan_cvs' => 'CVS',
];
if ($selectedPaymentMethod !== '' && isset($expectedBySelectedMethod[$selectedPaymentMethod])) {
return $expectedBySelectedMethod[$selectedPaymentMethod];
}
$authPayMethod = $this->normalizeCbtPayMethod((string) $request->input('paymethod', ''));
return $authPayMethod !== '' ? $authPayMethod : null;
}
private function resolveSelectedCbtPaymentMethod(CbtCallbackRequest $request, string $payMethod): ?string
{
$selectedPaymentMethod = (string) $request->input('selectedPaymentMethod', '');
$allowedSelectedMethods = [
'card',
'kginicis_japan_paypay',
'kginicis_japan_cvs',
];
if (in_array($selectedPaymentMethod, $allowedSelectedMethods, true)) {
return $selectedPaymentMethod;
}
return match ($this->normalizeCbtPayMethod($payMethod)) {
'CARD' => 'card',
'PAYPAY' => 'kginicis_japan_paypay',
'CVS' => 'kginicis_japan_cvs',
default => null,
};
}
private function buildCbtSelectionPaymentMeta(?string $selectedPaymentMethod): array
{
if ($selectedPaymentMethod === null || $selectedPaymentMethod === '') {
return [];
}
return [
'selected_payment_method' => $selectedPaymentMethod,
];
}
private function normalizeCbtPayMethod(string $payMethod): string
{
return strtoupper(trim($payMethod));
}
private function normalizeInstallmentMonths(mixed $value): ?int
{
if ($value === null || $value === '') {
return null;
}
return (int) $value;
}
private function isCbtCvsPayMethod(string $payMethod): bool
{
return strtoupper($payMethod) === 'CVS';
}
private function handleCbtCvsIssued(
Order $order,
array $pgResponse,
string $tid,
string $sid,
int $amount,
array $authResponse,
array $approveResponse,
?string $selectedPaymentMethod,
): void {
$paymentTerm = (string) ($pgResponse['paymentTerm'] ?? '');
$dueAt = null;
if (preg_match('/^\d{14}$/', $paymentTerm) === 1) {
try {
$dueAt = Carbon::createFromFormat('YmdHis', $paymentTerm, 'Asia/Tokyo')
->setTimezone(config('app.timezone', 'UTC'));
} catch (\Throwable) {
$dueAt = null;
}
}
$order->payment()->update(array_filter([
'pg_provider' => 'kginicis',
'payment_status' => PaymentStatusEnum::WAITING_DEPOSIT,
'transaction_id' => $tid,
'vbank_code' => $pgResponse['convenience'] ?? null,
'vbank_name' => 'CVS',
'vbank_number' => $pgResponse['confNo'] ?? ($pgResponse['receiptNo'] ?? null),
'vbank_due_at' => $dueAt,
'vbank_issued_at' => now(),
'payment_meta' => array_merge([
'result_code' => $pgResponse['resultCode'] ?? 'OK',
'pay_method' => 'CVS',
'cbt_type' => 'JPPG',
'cbt_mid' => $this->apiService->getJapanMid(),
'cbt_sid' => $sid,
'mid' => $this->apiService->getJapanMid(),
'currency' => 'JPY',
'is_cbt' => true,
'is_test_mode' => $this->apiService->isTestMode(),
'pg_response_sanitized' => true,
'pg_auth_response' => $authResponse,
'pg_approve_response' => $approveResponse,
'pg_raw_response' => $approveResponse,
'cvs_status' => 'waiting_deposit',
'cvs_amount' => $amount,
'cvs_convenience' => $pgResponse['convenience'] ?? null,
'cvs_conf_no' => $pgResponse['confNo'] ?? null,
'cvs_receipt_no' => $pgResponse['receiptNo'] ?? null,
'cvs_payment_term' => $paymentTerm !== '' ? $paymentTerm : null,
], $this->buildCbtSelectionPaymentMeta($selectedPaymentMethod)),
], fn ($value) => $value !== null));
}
private function refundApprovedCbtPaymentOrFlagManualReconciliation(
?string $tid,
string $oid,
int $amount,
string $reason,
): void {
if ($tid === null || $tid === '') {
return;
}
try {
$refundResult = $this->apiService->refundCbtPayment(
$tid,
null,
'CBT approved but local payment completion failed: '.mb_substr($reason, 0, 80),
);
$this->recordCbtReconciliationStatus($oid, [
'status' => CbtReconciliationService::STATUS_AUTO_REFUNDED,
'manual_action_required' => false,
'tid' => $tid,
'amount' => $amount,
'reason' => $reason,
'refund_error' => null,
'refund_result' => $this->sanitizePgResponse($refundResult, self::CBT_REFUND_RESPONSE_KEYS),
'is_test_mode' => $this->apiService->isTestMode(),
'cbt_mid' => $this->apiService->getJapanMid(),
'retry_count' => 0,
]);
Log::warning('KG Inicis CBT: approved payment auto-refunded after local failure', [
'tid' => $tid,
'oid' => $oid,
'amount' => $amount,
'reason' => $reason,
]);
return;
} catch (\Throwable $refundException) {
Log::error('KG Inicis CBT: auto refund after local failure failed', [
'tid' => $tid,
'oid' => $oid,
'amount' => $amount,
'reason' => $reason,
'refund_error' => $refundException->getMessage(),
]);
$this->recordCbtReconciliationStatus($oid, [
'status' => CbtReconciliationService::STATUS_MANUAL_REFUND_REQUIRED,
'manual_action_required' => true,
'tid' => $tid,
'amount' => $amount,
'reason' => $reason,
'refund_error' => $refundException->getMessage(),
'refund_result' => null,
'is_test_mode' => $this->apiService->isTestMode(),
'cbt_mid' => $this->apiService->getJapanMid(),
'retry_count' => 0,
]);
}
Log::error('KG Inicis CBT: post-approve failure — MANUAL CANCEL REQUIRED on KG Inicis JP merchant admin', [
'tid' => $tid,
'oid' => $oid,
'amount' => $amount,
'reason' => $reason,
]);
}
private function recordCbtReconciliationStatus(string $oid, array $attributes): void
{
$this->reconciliationService->record($oid, $attributes);
}
private function sanitizePgResponse(array $response, array $allowedKeys): array
{
$allowed = array_flip($allowedKeys);
$sanitized = [];
foreach ($response as $key => $value) {
if (! isset($allowed[$key])) {
continue;
}
$sanitized[$key] = is_scalar($value) || $value === null
? $value
: json_encode($value, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
}
return $sanitized;
}
private function resolveSuccessUrl(string $orderId): string
{
$settings = $this->pluginSettingsService->get(self::PLUGIN_IDENTIFIER) ?? [];
$urlTemplate = $settings['redirect_success_url'] ?? '/shop/orders/{orderId}/complete';
return $this->absolutize(str_replace('{orderId}', $orderId, $urlTemplate));
}
private function resolveFailUrl(array $queryParams = []): string
{
$settings = $this->pluginSettingsService->get(self::PLUGIN_IDENTIFIER) ?? [];
$baseUrl = $this->absolutize($settings['redirect_fail_url'] ?? '/shop/checkout');
if (empty($queryParams)) {
return $baseUrl;
}
$query = http_build_query(array_filter($queryParams));
$separator = str_contains($baseUrl, '?') ? '&' : '?';
return $baseUrl.$separator.$query;
}
/**
* 상대 경로면 APP_URL 기준으로 절대 URL 화.
*
* PG가 브라우저 POST 로 콜백을 보내는 동안 Apache 가 ProxyPreserveHost Off 등
* 으로 Host 헤더를 localhost 로 바꿔서 PHP 에 전달하는 경우, Laravel 의
* redirect('/path') 가 http://localhost/path 를 생성해버린다. config('app.url')
* (.env 의 APP_URL)을 명시적 base 로 사용하여 도메인을 보존한다.
*/
private function absolutize(string $url): string
{
if (preg_match('#^https?://#i', $url) === 1) {
return $url;
}
$base = rtrim((string) config('app.url'), '/');
$path = $url === '' ? '/' : ($url[0] === '/' ? $url : '/'.$url);
return $base.$path;
}
}
@@ -0,0 +1,111 @@
<?php
declare(strict_types=1);
namespace Plugins\Sirsoft\PayKginicis\Controllers;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\RateLimiter;
use Plugins\Sirsoft\PayKginicis\Concerns\ValidatesCbtOrderContext;
use Plugins\Sirsoft\PayKginicis\Services\CbtCheckoutTokenService;
use Plugins\Sirsoft\PayKginicis\Services\KgInicisApiService;
use Modules\Sirsoft\Ecommerce\Services\OrderProcessingService;
class CbtCheckoutTokenController
{
use ValidatesCbtOrderContext;
public function __construct(
private readonly KgInicisApiService $apiService,
private readonly OrderProcessingService $orderService,
private readonly CbtCheckoutTokenService $checkoutTokenService,
) {}
public function issue(Request $request): JsonResponse
{
$oid = (string) $request->input('oid', '');
$price = (int) $request->input('price', 0);
if ($oid === '' || $price <= 0) {
return response()->json([
'success' => false,
'message' => 'Missing required parameters: oid, price',
], 422);
}
$rateLimitKey = 'sirsoft-pay_kginicis:cbt-token:' . sha1($request->ip() . '|' . $oid);
if (RateLimiter::tooManyAttempts($rateLimitKey, 10)) {
return response()->json([
'success' => false,
'message' => 'Too many CBT checkout token requests. Please try again later.',
], 429);
}
RateLimiter::hit($rateLimitKey, 60);
if (! $this->apiService->isJapanEnabled()) {
return response()->json([
'success' => false,
'message' => 'Japan CBT payment is disabled.',
], 422);
}
if (! $this->apiService->isJapanConfigured()) {
return response()->json([
'success' => false,
'message' => 'Japan CBT payment is not configured.',
], 422);
}
$order = $this->orderService->findByOrderNumber($oid);
if (! $order) {
return response()->json([
'success' => false,
'message' => 'Order not found.',
], 404);
}
if (! $order->order_status->isBeforePayment()) {
return response()->json([
'success' => false,
'message' => 'Order is not payable.',
], 422);
}
if ((string) $order->currency !== 'JPY') {
return response()->json([
'success' => false,
'message' => 'CBT payment is only available for JPY orders.',
], 422);
}
if (! $this->cbtRequestMatchesOrderBuyer($request, $order)) {
return response()->json([
'success' => false,
'message' => 'Order buyer verification failed.',
], 403);
}
if ($price !== $this->cbtExpectedPrice($order)) {
return response()->json([
'success' => false,
'message' => 'Payment amount does not match the order amount.',
], 422);
}
$token = $this->checkoutTokenService->issue(
$oid,
$price,
(string) $request->input('buyer_email', ''),
(string) $request->input('buyer_phone', ''),
$request,
);
return response()->json([
'success' => true,
'data' => [
'checkout_token' => $token,
],
]);
}
}
@@ -0,0 +1,37 @@
<?php
declare(strict_types=1);
namespace Plugins\Sirsoft\PayKginicis\Controllers;
use Illuminate\Http\Response;
use Plugins\Sirsoft\PayKginicis\Http\Requests\CbtCvsNotifyRequest;
use Plugins\Sirsoft\PayKginicis\Services\CbtCvsOperationsService;
/**
* KG 이니시스 CBT 편의점 입금 NOTI 수신 컨트롤러.
*/
class CbtCvsNotifyController
{
public function __construct(
private readonly CbtCvsOperationsService $operationsService,
) {}
/**
* KG 이니시스 CBT 편의점 입금 통보를 수신한다.
*
* @param CbtCvsNotifyRequest $request
* @return Response
*/
public function handle(CbtCvsNotifyRequest $request): Response
{
$result = $this->operationsService->handleNotify($request->all(), 'kg', $request->ip());
return $this->plain((string) ($result['body'] ?? 'FAIL'));
}
private function plain(string $body): Response
{
return response($body, 200)->header('Content-Type', 'text/plain');
}
}
@@ -0,0 +1,143 @@
<?php
declare(strict_types=1);
namespace Plugins\Sirsoft\PayKginicis\Controllers;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\RateLimiter;
use Modules\Sirsoft\Ecommerce\Services\OrderProcessingService;
use Plugins\Sirsoft\PayKginicis\Concerns\ValidatesCbtOrderContext;
use Plugins\Sirsoft\PayKginicis\Concerns\ValidatesTimestampFreshness;
use Plugins\Sirsoft\PayKginicis\Services\CbtCheckoutTokenService;
use Plugins\Sirsoft\PayKginicis\Services\KgInicisApiService;
class CbtHashDataController
{
use ValidatesCbtOrderContext;
use ValidatesTimestampFreshness;
public function __construct(
private readonly KgInicisApiService $apiService,
private readonly OrderProcessingService $orderService,
private readonly CbtCheckoutTokenService $checkoutTokenService,
) {}
/**
* generate
*
* @param Request $request
* @return JsonResponse
*/
public function generate(Request $request): JsonResponse
{
$oid = (string) $request->input('oid', '');
$price = (int) $request->input('price', 0);
$timestamp = (string) $request->input('timestamp', '');
$checkoutToken = (string) $request->input('checkout_token', '');
if ($oid === '' || $price <= 0 || $timestamp === '') {
return response()->json([
'success' => false,
'message' => 'Missing required parameters: oid, price, timestamp',
], 422);
}
$rateLimitKey = $this->rateLimitKey($request, $oid);
if (RateLimiter::tooManyAttempts($rateLimitKey, 10)) {
return response()->json([
'success' => false,
'message' => 'Too many CBT hash requests. Please try again later.',
], 429);
}
RateLimiter::hit($rateLimitKey, 60);
if (! $this->isTimestampFresh($timestamp)) {
return response()->json([
'success' => false,
'message' => 'Timestamp is stale or invalid (signature replay protection).',
], 422);
}
if (! $this->apiService->isJapanEnabled()) {
return response()->json([
'success' => false,
'message' => 'Japan CBT payment is disabled.',
], 422);
}
if (! $this->apiService->isJapanConfigured()) {
return response()->json([
'success' => false,
'message' => 'Japan CBT payment is not configured.',
], 422);
}
$order = $this->orderService->findByOrderNumber($oid);
if (! $order) {
return response()->json([
'success' => false,
'message' => 'Order not found.',
], 404);
}
if (! $order->order_status->isBeforePayment()) {
return response()->json([
'success' => false,
'message' => 'Order is not payable.',
], 422);
}
if ((string) $order->currency !== 'JPY') {
return response()->json([
'success' => false,
'message' => 'CBT payment is only available for JPY orders.',
], 422);
}
if (! $this->cbtRequestMatchesOrderBuyer($request, $order)) {
return response()->json([
'success' => false,
'message' => 'Order buyer verification failed.',
], 403);
}
$expectedPrice = $this->cbtExpectedPrice($order);
if ($price !== $expectedPrice) {
return response()->json([
'success' => false,
'message' => 'Payment amount does not match the order amount.',
], 422);
}
if (! $this->checkoutTokenService->verify(
$checkoutToken,
$oid,
$price,
(string) $request->input('buyer_email', ''),
(string) $request->input('buyer_phone', ''),
$request,
)) {
return response()->json([
'success' => false,
'message' => 'CBT checkout token verification failed.',
], 403);
}
$mid = $this->apiService->getJapanMid();
$hashData = $this->apiService->generateCbtHashData($mid, $timestamp, $price, $oid);
return response()->json([
'success' => true,
'data' => [
'hash_data' => $hashData,
],
]);
}
private function rateLimitKey(Request $request, string $oid): string
{
return 'sirsoft-pay_kginicis:cbt-hash:' . sha1($request->ip() . '|' . $oid);
}
}
@@ -0,0 +1,466 @@
<?php
declare(strict_types=1);
namespace Plugins\Sirsoft\PayKginicis\Controllers;
use App\Services\PluginSettingsService;
use Carbon\Carbon;
use Illuminate\Support\Facades\Log;
use Modules\Sirsoft\Ecommerce\Enums\PaymentStatusEnum;
use Modules\Sirsoft\Ecommerce\Exceptions\PaymentAmountMismatchException;
use Modules\Sirsoft\Ecommerce\Models\Order;
use Modules\Sirsoft\Ecommerce\Services\OrderProcessingService;
use Plugins\Sirsoft\PayKginicis\Concerns\IssuesReceiptCookie;
use Plugins\Sirsoft\PayKginicis\Concerns\PreventsReplayCallback;
use Plugins\Sirsoft\PayKginicis\Concerns\ResolvesEasyPaySelection;
use Plugins\Sirsoft\PayKginicis\Concerns\SanitizesPgResponse;
use Plugins\Sirsoft\PayKginicis\Http\Requests\MobileCallbackRequest;
use Plugins\Sirsoft\PayKginicis\Services\KgInicisApiService;
/**
* KG 이니시스 모바일 결제 콜백 컨트롤러
*
* 모바일 결제 흐름:
* 1단계: 프론트엔드가 https://mobile.inicis.com/smart/payment/ 로 폼 제출 (페이지 이동)
* 2단계: KG 이니시스 인증 후 P_NEXT_URL(이 컨트롤러)로 POST 콜백 (manual.inicis.com/pay/stdpay_m.html)
* 3단계: 서버가 P_REQ_URL로 서버 승인 요청 (P_MID + P_TID)
* 4단계: 승인 응답(URL-encoded) 파싱 후 주문 완료 처리 (가상계좌는 발급 정보만 저장)
*/
class MobileCallbackController
{
use IssuesReceiptCookie;
use PreventsReplayCallback;
use ResolvesEasyPaySelection;
use SanitizesPgResponse;
private const PLUGIN_IDENTIFIER = 'sirsoft-pay_kginicis';
// KG 이니시스 모바일 표준결제 — 사용자 결제창 닫기 시 P_RMESG1 에 포함되는 패턴.
// Playwright 운영 재현으로 확인 (P_STATUS=01 은 일반 실패와 공유되므로 메시지 기반 분기).
private const USER_CANCEL_MESSAGE_PATTERNS = ['사용자가 결제를 취소', '결제를 취소하셨'];
private const MOBILE_APPROVE_RESPONSE_KEYS = [
'P_STATUS',
'P_RMESG1',
'P_TID',
'P_OID',
'P_AMT',
'P_TYPE',
'P_AUTH_DT',
'P_APPL_NUM',
'P_FN_CD1',
'P_FN_NM',
'P_CARD_ISSUER_NAME',
'P_CARD_QUOTA',
'P_CARD_INTEREST',
'P_MID',
'P_GOODS',
];
private const MOBILE_VBANK_ISSUE_RESPONSE_KEYS = [
'P_STATUS',
'P_RMESG1',
'P_TID',
'P_OID',
'P_AMT',
'P_TYPE',
'P_AUTH_DT',
'P_FN_CD1',
'P_FN_NM',
'P_VACT_BANK_CODE',
'P_VACT_BANK_NAME',
'P_VACT_DATE',
'P_VACT_TIME',
'P_MID',
'P_GOODS',
];
public function __construct(
private readonly OrderProcessingService $orderService,
private readonly PluginSettingsService $pluginSettingsService,
private readonly KgInicisApiService $apiService,
) {}
/**
* handle
*
* @param MobileCallbackRequest $request
* @return \Illuminate\Http\RedirectResponse
*/
public function handle(MobileCallbackRequest $request): \Illuminate\Http\RedirectResponse
{
$validated = $request->validated();
$selectedEasyPayMethod = $this->resolveSelectedEasyPayMethod($request);
$pStatus = $validated['P_STATUS'];
// KG 이니시스 모바일 메뉴얼(STEP 2) 표준 응답에는 P_OID 가 없으므로 P_NEXT_URL 쿼리스트링의
// orderId 를 fallback 으로 사용한다. 일부 PG 환경에서 P_OID 를 echo 하면 우선 채택.
$moid = $validated['P_OID'] ?? $request->query('orderId') ?? null;
$pAmt = $validated['P_AMT'] ?? null;
Log::info('KG Inicis mobile: callback received', [
'order_id' => $moid,
'P_STATUS' => $pStatus,
'idc_name' => $validated['idc_name'] ?? null,
'P_REQ_URL' => $validated['P_REQ_URL'] ?? null,
'input_keys' => array_keys($request->all()),
'query_keys' => array_keys($request->query()),
'easy_pay' => $this->buildEasyPayLogContext($selectedEasyPayMethod),
]);
if (! $moid) {
Log::error('KG Inicis mobile: order id missing — neither P_OID nor query orderId present', [
'all_keys' => array_keys($request->all()),
]);
return redirect($this->resolveFailUrl(['error' => 'order_id_missing']));
}
// 인증 실패
if ($pStatus !== '00') {
$pMesg = (string) ($validated['P_RMESG1'] ?? '');
$isUserCancel = $this->isUserCancelMessage($pMesg);
Log::info('KG Inicis mobile: auth not success', [
'P_OID' => $moid,
'P_STATUS' => $pStatus,
'P_RMESG1' => $pMesg,
'is_user_cancel' => $isUserCancel,
]);
// 사용자가 결제창을 직접 닫은 취소는 오류 모달 없이 체크아웃으로 조용히 복귀
if ($isUserCancel) {
return redirect($this->resolveFailUrl());
}
return redirect($this->resolveFailUrl([
'error' => $pStatus,
'message' => $pMesg,
'orderId' => $moid,
]));
}
$pTid = $validated['P_TID'] ?? null;
$idcName = $validated['idc_name'] ?? null;
$reqUrl = $validated['P_REQ_URL'] ?? null;
if (! $pTid || ! $idcName || ! $reqUrl) {
Log::error('KG Inicis mobile: missing required fields', [
'P_OID' => $moid,
'idc_name' => $idcName,
'P_TID' => $pTid,
'P_REQ_URL' => $reqUrl,
]);
return redirect($this->resolveFailUrl(['error' => 'missing_fields', 'orderId' => $moid]));
}
// P_REQ_URL 화이트리스트 검증 (모바일 IDC URL, SSRF 방어)
if (! $this->apiService->isValidIdcAuthUrl($idcName, $reqUrl)) {
Log::error('KG Inicis mobile: P_REQ_URL not in whitelist (possible SSRF attempt)', [
'P_OID' => $moid,
'idc_name' => $idcName,
'received' => $reqUrl,
]);
return redirect($this->resolveFailUrl(['error' => 'req_url_invalid', 'orderId' => $moid]));
}
// Approve 성공 후 후속 처리 실패 시 PG 측 자동 cancel 을 위한 추적 변수.
// catch 블록에서 set 되어 있으면 KG 이니시스 측 승인이 이미 발생한 상태이므로
// cancelPayment 를 호출해 PG 잔존 승인을 해제한다 (사용자 환불 보장).
$approvedTid = null;
$approvedTotPrice = 0;
try {
$order = $this->orderService->findByOrderNumber($moid);
if (! $order) {
Log::error('KG Inicis mobile: order not found', ['P_OID' => $moid]);
return redirect($this->resolveFailUrl(['error' => 'order_not_found', 'orderId' => $moid]));
}
// 서버 승인 요청: POST P_REQ_URL with P_MID + P_TID
$result = $this->apiService->authorizeMobilePayment($reqUrl, $pTid);
$resultStatus = $result['P_STATUS'] ?? '';
if ($resultStatus !== '00') {
Log::warning('KG Inicis mobile: server approve failed', [
'P_OID' => $moid,
'P_STATUS' => $resultStatus,
'P_RMESG1' => $result['P_RMESG1'] ?? '',
]);
$this->orderService->failPayment($order, $resultStatus, $result['P_RMESG1'] ?? '');
return redirect($this->resolveFailUrl([
'error' => $resultStatus,
'message' => $result['P_RMESG1'] ?? '',
'orderId' => $moid,
]));
}
$tid = $result['P_TID'] ?? $pTid;
$totPrice = (int) ($result['P_AMT'] ?? $pAmt ?? 0);
$payType = (string) ($result['P_TYPE'] ?? '');
// 가상계좌: completePayment 없이 발급 정보만 저장 (입금 통보 시점에 completePayment)
if (strcasecmp($payType, 'VBank') === 0) {
$this->handleVbankIssued($order, $result, $tid);
$this->queueReceiptCookie($moid);
return redirect($this->resolveSuccessUrl($moid));
}
// Replay 가드: 동일 tid 가 이미 paid 상태면 중복 처리하지 않고 성공 페이지로 복귀
if ($this->wasAlreadyPaid($tid)) {
$this->logReplayDetected($tid, $moid, 'mobile authCallback (card)');
$this->queueReceiptCookie($moid);
return redirect($this->resolveSuccessUrl($moid));
}
// PG 측 승인이 확정된 시점 — 후속 처리 실패 시 cancel 필요. catch 에서 참조.
$approvedTid = $tid;
$approvedTotPrice = $totPrice;
$embeddedPgProvider = $this->resolveEmbeddedPgProvider($selectedEasyPayMethod);
Log::info('KG Inicis mobile: completing card payment', [
'P_OID' => $moid,
'P_TID' => $tid,
'P_TYPE' => $payType ?: null,
'easy_pay' => $this->buildEasyPayLogContext($selectedEasyPayMethod),
]);
$this->orderService->completePayment($order, [
'transaction_id' => $tid,
'card_approval_number' => $result['P_APPL_NUM'] ?? null,
'card_number_masked' => $result['P_CARD_NUM'] ?? null,
'card_name' => $result['P_CARD_ISSUER_NAME'] ?? null,
'card_installment_months' => (int) ($result['P_CARD_QUOTA'] ?? 0),
'is_interest_free' => false,
'embedded_pg_provider' => $embeddedPgProvider,
'receipt_url' => null,
'payment_meta' => array_merge([
'result_code' => $resultStatus,
'pay_method' => $payType ?: null,
'auth_date' => $result['P_AUTH_DT'] ?? null,
'mid' => $this->apiService->getMid(),
'is_test_mode' => $this->apiService->isTestMode(),
'pg_response_sanitized' => true,
'pg_raw_response' => $this->sanitizePgResponse($result, self::MOBILE_APPROVE_RESPONSE_KEYS),
], $this->buildEasyPayPaymentMeta($selectedEasyPayMethod)),
'payment_device' => 'mobile',
], $totPrice);
$order->payment()->update(['pg_provider' => 'kginicis']);
$this->queueReceiptCookie($moid);
return redirect($this->resolveSuccessUrl($moid));
} catch (PaymentAmountMismatchException $e) {
Log::error('KG Inicis mobile: amount mismatch', [
'P_OID' => $moid,
'expected' => $e->getExpectedAmount(),
'actual' => $e->getActualAmount(),
]);
$this->autoCancelIfApproved($approvedTid, $moid, $approvedTotPrice, 'amount_mismatch');
return redirect($this->resolveFailUrl(['error' => 'amount_mismatch', 'orderId' => $moid]));
} catch (\Exception $e) {
Log::error('KG Inicis mobile: approve exception', [
'P_OID' => $moid,
'P_TID' => $approvedTid,
'error' => $e->getMessage(),
]);
if ($this->wasAlreadyPaid($approvedTid)) {
Log::warning('KG Inicis mobile: local payment already completed, auto-cancel skipped after exception', [
'P_OID' => $moid,
'P_TID' => $approvedTid,
'error' => $e->getMessage(),
]);
$this->queueReceiptCookie($moid);
return redirect($this->resolveSuccessUrl($moid));
}
$this->autoCancelIfApproved($approvedTid, $moid, $approvedTotPrice, 'approve_failed');
return redirect($this->resolveFailUrl([
'error' => 'approve_failed',
'message' => $e->getMessage(),
'orderId' => $moid,
]));
}
}
/**
* Approve 가 이미 발생한 후 후속 처리 실패 시 KG 이니시스 측 cancel 을 시도.
*
* KG 이니시스 모바일 승인이 완료되었으나 우리 서버에서 completePayment 가
* 실패한 경우 사용자 카드는 PG 측에서 승인 상태로 잔존 → 환불 불가 위험.
* 본 메서드는 cancelPayment API (/v2/pg/refund) 로 PG 잔존 승인을 즉시 해제.
*
* cancel 자체가 실패해도 사용자 응답 흐름은 막지 않음 — 로깅만 수행하고
* 운영자가 KG 이니시스 가맹점 관리자에서 수동 처리하도록 신호.
*/
private function autoCancelIfApproved(
?string $tid,
string $moid,
int $totPrice,
string $reason,
): void {
if ($tid === null || $tid === '') {
return;
}
try {
$result = $this->apiService->cancelPayment(
$tid,
'Card',
null,
'auto-cancel: ' . $reason,
$totPrice > 0 ? $totPrice : null,
);
Log::warning('KG Inicis mobile: auto-cancel after post-approve failure', [
'tid' => $tid,
'P_OID' => $moid,
'amount' => $totPrice,
'reason' => $reason,
'pg_result' => $result,
]);
} catch (\Throwable $e) {
Log::error('KG Inicis mobile: auto-cancel FAILED — manual reconciliation required', [
'tid' => $tid,
'P_OID' => $moid,
'amount' => $totPrice,
'reason' => $reason,
'error' => $e->getMessage(),
]);
}
}
/**
* 모바일 가상계좌 발급 처리 (completePayment 없이 계좌 정보만 저장)
*
* KG 이니시스 모바일 승인 응답에서 P_TYPE=VBank 로 판별된 경우 호출.
* 실제 결제 완료(completePayment)는 입금 통보(mobileVbankNotify) 시점에 처리.
* 응답 필드는 manual.inicis.com/pay/stdpay_m.html 표준에 따른 P_VACT_* 형식.
*/
private function handleVbankIssued(Order $order, array $result, string $tid): void
{
$vactDate = $result['P_VACT_DATE'] ?? null;
$vactTime = $result['P_VACT_TIME'] ?? '235959';
$vbankDueAt = null;
if ($vactDate && strlen((string) $vactDate) === 8) {
try {
$vbankDueAt = Carbon::createFromFormat('YmdHis', $vactDate . $vactTime);
} catch (\Exception) {
$vbankDueAt = null;
}
}
$order->payment()->update(array_filter([
'pg_provider' => 'kginicis',
'payment_status' => PaymentStatusEnum::WAITING_DEPOSIT,
'transaction_id' => $tid ?: null,
'vbank_code' => $result['P_VACT_BANK_CODE'] ?? $result['P_FN_CD1'] ?? null,
'vbank_name' => $result['P_VACT_BANK_NAME'] ?? $result['P_FN_NM'] ?? null,
'vbank_number' => $result['P_VACT_NUM'] ?? null,
'vbank_holder' => $result['P_VACT_NAME'] ?? $result['P_RVACTNM'] ?? null,
'vbank_due_at' => $vbankDueAt,
'vbank_issued_at' => now(),
'payment_device' => 'mobile',
'payment_meta' => [
'result_code' => $result['P_STATUS'] ?? '00',
'pay_method' => 'VBank',
'auth_date' => $result['P_AUTH_DT'] ?? null,
'mid' => $this->apiService->getMid(),
'is_test_mode' => $this->apiService->isTestMode(),
'pg_response_sanitized' => true,
'pg_raw_response' => $this->sanitizePgResponse($result, self::MOBILE_VBANK_ISSUE_RESPONSE_KEYS),
],
], fn ($v) => $v !== null));
Log::info('KG Inicis mobile: vbank account issued', [
'P_OID' => $order->order_number,
'P_TID' => $tid,
'vbank_name' => $result['P_VACT_BANK_NAME'] ?? $result['P_FN_NM'] ?? null,
'vbank_number' => $result['P_VACT_NUM'] ?? null,
'vbank_due_at' => $vbankDueAt?->toDateTimeString(),
]);
}
private function resolveSuccessUrl(string $orderId): string
{
$settings = $this->pluginSettingsService->get(self::PLUGIN_IDENTIFIER) ?? [];
$urlTemplate = $settings['redirect_success_url'] ?? '/shop/orders/{orderId}/complete';
return $this->absolutize(str_replace('{orderId}', $orderId, $urlTemplate));
}
private function resolveFailUrl(array $queryParams = []): string
{
$settings = $this->pluginSettingsService->get(self::PLUGIN_IDENTIFIER) ?? [];
$baseUrl = $this->absolutize($settings['redirect_fail_url'] ?? '/shop/checkout');
if (empty($queryParams)) {
return $baseUrl;
}
$query = http_build_query(array_filter($queryParams, fn ($v) => $v !== null && $v !== ''));
$separator = str_contains($baseUrl, '?') ? '&' : '?';
return $baseUrl . $separator . $query;
}
/**
* KG 이니시스 모바일 P_RMESG1 메시지가 사용자 직접 취소 패턴인지 판별.
*
* P_STATUS=01 은 일반 실패(예: MX1006)와 사용자 취소가 공유하므로, P_RMESG1
* 메시지의 한국어 문구로 분기. 시제/존대 변형을 흡수하기 위해 부분 일치.
*/
private function isUserCancelMessage(string $message): bool
{
if ($message === '') {
return false;
}
foreach (self::USER_CANCEL_MESSAGE_PATTERNS as $pattern) {
if (str_contains($message, $pattern)) {
return true;
}
}
return false;
}
/**
* 상대 경로면 APP_URL 기준으로 절대 URL 화.
*
* PG가 브라우저 POST 로 콜백을 보내는 동안 Apache 가 ProxyPreserveHost Off 등
* 으로 Host 헤더를 localhost 로 바꿔서 PHP 에 전달하는 경우, Laravel 의
* redirect('/path') 가 http://localhost/path 를 생성해버린다. config('app.url')
* (.env 의 APP_URL)을 명시적 base 로 사용하여 도메인을 보존한다.
*/
private function absolutize(string $url): string
{
if (preg_match('#^https?://#i', $url) === 1) {
return $url;
}
$base = rtrim((string) config('app.url'), '/');
$path = $url === '' ? '/' : ($url[0] === '/' ? $url : '/' . $url);
return $base . $path;
}
}
@@ -0,0 +1,124 @@
<?php
declare(strict_types=1);
namespace Plugins\Sirsoft\PayKginicis\Controllers;
use Illuminate\Http\JsonResponse;
use Illuminate\Support\Facades\RateLimiter;
use Modules\Sirsoft\Ecommerce\Services\OrderProcessingService;
use Plugins\Sirsoft\PayKginicis\Concerns\ValidatesCbtOrderContext;
use Plugins\Sirsoft\PayKginicis\Concerns\ValidatesTimestampFreshness;
use Plugins\Sirsoft\PayKginicis\Http\Requests\MobileSignatureRequest;
use Plugins\Sirsoft\PayKginicis\Services\KgInicisApiService;
class MobileSignatureController
{
use ValidatesCbtOrderContext;
use ValidatesTimestampFreshness;
public function __construct(
private readonly KgInicisApiService $apiService,
private readonly OrderProcessingService $orderService,
) {}
/**
* generate
*
* @param MobileSignatureRequest $request
* @return JsonResponse
*/
public function generate(MobileSignatureRequest $request): JsonResponse
{
$validated = $request->validated();
$oid = (string) $validated['oid'];
$price = (int) $validated['price'];
$rateLimitKey = $this->rateLimitKey($request, $oid);
if (RateLimiter::tooManyAttempts($rateLimitKey, 20)) {
return response()->json([
'success' => false,
'message' => 'Too many KG Inicis mobile signature requests. Please try again later.',
], 429);
}
RateLimiter::hit($rateLimitKey, 60);
if (! $this->isTimestampFresh((string) $validated['timestamp'])) {
return response()->json([
'success' => false,
'message' => 'Timestamp is stale or invalid (signature replay protection).',
], 422);
}
$contextError = $this->validateOrderContext($request, $oid, $price);
if ($contextError instanceof JsonResponse) {
return $contextError;
}
if (! $this->apiService->hasMobilePaymentCredentials()) {
return response()->json([
'success' => false,
'message' => 'KG Inicis mobile payment credentials are not configured.',
], 422);
}
$chkfake = $this->apiService->generateMobileChkfake(
$oid,
$price,
$validated['timestamp'],
);
return response()->json([
'data' => [
'chkfake' => $chkfake,
'mobile_payment_url' => $this->apiService->getMobilePaymentUrl(),
],
]);
}
private function validateOrderContext(MobileSignatureRequest $request, string $oid, int $price): ?JsonResponse
{
$order = $this->orderService->findByOrderNumber($oid);
if (! $order) {
return response()->json([
'success' => false,
'message' => 'Order not found.',
], 404);
}
if (! $order->order_status->isBeforePayment()) {
return response()->json([
'success' => false,
'message' => 'Order is not payable.',
], 422);
}
if (strtoupper((string) $order->currency) !== 'KRW') {
return response()->json([
'success' => false,
'message' => 'Standard KG Inicis signature is only available for KRW orders.',
], 422);
}
if (! $this->requestMatchesOrderBuyer($request, $order)) {
return response()->json([
'success' => false,
'message' => 'Order buyer verification failed.',
], 403);
}
if ($price !== $this->expectedPaymentPrice($order)) {
return response()->json([
'success' => false,
'message' => 'Payment amount does not match the order amount.',
], 422);
}
return null;
}
private function rateLimitKey(MobileSignatureRequest $request, string $oid): string
{
return 'sirsoft-pay_kginicis:mobile-signature:' . sha1($request->ip() . '|' . $oid);
}
}
@@ -0,0 +1,741 @@
<?php
declare(strict_types=1);
namespace Plugins\Sirsoft\PayKginicis\Controllers;
use App\Extension\HookManager;
use App\Services\PluginSettingsService;
use Carbon\Carbon;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Http\Response;
use Illuminate\Support\Facades\Log;
use Modules\Sirsoft\Ecommerce\Enums\PaymentMethodEnum;
use Modules\Sirsoft\Ecommerce\Enums\PaymentStatusEnum;
use Modules\Sirsoft\Ecommerce\Exceptions\PaymentAmountMismatchException;
use Modules\Sirsoft\Ecommerce\Helpers\DeviceDetector;
use Modules\Sirsoft\Ecommerce\Models\Order;
use Modules\Sirsoft\Ecommerce\Services\CurrencyConversionService;
use Modules\Sirsoft\Ecommerce\Services\OrderProcessingService;
use Plugins\Sirsoft\PayKginicis\Concerns\IssuesReceiptCookie;
use Plugins\Sirsoft\PayKginicis\Concerns\PreventsReplayCallback;
use Plugins\Sirsoft\PayKginicis\Concerns\ResolvesEasyPaySelection;
use Plugins\Sirsoft\PayKginicis\Concerns\SanitizesPgResponse;
use Plugins\Sirsoft\PayKginicis\Http\Requests\AuthCallbackRequest;
use Plugins\Sirsoft\PayKginicis\Http\Requests\MobileVbankNotifyRequest;
use Plugins\Sirsoft\PayKginicis\Http\Requests\VbankNotifyRequest;
use Plugins\Sirsoft\PayKginicis\Services\KgInicisApiService;
/**
* KG 이니시스 결제 콜백 컨트롤러
*
* KG 이니시스 표준결제창은 2단계 인증 방식입니다:
* 1단계: 브라우저가 POST 콜백으로 authToken + authUrl 전달 → authCallback()
* 2단계: 서버가 authUrl로 최종 승인 요청 → KgInicisApiService::authorizePayment()
*/
class PaymentCallbackController
{
use IssuesReceiptCookie;
use PreventsReplayCallback;
use ResolvesEasyPaySelection;
use SanitizesPgResponse;
private const PLUGIN_IDENTIFIER = 'sirsoft-pay_kginicis';
/**
* 사용자가 결제창을 X / '취소' 로 종료했을 때 KG 이니시스가 전달하는 resultCode 목록.
*
* 사용자 취소는 결제 실패가 아니라 의도된 중단이므로 에러 query 없이 체크아웃으로
* 조용히 복귀시킨다 (NHN KCP 의 CANCEL_RES_CODES 패턴과 동일).
*/
private const CANCEL_RES_CODES = ['2001', '0021', '0022', ''];
private const PC_AUTH_RESPONSE_KEYS = [
'resultCode',
'resultMsg',
'tid',
'payMethod',
'applNum',
'applDate',
'applTime',
'TotPrice',
'totPrice',
'MOID',
'moid',
'mid',
'MID',
'cardCode',
'cardName',
'cardQuota',
'cardInterest',
'goodName',
'goodsName',
'currency',
'currencyCode',
];
private const PC_VBANK_ISSUE_RESPONSE_KEYS = [
'resultCode',
'resultMsg',
'tid',
'payMethod',
'applDate',
'applTime',
'MOID',
'moid',
'mid',
'MID',
'TotPrice',
'totPrice',
'VACT_BankCode',
'VACT_BankName',
'vactBankName',
'VACT_Date',
'VACT_Time',
'VACT_Status',
'goodName',
'goodsName',
];
private const PC_VBANK_NOTIFY_RESPONSE_KEYS = [
'no_tid',
'no_oid',
'id_merchant',
'dt_trans',
'tm_trans',
'cd_bank',
'amt_input',
'nm_inputbank',
];
private const MOBILE_VBANK_NOTIFY_RESPONSE_KEYS = [
'P_STATUS',
'P_TYPE',
'P_TID',
'P_OID',
'P_AMT',
'P_AUTH_DT',
'P_FN_CD1',
'P_FN_NM',
];
public function __construct(
private readonly OrderProcessingService $orderService,
private readonly PluginSettingsService $pluginSettingsService,
private readonly KgInicisApiService $apiService,
) {}
/**
* KG 이니시스 표준결제 인증 콜백을 받아 서버 승인 후 결과 페이지로 리다이렉트합니다.
*
* @param AuthCallbackRequest $request 결제 인증 콜백 요청
* @return RedirectResponse 성공/실패 결과 페이지 리다이렉트
*/
public function authCallback(AuthCallbackRequest $request): RedirectResponse
{
$validated = $request->validated();
$selectedEasyPayMethod = $this->resolveSelectedEasyPayMethod($request);
$resultCode = $validated['resultCode'];
// 주문번호: 구버전 MOID, 신버전 orderNumber 모두 지원
$moid = $validated['MOID'] ?? $validated['orderNumber'] ?? null;
// 결제금액: 콜백에 없을 수 있음 → 서버 승인 후 PG 응답에서 가져옴
$totPrice = isset($validated['TotPrice']) ? (int) $validated['TotPrice'] : null;
Log::info('KG Inicis: callback received', [
'moid' => $moid,
'result_code' => $resultCode,
'idc_name' => $validated['idc_name'] ?? null,
'auth_url' => $validated['authUrl'] ?? null,
'all_fields' => array_keys($request->all()),
'easy_pay' => $this->buildEasyPayLogContext($selectedEasyPayMethod),
]);
if (! $moid) {
Log::error('KG Inicis: order number missing from callback', ['input' => array_keys($request->all())]);
return redirect($this->resolveFailUrl(['error' => 'invalid_params']));
}
// 결제 실패/취소인 경우: authToken/authUrl 없이 올 수 있으므로 먼저 처리
if ($resultCode !== '0000') {
$resultMsg = (string) ($validated['resultMsg'] ?? '');
// 사용자 취소는 결제 실패가 아니라 의도된 중단 — 에러 query 없이 조용히 복귀.
// 1) resultCode 가 KG 이니시스 표준 cancel 코드 목록에 포함되거나
// 2) resultMsg 에 '취소' 또는 '사용자' 키워드가 포함된 경우 (버전별 코드 차이 대응)
$isUserCancel = in_array($resultCode, self::CANCEL_RES_CODES, true)
|| str_contains($resultMsg, '취소')
|| str_contains($resultMsg, '사용자');
Log::info('KG Inicis: auth result non-success', [
'moid' => $moid,
'result_code' => $resultCode,
'result_msg' => $resultMsg,
'is_user_cancel' => $isUserCancel,
]);
if ($isUserCancel) {
// 에러 query 미부착 → 체크아웃 페이지가 toast/error 분기를 타지 않음
return redirect($this->resolveFailUrl());
}
return redirect($this->resolveFailUrl([
'error' => $resultCode,
'message' => $resultMsg,
'orderId' => $moid,
]));
}
// 결제 성공(0000) 이후: authToken, authUrl, idc_name 필수
$authToken = $validated['authToken'] ?? null;
$idcName = $validated['idc_name'] ?? null;
// authUrl 또는 checkAckUrl (버전에 따라 다름)
$receivedAuthUrl = $validated['authUrl'] ?? $validated['checkAckUrl'] ?? null;
$receivedNetCancelUrl = $validated['netCancelUrl'] ?? null;
if (! $authToken || ! $idcName || ! $receivedAuthUrl) {
Log::error('KG Inicis: missing required fields on success callback', [
'moid' => $moid,
'idc_name' => $idcName,
'auth_url' => $receivedAuthUrl,
'has_token' => (bool) $authToken,
]);
return redirect($this->resolveFailUrl(['error' => 'missing_fields', 'orderId' => $moid]));
}
// idc_name + authUrl 화이트리스트 검증 (PC/모바일 URL 모두 허용, SSRF 방어)
if (! $this->apiService->isValidIdcAuthUrl($idcName, $receivedAuthUrl)) {
Log::error('KG Inicis: authUrl not in whitelist (possible SSRF attempt)', [
'moid' => $moid,
'idc_name' => $idcName,
'received' => $receivedAuthUrl,
]);
return redirect($this->resolveFailUrl(['error' => 'auth_url_invalid', 'orderId' => $moid]));
}
// 화이트리스트 검증 통과 → 수신된 URL을 그대로 사용 (PC/모바일 자동 대응)
$authUrl = $receivedAuthUrl;
$netCancelUrl = $this->apiService->resolveIdcNetCancelUrl($idcName);
$tid = '';
try {
$order = $this->orderService->findByOrderNumber($moid);
if (! $order) {
Log::error('KG Inicis: order not found', ['moid' => $moid]);
return redirect($this->resolveFailUrl(['error' => 'order_not_found', 'orderId' => $moid]));
}
HookManager::doAction('sirsoft-pay_kginicis.payment.before_authorize', $order, $validated);
$pgResponse = $this->apiService->authorizePayment($authUrl, $authToken);
HookManager::doAction('sirsoft-pay_kginicis.payment.after_authorize', $order, $pgResponse);
$pgResultCode = $pgResponse['resultCode'] ?? '';
if ($pgResultCode !== '0000') {
Log::warning('KG Inicis: authorize failed', [
'moid' => $moid,
'result_code' => $pgResultCode,
'result_msg' => $pgResponse['resultMsg'] ?? '',
]);
$this->orderService->failPayment($order, $pgResultCode, $pgResponse['resultMsg'] ?? '');
return redirect($this->resolveFailUrl([
'error' => $pgResultCode,
'message' => $pgResponse['resultMsg'] ?? '',
'orderId' => $moid,
]));
}
$tid = (string) ($pgResponse['tid'] ?? '');
// 가상계좌: completePayment 없이 계좌 정보만 저장 (입금 통보 시 completePayment)
if (($pgResponse['payMethod'] ?? '') === 'VBank') {
$this->handleVbankIssued($order, $pgResponse, $tid, $request);
$this->queueReceiptCookie($moid);
return redirect($this->resolveSuccessUrl($moid));
}
// Replay 가드: 동일 tid 가 이미 paid 상태면 중복 처리하지 않고 성공 페이지로 복귀
if ($this->wasAlreadyPaid($tid)) {
$this->logReplayDetected($tid, $moid, 'PC authCallback (card)');
$this->queueReceiptCookie($moid);
return redirect($this->resolveSuccessUrl($moid));
}
// TotPrice 가 콜백에 없으면 PG 승인 응답의 TotPrice 사용
if ($totPrice === null) {
$totPrice = (int) ($pgResponse['TotPrice'] ?? $pgResponse['totPrice'] ?? 0);
}
$embeddedPgProvider = $this->resolveEmbeddedPgProvider($selectedEasyPayMethod);
Log::info('KG Inicis: completing card payment', [
'moid' => $moid,
'tid' => $tid,
'pg_pay_method' => $pgResponse['payMethod'] ?? null,
'easy_pay' => $this->buildEasyPayLogContext($selectedEasyPayMethod),
]);
$this->orderService->completePayment($order, [
'transaction_id' => $tid,
'card_approval_number' => $pgResponse['applNum'] ?? null,
'card_number_masked' => $pgResponse['cardNum'] ?? null,
'card_name' => $pgResponse['cardName'] ?? null,
'card_installment_months' => (int) ($pgResponse['cardQuota'] ?? 0),
'is_interest_free' => false,
'embedded_pg_provider' => $embeddedPgProvider,
'receipt_url' => null,
'payment_meta' => array_merge([
'result_code' => $pgResultCode,
'pay_method' => $pgResponse['payMethod'] ?? null,
'auth_date' => $pgResponse['applDate'] ?? null,
'mid' => $this->apiService->getMid(),
'is_test_mode' => $this->apiService->isTestMode(),
'pg_response_sanitized' => true,
'pg_raw_response' => $this->sanitizePgResponse($pgResponse, self::PC_AUTH_RESPONSE_KEYS),
], $this->buildEasyPayPaymentMeta($selectedEasyPayMethod)),
'payment_device' => DeviceDetector::detect($request),
], $totPrice);
$order->payment()->update(['pg_provider' => 'kginicis']);
$this->queueReceiptCookie($moid);
return redirect($this->resolveSuccessUrl($moid));
} catch (PaymentAmountMismatchException $e) {
Log::error('KG Inicis: amount mismatch', [
'moid' => $moid,
'expected' => $e->getExpectedAmount(),
'actual' => $e->getActualAmount(),
]);
$this->apiService->sendNetCancel($netCancelUrl, $authToken);
return redirect($this->resolveFailUrl(['error' => 'amount_mismatch', 'orderId' => $moid]));
} catch (\Exception $e) {
Log::error('KG Inicis: authorize exception', [
'moid' => $moid,
'tid' => $tid,
'error' => $e->getMessage(),
]);
if ($this->wasAlreadyPaid($tid)) {
Log::warning('KG Inicis: local payment already completed, net cancel skipped after exception', [
'moid' => $moid,
'tid' => $tid,
'error' => $e->getMessage(),
]);
$this->queueReceiptCookie($moid);
return redirect($this->resolveSuccessUrl($moid));
}
$this->apiService->sendNetCancel($netCancelUrl, $authToken);
return redirect($this->resolveFailUrl([
'error' => 'authorize_failed',
'message' => $e->getMessage(),
'orderId' => $moid,
]));
}
}
/**
* PC 가상계좌 입금통보를 받아 입금대기 주문을 결제완료로 전환합니다.
*
* @param VbankNotifyRequest $request 가상계좌 입금통보 요청
* @return Response KG 이니시스에 반환할 통보 처리 결과 응답
*/
public function vbankNotify(VbankNotifyRequest $request): Response
{
$validated = $request->validated();
$tid = (string) $validated['no_tid'];
$moid = (string) $validated['no_oid'];
$amt = (int) $validated['amt_input'];
Log::info('KG Inicis: PC vbank deposit notify received', [
'tid' => $tid,
'moid' => $moid,
'amt' => $amt,
'bank' => $validated['nm_inputbank'] ?? null,
]);
try {
$order = $this->orderService->findByOrderNumber($moid);
if (! $order) {
Log::error('KG Inicis: PC vbank notify - order not found', ['moid' => $moid, 'tid' => $tid]);
return response('FAIL', 200)->header('Content-Type', 'text/plain');
}
if ($this->wasAlreadyPaid($tid)) {
$this->logReplayDetected($tid, $moid, 'PC vbankNotify');
return response('OK', 200)->header('Content-Type', 'text/plain');
}
if (! $this->validateVbankNotifyContext($order, [
'tid' => $tid,
'mid' => (string) ($validated['id_merchant'] ?? ''),
'amount' => $amt,
'account' => (string) ($validated['no_vacct'] ?? ''),
'source' => 'PC vbankNotify',
])) {
return response('FAIL', 200)->header('Content-Type', 'text/plain');
}
$this->orderService->completePayment($order, [
'transaction_id' => $tid,
'payment_meta' => [
'vbank_num' => $validated['no_vacct'] ?? null,
'vbank_name' => $validated['nm_inputbank'] ?? null,
'depositor_name' => $validated['nm_input'] ?? null,
'deposit_date' => ($validated['dt_trans'] ?? '').($validated['tm_trans'] ?? ''),
'bank_code' => $validated['cd_bank'] ?? null,
'mid' => $this->apiService->getMid(),
'is_test_mode' => $this->apiService->isTestMode(),
'pg_response_sanitized' => true,
'pg_raw_response' => $this->sanitizePgResponse($validated, self::PC_VBANK_NOTIFY_RESPONSE_KEYS),
],
], $amt);
$order->payment()->update(['pg_provider' => 'kginicis']);
Log::info('KG Inicis: PC vbank deposit confirmed', ['tid' => $tid, 'moid' => $moid, 'amt' => $amt]);
return response('OK', 200)->header('Content-Type', 'text/plain');
} catch (\Exception $e) {
Log::error('KG Inicis: PC vbank notify failed', [
'tid' => $tid,
'moid' => $moid,
'error' => $e->getMessage(),
]);
return response('FAIL', 200)->header('Content-Type', 'text/plain');
}
}
/**
* 모바일 가상계좌 입금통보를 받아 입금대기 주문을 결제완료로 전환합니다.
*
* @param MobileVbankNotifyRequest $request 모바일 가상계좌 입금통보 요청
* @return Response KG 이니시스에 반환할 통보 처리 결과 응답
*/
public function mobileVbankNotify(MobileVbankNotifyRequest $request): Response
{
$validated = $request->validated();
$pStatus = (string) $validated['P_STATUS'];
$pType = (string) $validated['P_TYPE'];
$tid = (string) $validated['P_TID'];
$moid = (string) $validated['P_OID'];
$amt = (int) $validated['P_AMT'];
// P_STATUS == "02" (입금통보) + P_TYPE == "VBANK" 만 처리
if ($pStatus !== '02' || $pType !== 'VBANK') {
Log::info('KG Inicis: mobile vbank notify - not a deposit, ignored', [
'tid' => $tid,
'P_STATUS' => $pStatus,
'P_TYPE' => $pType,
]);
return response('OK', 200)->header('Content-Type', 'text/plain');
}
Log::info('KG Inicis: mobile vbank deposit notify received', [
'tid' => $tid,
'moid' => $moid,
'amt' => $amt,
'bank' => $validated['P_FN_NM'] ?? null,
]);
try {
$order = $this->orderService->findByOrderNumber($moid);
if (! $order) {
Log::error('KG Inicis: mobile vbank notify - order not found', ['moid' => $moid, 'tid' => $tid]);
return response('FAIL', 200)->header('Content-Type', 'text/plain');
}
if ($this->wasAlreadyPaid($tid)) {
$this->logReplayDetected($tid, $moid, 'mobile vbankNotify');
return response('OK', 200)->header('Content-Type', 'text/plain');
}
if (! $this->validateVbankNotifyContext($order, [
'tid' => $tid,
'mid' => (string) ($validated['P_MID'] ?? ''),
'amount' => $amt,
'account' => $this->extractMobileVbankAccount((string) ($validated['P_RMESG1'] ?? '')),
'source' => 'mobile vbankNotify',
])) {
return response('FAIL', 200)->header('Content-Type', 'text/plain');
}
$this->orderService->completePayment($order, [
'transaction_id' => $tid,
'payment_meta' => [
'vbank_name' => $validated['P_FN_NM'] ?? null,
'depositor_name' => $validated['P_UNAME'] ?? null,
'deposit_date' => $validated['P_AUTH_DT'] ?? null,
'bank_code' => $validated['P_FN_CD1'] ?? null,
'mid' => $this->apiService->getMid(),
'is_test_mode' => $this->apiService->isTestMode(),
'pg_response_sanitized' => true,
'pg_raw_response' => $this->sanitizePgResponse($validated, self::MOBILE_VBANK_NOTIFY_RESPONSE_KEYS),
],
'payment_device' => 'mobile',
], $amt);
$order->payment()->update(['pg_provider' => 'kginicis']);
Log::info('KG Inicis: mobile vbank deposit confirmed', ['tid' => $tid, 'moid' => $moid, 'amt' => $amt]);
return response('OK', 200)->header('Content-Type', 'text/plain');
} catch (\Exception $e) {
Log::error('KG Inicis: mobile vbank notify failed', [
'tid' => $tid,
'moid' => $moid,
'error' => $e->getMessage(),
]);
return response('FAIL', 200)->header('Content-Type', 'text/plain');
}
}
/**
* 입금통보가 실제로 이 주문에서 발급한 가상계좌 결제 건인지 확인한다.
*
* KG 이니시스 PC 노티는 별도 서명 필드를 제공하지 않으므로, IP 화이트리스트에 더해
* 결제행에 저장된 발급 시점 TID/MID/계좌/금액을 대조해 위조 통보 표면을 줄인다.
*
* @param array{tid:string,mid:string,amount:int,account:string,source:string} $notify
*/
private function validateVbankNotifyContext(Order $order, array $notify): bool
{
$payment = $order->payment()->first();
$meta = is_array($payment?->payment_meta) ? $payment->payment_meta : [];
$source = $notify['source'];
if (! $payment) {
Log::warning('KG Inicis: vbank notify rejected - payment missing', [
'source' => $source,
'moid' => $order->order_number,
'tid' => $notify['tid'],
]);
return false;
}
$paymentStatus = $this->enumValue($payment->payment_status);
if ($paymentStatus !== PaymentStatusEnum::WAITING_DEPOSIT->value) {
Log::warning('KG Inicis: vbank notify rejected - payment is not waiting deposit', [
'source' => $source,
'moid' => $order->order_number,
'tid' => $notify['tid'],
'payment_status' => $paymentStatus,
]);
return false;
}
$paymentMethod = $this->enumValue($payment->payment_method);
if ($paymentMethod !== PaymentMethodEnum::VBANK->value) {
Log::warning('KG Inicis: vbank notify rejected - payment method mismatch', [
'source' => $source,
'moid' => $order->order_number,
'tid' => $notify['tid'],
'payment_method' => $paymentMethod,
]);
return false;
}
$expectedTid = trim((string) $payment->transaction_id);
if ($expectedTid === '' || ! hash_equals($expectedTid, $notify['tid'])) {
Log::warning('KG Inicis: vbank notify rejected - tid mismatch', [
'source' => $source,
'moid' => $order->order_number,
'received_tid' => $notify['tid'],
'expected_tid' => $expectedTid,
]);
return false;
}
$expectedMid = trim((string) ($meta['mid'] ?? $this->apiService->getMid()));
if ($expectedMid !== '' && ! hash_equals($expectedMid, $notify['mid'])) {
Log::warning('KG Inicis: vbank notify rejected - mid mismatch', [
'source' => $source,
'moid' => $order->order_number,
'tid' => $notify['tid'],
'received_mid' => $notify['mid'],
'expected_mid' => $expectedMid,
]);
return false;
}
// 결제 청구액 SSoT = 결제 통화(order_currency) 환산액 (buildPgPaymentData 와 동일 기준).
// base≠결제 통화에서 PG 통보 금액(환산 통화)과 단위가 일치하도록 한다.
$expectedAmount = app(CurrencyConversionService::class)->resolveOrderPaymentChargeAmount($order);
if ($expectedAmount > 0 && $notify['amount'] !== $expectedAmount) {
Log::warning('KG Inicis: vbank notify rejected - amount mismatch', [
'source' => $source,
'moid' => $order->order_number,
'tid' => $notify['tid'],
'received_amount' => $notify['amount'],
'expected_amount' => $expectedAmount,
]);
return false;
}
$expectedAccount = preg_replace('/\D+/', '', (string) $payment->vbank_number);
$receivedAccount = preg_replace('/\D+/', '', $notify['account']);
if ($expectedAccount !== '' && $receivedAccount !== '' && ! hash_equals($expectedAccount, $receivedAccount)) {
Log::warning('KG Inicis: vbank notify rejected - account mismatch', [
'source' => $source,
'moid' => $order->order_number,
'tid' => $notify['tid'],
'received_account_suffix' => substr($receivedAccount, -4),
'expected_account_suffix' => substr($expectedAccount, -4),
]);
return false;
}
return true;
}
private function extractMobileVbankAccount(string $message): string
{
$parts = explode('|', $message);
return trim((string) ($parts[0] ?? ''));
}
private function enumValue(mixed $value): string
{
if ($value instanceof \BackedEnum) {
return (string) $value->value;
}
return (string) $value;
}
private function resolveSuccessUrl(string $orderId): string
{
$settings = $this->pluginSettingsService->get(self::PLUGIN_IDENTIFIER) ?? [];
$urlTemplate = $settings['redirect_success_url'] ?? '/shop/orders/{orderId}/complete';
return $this->absolutize(str_replace('{orderId}', $orderId, $urlTemplate));
}
private function resolveFailUrl(array $queryParams = []): string
{
$settings = $this->pluginSettingsService->get(self::PLUGIN_IDENTIFIER) ?? [];
$baseUrl = $this->absolutize($settings['redirect_fail_url'] ?? '/shop/checkout');
if (empty($queryParams)) {
return $baseUrl;
}
$query = http_build_query(array_filter($queryParams));
$separator = str_contains($baseUrl, '?') ? '&' : '?';
return $baseUrl.$separator.$query;
}
/**
* 상대 경로면 APP_URL 기준으로 절대 URL 화.
*
* PG가 브라우저 POST 로 콜백을 보내는 동안 Apache 가 ProxyPreserveHost Off 등
* 으로 Host 헤더를 localhost 로 바꿔서 PHP 에 전달하는 경우, Laravel 의
* redirect('/path') 가 http://localhost/path 를 생성해버린다. config('app.url')
* (.env 의 APP_URL)을 명시적 base 로 사용하여 도메인을 보존한다.
*/
private function absolutize(string $url): string
{
if (preg_match('#^https?://#i', $url) === 1) {
return $url;
}
$base = rtrim((string) config('app.url'), '/');
$path = $url === '' ? '/' : ($url[0] === '/' ? $url : '/'.$url);
return $base.$path;
}
/**
* 가상계좌 발급 처리 (completePayment 없이 계좌 정보만 저장)
*
* KG 이니시스 authCallback 에서 payMethod=VBank 로 판별된 경우 호출.
* 실제 결제 완료(completePayment)는 입금 통보(vbankNotify) 시점에 처리.
*/
private function handleVbankIssued(Order $order, array $pgResponse, string $tid, Request $request): void
{
$vactDate = $pgResponse['VACT_Date'] ?? null;
$vactTime = $pgResponse['VACT_Time'] ?? '235959';
$vbankDueAt = null;
if ($vactDate && strlen($vactDate) === 8) {
try {
$vbankDueAt = Carbon::createFromFormat('YmdHis', $vactDate.$vactTime);
} catch (\Exception) {
$vbankDueAt = null;
}
}
$order->payment()->update(array_filter([
'pg_provider' => 'kginicis',
'payment_status' => PaymentStatusEnum::WAITING_DEPOSIT,
'transaction_id' => $tid ?: null,
'vbank_code' => $pgResponse['VACT_BankCode'] ?? null, // KG 이니시스 은행코드 (e.g. 89=케이뱅크)
'vbank_name' => $pgResponse['vactBankName'] ?? null, // 입금은행명
'vbank_number' => $pgResponse['VACT_Num'] ?? null, // 가상계좌번호
'vbank_holder' => $pgResponse['VACT_Name'] ?? null, // 예금주명
'vbank_due_at' => $vbankDueAt,
'vbank_issued_at' => now(),
'payment_device' => DeviceDetector::detect($request),
'payment_meta' => [
'result_code' => '0000',
'pay_method' => 'VBank',
'auth_date' => $pgResponse['applDate'] ?? null,
'mid' => $this->apiService->getMid(),
'is_test_mode' => $this->apiService->isTestMode(),
'pg_response_sanitized' => true,
'pg_raw_response' => $this->sanitizePgResponse($pgResponse, self::PC_VBANK_ISSUE_RESPONSE_KEYS),
],
], fn ($v) => $v !== null));
Log::info('KG Inicis: vbank account issued', [
'moid' => $order->order_number,
'tid' => $tid,
'vbank_name' => $pgResponse['vactBankName'] ?? null,
'vbank_number' => $pgResponse['VACT_Num'] ?? null,
'vbank_due_at' => $vbankDueAt?->toDateTimeString(),
]);
}
}
@@ -0,0 +1,69 @@
<?php
declare(strict_types=1);
namespace Plugins\Sirsoft\PayKginicis\Controllers;
use App\Http\Controllers\Controller;
use App\Services\PluginSettingsService;
use Illuminate\Http\Response;
class PaymentCloseController extends Controller
{
private const PLUGIN_IDENTIFIER = 'sirsoft-pay_kginicis';
private const CLOSE_JS_URL_TEST = 'https://stgstdpay.inicis.com/stdjs/INIStdPay_close.js';
private const CLOSE_JS_URL_LIVE = 'https://stdpay.inicis.com/stdjs/INIStdPay_close.js';
public function __construct(
private readonly PluginSettingsService $pluginSettingsService,
) {}
public function show(): Response
{
$settings = $this->pluginSettingsService->get(self::PLUGIN_IDENTIFIER) ?? [];
$closeJsUrl = ($settings['is_test_mode'] ?? true)
? self::CLOSE_JS_URL_TEST
: self::CLOSE_JS_URL_LIVE;
$html = <<<HTML
<!DOCTYPE html>
<html lang="ko">
<head>
<meta charset="UTF-8">
<title>KG 이니시스 결제창 닫기</title>
<script>
(function () {
var payload = {
source: 'sirsoft-pay_kginicis',
type: 'payment-window-closed',
reason: 'inicis-close-url'
};
var targetOrigin = window.location.origin;
try {
if (window.parent && window.parent !== window) {
window.parent.postMessage(payload, targetOrigin);
}
if (window.opener && !window.opener.closed) {
window.opener.postMessage(payload, targetOrigin);
}
} catch (error) {
// 결제창 닫기 페이지는 상태 알림 실패와 무관하게 KG close script를 실행한다.
}
})();
</script>
<script src="{$closeJsUrl}" charset="UTF-8"></script>
</head>
<body></body>
</html>
HTML;
return response($html, 200, [
'Content-Type' => 'text/html; charset=UTF-8',
'Cache-Control' => 'no-store, no-cache, must-revalidate, max-age=0',
]);
}
}
@@ -0,0 +1,144 @@
<?php
declare(strict_types=1);
namespace Plugins\Sirsoft\PayKginicis\Controllers;
use App\Helpers\ResponseHelper;
use Illuminate\Http\JsonResponse;
use Illuminate\Support\Facades\RateLimiter;
use Modules\Sirsoft\Ecommerce\Models\Order;
use Modules\Sirsoft\Ecommerce\Services\OrderProcessingService;
use Plugins\Sirsoft\PayKginicis\Concerns\ResolvesEasyPaySelection;
use Plugins\Sirsoft\PayKginicis\Concerns\ValidatesCbtOrderContext;
use Plugins\Sirsoft\PayKginicis\Http\Requests\PaymentCloseReportRequest;
class PaymentCloseReportController
{
use ResolvesEasyPaySelection;
use ValidatesCbtOrderContext;
private const FAILURE_CODE = 'USER_CANCEL';
private const FAILURE_MESSAGE = '사용자가 KG 이니시스 결제창을 닫았습니다.';
public function __construct(
private readonly OrderProcessingService $orderService,
) {}
/**
* PC 표준결제창 닫힘 보고를 검증하고 결제 실패/취소 이력을 기록합니다.
*
* @param PaymentCloseReportRequest $request 결제창 닫힘 보고 요청
* @return JsonResponse 닫힘 보고 처리 결과
*/
public function store(PaymentCloseReportRequest $request): JsonResponse
{
$validated = $request->validated();
$oid = $validated['oid'];
$price = (int) $validated['price'];
$rateLimitKey = $this->rateLimitKey($request, $oid);
if (RateLimiter::tooManyAttempts($rateLimitKey, 20)) {
return ResponseHelper::error('messages.failed', 429, [
'message' => ['Too many KG Inicis payment close reports. Please try again later.'],
]);
}
RateLimiter::hit($rateLimitKey, 60);
$order = $this->orderService->findByOrderNumber($oid);
if (! $order) {
return ResponseHelper::error('messages.failed', 404, [
'message' => ['Order not found.'],
]);
}
if (strtoupper((string) $order->currency) !== 'KRW') {
return ResponseHelper::error('messages.failed', 422, [
'message' => ['Standard KG Inicis close report is only available for KRW orders.'],
]);
}
if (! $this->requestMatchesOrderBuyer($request, $order)) {
return ResponseHelper::error('messages.failed', 403, [
'message' => ['Order buyer verification failed.'],
]);
}
if ($price !== $this->expectedPaymentPrice($order)) {
return ResponseHelper::error('messages.failed', 422, [
'message' => ['Payment amount does not match the order amount.'],
]);
}
if (! $order->order_status->isBeforePayment()) {
return ResponseHelper::success('messages.success', [
'status' => 'ignored',
'reason' => 'order_not_payable',
]);
}
// 결제 성공 콜백(authorize)과 결제창 닫힘 보고가 경쟁할 때, 카드 주문은 승인 직전까지
// order_status=PENDING_ORDER 라 위 가드를 통과한다. payment_status 가 이미 PAID 면 결제가
// 성공한 것이므로 실패 처리하지 않는다(failPayment 가 옵션을 취소로 덮어 주문/옵션 상태가
// 어긋나는 race 차단). failPayment 자체에도 동일 가드가 있으나, 여기서 차단해 불필요한
// 마일리지 복원 시도·결제취소 이력 기록까지 미연에 방지한다.
if ($order->payment?->isPaid()) {
return ResponseHelper::success('messages.success', [
'status' => 'ignored',
'reason' => 'payment_already_paid',
]);
}
$selectedEasyPayMethod = $this->normalizeEasyPayMethod(
is_string($validated['payment_method'] ?? null) ? $validated['payment_method'] : null,
);
$failedOrder = $this->orderService->failPayment(
$order,
self::FAILURE_CODE,
self::FAILURE_MESSAGE,
);
$closeReason = trim((string) ($validated['reason'] ?? ''));
$this->persistEasyPayCloseContext($failedOrder, $selectedEasyPayMethod);
$this->orderService->recordPaymentCancellation(
$failedOrder,
self::FAILURE_CODE,
$closeReason !== '' ? $closeReason : self::FAILURE_MESSAGE,
);
return ResponseHelper::success('messages.success', [
'status' => 'recorded',
]);
}
private function rateLimitKey(PaymentCloseReportRequest $request, string $oid): string
{
return 'sirsoft-pay_kginicis:payment-close-report:'.sha1($request->ip().'|'.$oid);
}
private function persistEasyPayCloseContext(Order $order, ?string $selectedEasyPayMethod): void
{
if ($selectedEasyPayMethod === null || ! $order->exists) {
return;
}
$payment = $order->payment()->first();
if (! $payment) {
return;
}
$existingMeta = is_array($payment->payment_meta) ? $payment->payment_meta : [];
$payment->update([
'embedded_pg_provider' => $this->resolveEmbeddedPgProvider($selectedEasyPayMethod),
'payment_meta' => array_merge(
$existingMeta,
$this->buildEasyPayPaymentMeta($selectedEasyPayMethod),
['close_report_payment_method' => $selectedEasyPayMethod],
),
]);
}
}
@@ -0,0 +1,125 @@
<?php
declare(strict_types=1);
namespace Plugins\Sirsoft\PayKginicis\Controllers;
use Illuminate\Http\JsonResponse;
use Illuminate\Support\Facades\RateLimiter;
use Modules\Sirsoft\Ecommerce\Services\OrderProcessingService;
use Plugins\Sirsoft\PayKginicis\Concerns\ValidatesCbtOrderContext;
use Plugins\Sirsoft\PayKginicis\Concerns\ValidatesTimestampFreshness;
use Plugins\Sirsoft\PayKginicis\Http\Requests\SignatureRequest;
use Plugins\Sirsoft\PayKginicis\Services\KgInicisApiService;
class PaymentSignatureController
{
use ValidatesCbtOrderContext;
use ValidatesTimestampFreshness;
public function __construct(
private readonly KgInicisApiService $apiService,
private readonly OrderProcessingService $orderService,
) {}
/**
* generate
*
* @param SignatureRequest $request
* @return JsonResponse
*/
public function generate(SignatureRequest $request): JsonResponse
{
$validated = $request->validated();
$oid = $validated['oid'];
$price = (int) $validated['price'];
$timestamp = $validated['timestamp'];
$rateLimitKey = $this->rateLimitKey($request, $oid);
if (RateLimiter::tooManyAttempts($rateLimitKey, 20)) {
return response()->json([
'success' => false,
'message' => 'Too many KG Inicis signature requests. Please try again later.',
], 429);
}
RateLimiter::hit($rateLimitKey, 60);
if (! $this->isTimestampFresh($timestamp)) {
return response()->json([
'success' => false,
'message' => 'Timestamp is stale or invalid (signature replay protection).',
], 422);
}
$contextError = $this->validateOrderContext($request, $oid, $price);
if ($contextError instanceof JsonResponse) {
return $contextError;
}
if (! $this->apiService->hasStandardPaymentCredentials()) {
return response()->json([
'success' => false,
'message' => 'KG Inicis standard payment credentials are not configured.',
], 422);
}
$signature = $this->apiService->generateSignature($oid, $price, $timestamp);
$verification = $this->apiService->generateVerification($oid, $price, $timestamp);
$mKey = $this->apiService->getMKey();
return response()->json([
'data' => [
'signature' => $signature,
'verification' => $verification,
'mKey' => $mKey,
],
]);
}
private function validateOrderContext(SignatureRequest $request, string $oid, int $price): ?JsonResponse
{
$order = $this->orderService->findByOrderNumber($oid);
if (! $order) {
return response()->json([
'success' => false,
'message' => 'Order not found.',
], 404);
}
if (! $order->order_status->isBeforePayment()) {
return response()->json([
'success' => false,
'message' => 'Order is not payable.',
], 422);
}
if (strtoupper((string) $order->currency) !== 'KRW') {
return response()->json([
'success' => false,
'message' => 'Standard KG Inicis signature is only available for KRW orders.',
], 422);
}
if (! $this->requestMatchesOrderBuyer($request, $order)) {
return response()->json([
'success' => false,
'message' => 'Order buyer verification failed.',
], 403);
}
if ($price !== $this->expectedPaymentPrice($order)) {
return response()->json([
'success' => false,
'message' => 'Payment amount does not match the order amount.',
], 422);
}
return null;
}
private function rateLimitKey(SignatureRequest $request, string $oid): string
{
return 'sirsoft-pay_kginicis:signature:' . sha1($request->ip() . '|' . $oid);
}
}
@@ -0,0 +1,277 @@
<?php
declare(strict_types=1);
namespace Plugins\Sirsoft\PayKginicis\Controllers;
use App\Http\Controllers\Controller;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Http\Response;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Plugins\Sirsoft\PayKginicis\Services\KgInicisApiService;
/**
* KG 이니시스 에스크로 구매결정 컨트롤러 (사용자용)
*
* PC: INIStdPay_escrow_conf.js 팝업 → POST returnUrl
* 모바일: mobile.inicis.com/smart/payment/ 자동 submit → POST P_NEXT_URL
*/
class UserEscrowConfirmController extends Controller
{
private const PC_JS_URL_TEST = 'https://stgstdpay.inicis.com/stdjs/INIStdPay_escrow_conf.js';
private const PC_JS_URL_LIVE = 'https://stdpay.inicis.com/stdjs/INIStdPay_escrow_conf.js';
private const MOBILE_PAY_URL = 'https://mobile.inicis.com/smart/payment/';
public function __construct(
private readonly KgInicisApiService $apiService,
) {}
/**
* show
*
* @param Request $request
* @param string $orderNumber
* @return Response
*/
public function show(Request $request, string $orderNumber): Response
{
$payment = $this->findEscrowPayment($orderNumber, (int) Auth::id());
if (! $payment) {
abort(404);
}
$this->apiService->useEscrowCredentials(true);
if ($this->isMobile($request)) {
return $this->mobileConfirmPage($payment->transaction_id);
}
return $this->pcConfirmPage($payment->transaction_id);
}
/**
* pcReturn
*
* @param Request $request
* @return Response
*/
public function pcReturn(Request $request): Response
{
$resultCode = (string) $request->input('ResultCode', '');
$tid = (string) $request->input('tid', '');
Log::info('KG Inicis: escrow PC confirm return', [
'result_code' => $resultCode,
'tid' => $tid,
]);
$this->saveConfirmResult($tid, [
'type' => $resultCode === '00' ? 'confirm' : 'deny',
'result_code' => $resultCode,
'cnf_date' => (string) $request->input('CNF_Date', ''),
'cnf_time' => (string) $request->input('CNF_Time', ''),
'dny_date' => (string) $request->input('DNY_Date', ''),
'dny_time' => (string) $request->input('DNY_Time', ''),
'dny_msg' => (string) $request->input('DNY_DenyMsg', ''),
]);
// 팝업 닫기 + 부모 창 새로고침
return $this->htmlResponse(
'<script>try{window.opener&&window.opener.location.reload();}catch(e){}window.close();</script>'
);
}
/**
* close
*
* @return Response
*/
public function close(): Response
{
return $this->htmlResponse('<script>window.close();</script>');
}
/**
* mobileReturn
*
* @param Request $request
* @return RedirectResponse
*/
public function mobileReturn(Request $request): RedirectResponse
{
$status = (string) $request->input('P_STATUS', '');
$tid = (string) $request->input('P_ESCROW_TID', '');
$clStatus = (string) $request->input('P_CL_STATUS', '');
$rmesg = (string) $request->input('P_RMESG1', '');
Log::info('KG Inicis: escrow mobile confirm return', [
'status' => $status,
'tid' => $tid,
'cl_status' => $clStatus,
]);
$orderNumber = $this->saveConfirmResult($tid, [
'type' => $status === '00' ? 'confirm' : 'deny',
'result_code' => $status,
'cl_status' => $clStatus,
'result_msg' => $rmesg,
]);
return redirect($orderNumber ? '/mypage/orders/' . $orderNumber : '/mypage/orders');
}
// ──────────────────────────── Private ────────────────────────────
private function pcConfirmPage(string $tid): Response
{
$isTest = $this->apiService->isTestMode();
$mid = $this->apiService->getMid();
$mKey = $this->apiService->getEscrowConfirmMKey();
$timestamp = (string) round(microtime(true) * 1000);
$jsUrl = $isTest ? self::PC_JS_URL_TEST : self::PC_JS_URL_LIVE;
$returnUrl = url('/plugins/sirsoft-pay_kginicis/payment/escrow-confirm/pc/return');
$closeUrl = url('/plugins/sirsoft-pay_kginicis/payment/escrow-confirm/close');
$html = <<<HTML
<!DOCTYPE html>
<html lang="ko">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width,initial-scale=1.0">
<title>에스크로 구매결정</title>
<script src="{$jsUrl}" charset="UTF-8"></script>
<script>window.onload = function() { INIStdPay.pay('escrow_confirm_form'); };</script>
<style>
body { font-family: sans-serif; display: flex; align-items: center;
justify-content: center; height: 100vh; margin: 0; background: #f5f5f5; }
p { color: #666; font-size: 14px; }
</style>
</head>
<body>
<p>에스크로 구매결정 창을 준비 중입니다...</p>
<form id="escrow_confirm_form" method="post">
<input type="hidden" name="version" value="1.0">
<input type="hidden" name="mid" value="{$mid}">
<input type="hidden" name="tid" value="{$tid}">
<input type="hidden" name="timestamp" value="{$timestamp}">
<input type="hidden" name="mKey" value="{$mKey}">
<input type="hidden" name="currency" value="WON">
<input type="hidden" name="returnUrl" value="{$returnUrl}">
<input type="hidden" name="closeUrl" value="{$closeUrl}">
<input type="hidden" name="acceptmethod" value="">
</form>
</body>
</html>
HTML;
return $this->htmlResponse($html);
}
private function mobileConfirmPage(string $tid): Response
{
$mid = $this->apiService->getMid();
$nextUrl = url('/plugins/sirsoft-pay_kginicis/payment/escrow-confirm/mobile/return');
$payUrl = self::MOBILE_PAY_URL;
$html = <<<HTML
<!DOCTYPE html>
<html lang="ko">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width,initial-scale=1.0">
<title>에스크로 구매결정</title>
<style>
body { font-family: sans-serif; display: flex; align-items: center;
justify-content: center; height: 100vh; margin: 0; background: #f5f5f5; }
p { color: #666; font-size: 14px; }
</style>
</head>
<body>
<p>에스크로 구매결정 페이지로 이동 중입니다...</p>
<form id="mobile_confirm_form" name="mobileweb" method="post"
action="{$payUrl}" accept-charset="euc-kr">
<input type="hidden" name="P_INI_PAYMENT" value="ESCROWCONFIRM">
<input type="hidden" name="P_MID" value="{$mid}">
<input type="hidden" name="P_ESCROW_TID" value="{$tid}">
<input type="hidden" name="P_NEXT_URL" value="{$nextUrl}">
<input type="hidden" name="P_RESERVED" value="">
</form>
<script>document.getElementById('mobile_confirm_form').submit();</script>
</body>
</html>
HTML;
return $this->htmlResponse($html);
}
private function htmlResponse(string $html): Response
{
return response($html, 200, ['Content-Type' => 'text/html; charset=UTF-8']);
}
/**
* TID로 payment_meta에 구매결정 결과를 저장하고 주문번호를 반환.
*/
private function saveConfirmResult(string $tid, array $data): ?string
{
if ($tid === '') {
return null;
}
$row = DB::table('ecommerce_order_payments as p')
->join('ecommerce_orders as o', 'o.id', '=', 'p.order_id')
->where('p.transaction_id', $tid)
->where('p.pg_provider', 'kginicis')
->where('p.is_escrow', true)
->select('p.id', 'p.payment_meta', 'o.order_number')
->first();
if (! $row) {
Log::warning('KG Inicis: escrow confirm — payment not found', ['tid' => $tid]);
return null;
}
$meta = $row->payment_meta ? json_decode($row->payment_meta, true) : [];
$meta['escrow_confirm'] = array_merge(
['confirmed_at' => now()->toDateTimeString()],
$data,
);
DB::table('ecommerce_order_payments')
->where('id', $row->id)
->update([
'payment_meta' => json_encode($meta, JSON_UNESCAPED_UNICODE),
'updated_at' => now(),
]);
Log::info('KG Inicis: escrow confirm saved', [
'order_number' => $row->order_number,
'tid' => $tid,
'type' => $data['type'] ?? '',
]);
return $row->order_number;
}
private function findEscrowPayment(string $orderNumber, int $userId): ?object
{
return DB::table('ecommerce_order_payments as p')
->join('ecommerce_orders as o', 'o.id', '=', 'p.order_id')
->where('o.order_number', $orderNumber)
->where('o.user_id', $userId)
->where('p.pg_provider', 'kginicis')
->where('p.is_escrow', true)
->whereNotNull('p.transaction_id')
->select('p.id', 'p.transaction_id')
->first();
}
private function isMobile(Request $request): bool
{
return (bool) preg_match('/(android|iphone|ipad|ipod|mobile|phone)/i', $request->userAgent() ?? '');
}
}
@@ -0,0 +1,392 @@
<?php
declare(strict_types=1);
namespace Plugins\Sirsoft\PayKginicis\Controllers;
use App\Services\PluginSettingsService;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;
use Modules\Sirsoft\Ecommerce\Services\GuestOrderAuthService;
use Plugins\Sirsoft\PayKginicis\Concerns\IssuesReceiptCookie;
use Plugins\Sirsoft\PayKginicis\Concerns\ResolvesEasyPaySelection;
class UserReceiptController
{
use IssuesReceiptCookie;
use ResolvesEasyPaySelection;
private const PLUGIN_IDENTIFIER = 'sirsoft-pay_kginicis';
// 출처: C:\xampp824\www\gnu5\shop\orderinquiryview.php (mCmReceipt_head.jsp)
private const RECEIPT_BASE_URL = 'https://iniweb.inicis.com/DefaultWebApp/mall/cr/cm/mCmReceipt_head.jsp';
public function __construct(
private readonly PluginSettingsService $pluginSettingsService,
private readonly GuestOrderAuthService $guestOrderAuthService,
) {}
/**
* show
*
* 회원/비회원 공유 영수증 조회. 코어 OrderController::showByOrderNumber 와 동일한
* 회원 우선 분기 — Auth::check() 일 때는 본인 회원 주문만, 비로그인일 때는
* X-Guest-Order-Token 으로 비회원 주문 매칭. 실패 사유는 모두 404 로 통일.
*
* @param Request $request
* @param string $orderNumber
* @return JsonResponse
*/
public function show(Request $request, string $orderNumber): JsonResponse
{
$query = DB::table('ecommerce_order_payments as p')
->join('ecommerce_orders as o', 'o.id', '=', 'p.order_id')
->where('o.order_number', $orderNumber)
->where('p.pg_provider', 'kginicis');
if (Auth::check()) {
$query->where('o.user_id', Auth::id());
} else {
// 1차: X-Guest-Order-Token 헤더 (코어 globalHeaders 또는 명시 헤더)
$token = $request->header('X-Guest-Order-Token');
$order = $this->guestOrderAuthService->verifyToken($token, $orderNumber);
// 2차 폴백: 결제 완료 직후 PG callback 이 발급한 단기 영수증 쿠키.
// sessionStorage 토큰이 없거나 브라우저 캐시가 stale 한 환경에서도 5분간 동작.
if (! $order) {
$cookieValue = $request->cookie(self::RECEIPT_COOKIE_NAME);
if ($this->verifyReceiptCookie($cookieValue, $orderNumber)) {
$query->where('o.id', function ($sub) use ($orderNumber) {
$sub->select('id')->from('ecommerce_orders')->where('order_number', $orderNumber);
});
} else {
return response()->json(['error' => 'Not found'], 404);
}
} else {
$query->whereNull('o.user_id')->where('o.id', $order->id);
}
}
$payment = $query
->select([
'o.order_number',
'o.currency as order_currency',
'o.total_amount',
'p.transaction_id',
'p.payment_status',
'p.payment_method',
'p.embedded_pg_provider',
'p.paid_amount_local',
'p.currency',
'p.card_approval_number',
'p.card_installment_months',
'p.vbank_number',
'p.vbank_due_at',
'p.payment_meta',
])
->first();
if (! $payment || ! $payment->transaction_id) {
return response()->json(['error' => 'Not found'], 404);
}
$settings = $this->pluginSettingsService->get(self::PLUGIN_IDENTIFIER) ?? [];
$isTestMode = (bool) ($settings['is_test_mode'] ?? true);
$paymentMeta = $this->decodePaymentMeta($payment->payment_meta ?? null);
$embeddedPgProvider = $payment->embedded_pg_provider
?: ($paymentMeta['embedded_pg_provider'] ?? null);
$embeddedPgProviderLabel = $paymentMeta['embedded_pg_provider_label']
?? $this->embeddedPgProviderLabel(is_string($embeddedPgProvider) ? $embeddedPgProvider : null);
$basePaymentMethodLabel = $this->paymentMethodLabel((string) ($payment->payment_method ?? ''));
if ($this->isCbtPayment($payment, $paymentMeta)) {
$cbtPayMethod = $this->resolveCbtPayMethod($paymentMeta);
$cbtPaymentMethodLabel = $this->cbtPayMethodLabel($cbtPayMethod);
$receiptLabels = $this->cbtReceiptLabels($cbtPayMethod, (string) ($payment->payment_status ?? ''));
return response()->json([
'receipt_type' => 'cbt_confirmation',
'receipt_url' => null,
'receipt_label' => $receiptLabels['label'],
'receipt_view_label' => $receiptLabels['view_label'],
'receipt_title' => $receiptLabels['title'],
'receipt_notice' => $receiptLabels['notice'],
'receipt_fields' => $this->buildCbtReceiptFields($payment, $paymentMeta),
'is_test_mode' => $isTestMode,
'payment_method_label' => $cbtPaymentMethodLabel,
'payment_method_display_label' => $cbtPaymentMethodLabel,
'cbt_pay_method' => $cbtPayMethod,
'payment_status' => (string) ($payment->payment_status ?? ''),
'selected_payment_method' => $paymentMeta['selected_payment_method'] ?? null,
'embedded_pg_provider' => is_string($embeddedPgProvider) ? $embeddedPgProvider : null,
'embedded_pg_provider_label' => is_string($embeddedPgProviderLabel) ? $embeddedPgProviderLabel : null,
]);
}
$receiptUrl = self::RECEIPT_BASE_URL . '?' . http_build_query([
'noTid' => $payment->transaction_id,
'noMethod' => '1',
]);
return response()->json([
'receipt_type' => 'inicis_receipt',
'receipt_url' => $receiptUrl,
'receipt_label' => '영수증',
'receipt_view_label' => '영수증 조회',
'is_test_mode' => $isTestMode,
'payment_method_label' => $basePaymentMethodLabel,
'payment_method_display_label' => $this->paymentMethodDisplayLabel(
$basePaymentMethodLabel,
is_string($embeddedPgProviderLabel) ? $embeddedPgProviderLabel : null,
),
'selected_payment_method' => $paymentMeta['selected_payment_method'] ?? null,
'embedded_pg_provider' => is_string($embeddedPgProvider) ? $embeddedPgProvider : null,
'embedded_pg_provider_label' => is_string($embeddedPgProviderLabel) ? $embeddedPgProviderLabel : null,
]);
}
private function isCbtPayment(object $payment, array $paymentMeta): bool
{
if (($paymentMeta['is_cbt'] ?? false) === true) {
return true;
}
if (($paymentMeta['cbt_type'] ?? null) !== null || ($paymentMeta['cbt_mid'] ?? null) !== null) {
return true;
}
return strtoupper((string) ($payment->currency ?? $payment->order_currency ?? '')) === 'JPY'
&& str_starts_with((string) $payment->transaction_id, 'INIJPG');
}
private function buildCbtReceiptFields(object $payment, array $paymentMeta): array
{
$approveResponse = is_array($paymentMeta['pg_approve_response'] ?? null)
? $paymentMeta['pg_approve_response']
: [];
$notifyResponse = is_array($paymentMeta['pg_cvs_notify_response'] ?? null)
? $paymentMeta['pg_cvs_notify_response']
: [];
$raw = array_merge($approveResponse, $notifyResponse);
$payMethod = $this->resolveCbtPayMethod($paymentMeta, $raw);
$currency = strtoupper((string) ($payment->currency ?? $paymentMeta['currency'] ?? 'JPY'));
$paymentStatus = (string) ($payment->payment_status ?? '');
$isWaitingDeposit = $payMethod === 'CVS' && $paymentStatus === 'waiting_deposit';
$amountLabel = $isWaitingDeposit ? '입금예정금액' : '결제금액';
$fields = [
['label' => '주문번호', 'value' => (string) ($payment->order_number ?? '')],
['label' => '결제수단', 'value' => $this->cbtPayMethodLabel($payMethod)],
['label' => '거래번호', 'value' => (string) $payment->transaction_id],
['label' => $amountLabel, 'value' => $this->formatCbtAmount($this->resolveCbtAmount($payment, $paymentMeta, $raw), $currency)],
['label' => '입금 상태', 'value' => $this->cbtPaymentStatusLabel($paymentStatus)],
['label' => '승인일시', 'value' => $this->formatCbtDateTime($raw['applDate'] ?? $raw['applDt'] ?? null, $raw['applTime'] ?? $raw['applTm'] ?? null)],
];
if ($payMethod === 'CARD') {
$fields[] = ['label' => '카드 승인번호', 'value' => (string) ($raw['approve'] ?? $payment->card_approval_number ?? '')];
$fields[] = ['label' => '할부개월', 'value' => $this->formatInstallmentMonths($raw['installMonth'] ?? $payment->card_installment_months ?? null)];
}
if ($payMethod === 'PAYPAY') {
$fields[] = ['label' => '승인번호', 'value' => (string) ($raw['approve'] ?? '')];
}
if ($payMethod === 'CVS') {
$fields[] = ['label' => '편의점 코드', 'value' => (string) ($raw['convenience'] ?? $paymentMeta['cvs_convenience'] ?? '')];
$fields[] = ['label' => '편의점 확인번호', 'value' => (string) ($raw['confNo'] ?? $paymentMeta['cvs_conf_no'] ?? $payment->vbank_number ?? '')];
$fields[] = ['label' => '편의점 접수번호', 'value' => (string) ($raw['receiptNo'] ?? $paymentMeta['cvs_receipt_no'] ?? '')];
$fields[] = ['label' => '입금 마감일시', 'value' => $this->formatCbtCompactDateTime((string) ($raw['paymentTerm'] ?? $paymentMeta['cvs_payment_term'] ?? ''))];
}
return array_values(array_filter(
$fields,
fn (array $field) => ($field['value'] ?? '') !== ''
));
}
private function resolveCbtPayMethod(array $paymentMeta, array $raw = []): string
{
$payMethod = strtoupper((string) ($paymentMeta['pay_method'] ?? $raw['paymethod'] ?? 'CBT'));
return match ($payMethod) {
'PAYPAY', 'PAYPAYMENT', 'PAYPAYPAYMENT' => 'PAYPAY',
'LINEPAY', 'LINEPAYMENT' => 'LINEPAY',
default => $payMethod,
};
}
private function cbtPayMethodLabel(string $payMethod): string
{
return match ($payMethod) {
'CARD' => '신용카드 (일본 CBT)',
'CVS' => '일본 편의점결제',
'PAYPAY' => 'PayPay',
'LINEPAY' => 'LINE Pay',
default => $payMethod !== '' ? $payMethod : '일본 CBT 결제',
};
}
private function cbtReceiptLabels(string $payMethod, string $paymentStatus): array
{
if ($payMethod === 'CVS' && $paymentStatus === 'waiting_deposit') {
return [
'label' => '입금정보',
'view_label' => '편의점 입금정보 보기',
'title' => 'KG 이니시스 CBT 편의점 입금정보',
'notice' => '일본 편의점결제는 입금 마감일시 전까지 편의점에서 확인번호로 결제를 완료해야 합니다.',
];
}
return [
'label' => '결제확인',
'view_label' => '결제확인서 보기',
'title' => 'KG 이니시스 CBT 결제확인서',
'notice' => '일본 CBT 결제는 한국 KG 이니시스 매출전표 조회와 별도로 결제 승인 정보를 표시합니다.',
];
}
private function cbtPaymentStatusLabel(string $paymentStatus): string
{
return match ($paymentStatus) {
'waiting_deposit' => '입금대기',
'paid' => '입금완료',
'cancelled' => '취소',
'failed' => '실패',
default => $paymentStatus,
};
}
private function resolveCbtAmount(object $payment, array $paymentMeta, array $raw): mixed
{
foreach ([
$raw['amount'] ?? null,
$raw['price'] ?? null,
$paymentMeta['cvs_amount'] ?? null,
$payment->paid_amount_local ?? null,
$payment->total_amount ?? null,
] as $amount) {
if ($amount !== null && $amount !== '' && (float) $amount > 0) {
return $amount;
}
}
return $payment->paid_amount_local ?? null;
}
private function formatCbtAmount(mixed $amount, string $currency): string
{
if ($amount === null || $amount === '') {
return '';
}
return number_format((float) $amount) . ' ' . $currency;
}
private function formatCbtDateTime(mixed $date, mixed $time): string
{
$date = preg_replace('/\D+/', '', (string) $date);
$time = preg_replace('/\D+/', '', (string) $time);
if (strlen($date) !== 8 || strlen($time) !== 6) {
return '';
}
return sprintf(
'%s-%s-%s %s:%s:%s',
substr($date, 0, 4),
substr($date, 4, 2),
substr($date, 6, 2),
substr($time, 0, 2),
substr($time, 2, 2),
substr($time, 4, 2),
);
}
private function formatCbtCompactDateTime(string $value): string
{
$value = preg_replace('/\D+/', '', $value);
if (strlen($value) !== 14) {
return '';
}
return $this->formatCbtDateTime(substr($value, 0, 8), substr($value, 8, 6));
}
private function formatInstallmentMonths(mixed $value): string
{
if ($value === null || $value === '') {
return '';
}
$months = (int) $value;
return $months <= 0 ? '일시불' : $months . '개월';
}
private function decodePaymentMeta(mixed $paymentMeta): array
{
if (is_array($paymentMeta)) {
return $paymentMeta;
}
if (! is_string($paymentMeta) || $paymentMeta === '') {
return [];
}
$decoded = json_decode($paymentMeta, true);
return is_array($decoded) ? $decoded : [];
}
private function paymentMethodLabel(string $paymentMethod): string
{
return match (strtolower($paymentMethod)) {
'card' => '신용카드',
'vbank' => '가상계좌',
'bank' => '계좌이체',
'dbank' => '무통장입금',
'phone', 'mobile' => '휴대폰결제',
'point' => '포인트결제',
'deposit' => '예치금결제',
'free' => '무료',
default => $paymentMethod !== '' ? $paymentMethod : '-',
};
}
private function embeddedPgProviderLabel(?string $provider): ?string
{
if ($provider === null || $provider === '') {
return null;
}
foreach ($this->kginicisEasyPayMethodMap() as $context) {
if (($context['provider'] ?? null) === $provider) {
return $context['label'];
}
}
return match (strtolower($provider)) {
'payco' => '페이코',
'tosspay', 'toss' => '토스페이',
'ssgpay' => 'SSG페이',
default => $provider,
};
}
private function paymentMethodDisplayLabel(string $baseLabel, ?string $embeddedLabel): string
{
if ($embeddedLabel === null || $embeddedLabel === '') {
return $baseLabel;
}
if ($baseLabel === '-' || $baseLabel === '') {
return $embeddedLabel;
}
return $embeddedLabel . ' (' . $baseLabel . ')';
}
}