fix(core,extensions): 보안 결함 3건과 이중저장소·레이아웃 중복키 결함군 폐쇄
KISA 제보 3건(KVE-2026-2010/2011/2018)과 그 동일 계열 형제 결함을 전수 조치하고, 그 과정에서 드러난 두 결함군을 함께 닫는다. - 검증 시점과 연결 시점이 host 를 다르게 읽던 SSRF 통로를 정규화 SSoT 한 곳으로 모았다 - 세션을 여는 지점(2FA 완료·토큰 재발급)이 잠금 검사를 거치지 않아 계정 잠금이 우회됐다 - 인증도 서명도 없는 브라우저 리턴 콜백이 주문 상태를 바꾸던 통로를 4 PG 전부에서 닫고, 소유권을 대조하는 close-report 를 토스에도 신설했다. 그 결과 정리 주체를 잃는 결제창 미완료 주문은 만료 자동취소가 거둔다 - 저장소 A(_local)에만 쓰는 경로가 B 의 값을 조용히 덮던 회귀를 정본 writer 로 닫았다 (engine-v1.63.5). 한 방향만 보던 정적 검사에 반대 방향 축과 양방향 계약 테스트를 더했다 - 레이아웃 JSON 의 같은 객체 중복 키가 앞선 선언을 오류 없이 삼키던 결함군을 닫았다
This commit is contained in:
1 parent
d4439ea30a
commit
21fc114f37
137 files changed
+6470
-829
No files matched your search
@@ -132,6 +132,12 @@ CBT 인증 URL 로 폼 POST → KG 이니시스가 `sid` 를 콜백으로 전달
|
||||
| 결제창 서명/모바일 해시/CBT 해시 요청에 타임스탬프 검증 생략 | 타임스탬프 신선도 검증 유지 | 오래된 서명 재사용(replay)으로 위조 결제 요청이 통과할 수 있다 |
|
||||
| 일본 결제 설정 미완료 시 한국 표준결제로 조용히 대체 | 설정 미완료면 결제 자체를 중단 | 통화·수수료·정산 구조가 다른 결제가 잘못된 흐름으로 승인될 수 있다 |
|
||||
| 라이브 키(사인키·INIAPI 키/IV·해시키)를 로그·에러 메시지에 노출 | 운영 키는 항상 마스킹하거나 로그 대상에서 제외 | 노출되면 제3자가 결제창 서명을 위조할 수 있다 |
|
||||
| 서버 승인 실패 분기(PC `authorizePayment` · 모바일 `P_STATUS` · CBT `approveCbtPayment`)에서 `failPayment()` 호출 | 로그 + `resolveFailUrl()` 만. 주문 상태는 건드리지 않는다 | 세 콜백 모두 PG 서명도 IP 증명도 없는 비인증 브라우저 요청이고 주문번호(`MOID`/`P_OID`/`oid`)도 요청자가 고른 값이다. 승인 실패는 위조 `authToken`/`P_TID`/`sid` 만으로 만들어낼 수 있으므로, 그것을 근거로 실패 처리하면 타인의 결제대기 주문이 취소된다 |
|
||||
| 정당한 결제 실패 기록을 콜백에서 처리 | 소유권을 검증하는 `close-report`(`requestMatchesOrderBuyer`) 경유 | 구매자 이메일·전화 대조를 통과한 요청만 주문 상태를 바꿔야 한다 |
|
||||
| PG 대상 `netCancel` 을 로컬 주문 실패 처리와 같은 것으로 취급 | `sendNetCancel()` 은 PG 잔존 승인 해제이므로 유지, 로컬 주문 mutation 은 별개 판단 | 두 동작을 묶으면 PG 정합성을 지키려다 주문 취소 통로를 다시 연다 |
|
||||
| 결제창 컨텍스트를 `window` 전역에만 보관 | `markStandardPaymentCloseReportContext()` 가 sessionStorage 에도 남기고, 부팅 시 `reportStandardPaymentFailureOnReturn()` 으로 보고 | 결제창은 전체 페이지 이동으로 열리고 돌아와 전역이 소실된다. 승인 거절은 fail URL 리다이렉트로 끝나므로, 남겨 둔 정보가 없으면 정당한 결제 실패가 어디에도 기록되지 않는다 |
|
||||
| 리턴 콜백 복귀 보고에 체크아웃 경로 검사를 강제 | `reportStandardPaymentWindowClosed($reason, requireCheckoutPage: false)` | 상점이 `redirect_fail_url` 을 바꿔 두면 경로 검사가 보고를 통째로 막는다. 닫힘 메시지 경로(체크아웃 화면 전용)와 리턴 복귀 경로는 판정 기준이 다르다 |
|
||||
| 실패 화면에서 보고가 닿지 못한 주문을 방치 | 이커머스 모듈의 만료 주문 자동 정리가 최종 안전망 | 브라우저를 바로 닫으면 보고가 나가지 않는다. 두 경로가 함께 있어야 선차감 마일리지가 무기한 묶이지 않는다 |
|
||||
<!-- @intent END -->
|
||||
|
||||
## 7. 테스트 실행
|
||||
@@ -141,7 +147,7 @@ CBT 인증 URL 로 폼 POST → KG 이니시스가 `sid` 를 콜백으로 전달
|
||||
|---|---|---|
|
||||
| PHPUnit | 35개 | `plugins/_bundled/sirsoft-pay_kginicis/tests` |
|
||||
| Vitest | 12개 | `vitest.config.ts` |
|
||||
| Playwright | 0개 | — |
|
||||
| Playwright | 1개 | `tests/Playwright` |
|
||||
| 시나리오 매니페스트 | 2개 | `tests/scenarios` |
|
||||
|
||||
기저 TestCase: `tests/PluginTestCase.php` — 확장 테스트는 이 클래스를 상속합니다 (`Tests\TestCase` 직접 상속 금지).
|
||||
@@ -153,6 +159,9 @@ php vendor/bin/phpunit plugins/_bundled/sirsoft-pay_kginicis/tests --filter='<
|
||||
# Vitest (확장 디렉토리에서) (PowerShell)
|
||||
cd plugins/_bundled/sirsoft-pay_kginicis && powershell -Command "npm run test:run -- <대상>"
|
||||
|
||||
# Playwright E2E (확장 디렉토리에서) (Bash)
|
||||
cd plugins/_bundled/sirsoft-pay_kginicis && npm run test:e2e -- specs/<대상>.spec.ts
|
||||
|
||||
```
|
||||
|
||||
무필터 전체 실행은 금지되어 있습니다 — 변경 범위에 걸리는 대상만 지정해 실행합니다.
|
||||
|
||||
@@ -6,8 +6,13 @@
|
||||
|
||||
## [1.1.3] - 2026-08-31
|
||||
|
||||
### Security
|
||||
|
||||
- 제3자가 남의 주문번호만 알면 결제창을 거치지 않고도 그 주문을 취소시킬 수 있던 문제를 수정했습니다. 결제 결과 콜백은 로그인도 서명 확인도 거치지 않는 경로여서, 위조한 인증 정보를 보내 승인을 일부러 실패시키면 그 주문이 결제 실패로 처리되었습니다. 이제 승인이 성립하지 않은 콜백은 주문 상태를 바꾸지 않고 결제 화면으로 되돌려 보내기만 합니다. PC·모바일·해외결제(CBT) 결제창 모두에 적용됩니다. 구매자가 결제창을 닫아 생기는 정상적인 결제 실패는 종전처럼 기록됩니다.
|
||||
|
||||
### Added
|
||||
|
||||
- 결제가 거절되어 실패 화면으로 돌아오면 그 사실이 자동으로 서버에 기록됩니다. 구매자 본인인지 확인한 뒤에만 주문을 실패로 처리하므로, 남의 주문번호를 아는 것만으로는 그 주문을 건드릴 수 없습니다. PC·모바일·해외결제 결제창 모두에 적용되며, 상점이 실패 안내 주소를 바꿔 두었어도 동작합니다.
|
||||
- 개발자와 AI 에이전트를 위한 문서를 추가했습니다. 확장 폴더의 `AGENTS.md`(설계 의도·확장점·수정 시 확인할 것)와 `README.md`(도입·운영 안내), `docs/`(상세 문서)로 구성됩니다.
|
||||
- 확장 문서에 「레이아웃 편집기 스펙」 항목을 추가했습니다. 이 확장이 레이아웃 편집기에 무엇을 선언했는지와, 화면 요소나 데이터를 추가할 때 편집기 쪽에서 함께 해야 할 일을 담습니다.
|
||||
- 문서의 제품 표기를 「그누보드7」로 통일했습니다.
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"$schema": "https://json-schema.org/draft/2020-12/schema",
|
||||
"identifier": "sirsoft-pay_kginicis",
|
||||
"version": "1.1.0",
|
||||
"version": "1.1.3",
|
||||
"components": {
|
||||
"basic": [],
|
||||
"composite": [],
|
||||
|
||||
@@ -1,14 +1,14 @@
|
||||
(function(){"use strict";const x="kginicis_pay_form_",R="__sirsoftKginicisReloadStandardPaySdk",w="__sirsoftKginicisMobilePaymentReturnPending";function ie(){if(typeof document>"u")return 0;const e=document.querySelectorAll(`form[id^="${x}"]`);return e.forEach(t=>t.remove()),e.length}function qe(){typeof window>"u"||(window[R]=!0)}function We(){if(typeof window>"u")return!1;const e=window,t=e[R]===!0;return delete e[R],t}function Ve(e){typeof window>"u"||typeof document>"u"||(window.INIStdPay=void 0,document.querySelectorAll(`script[src="${e}"], script[src*="/INIStdPay_third-party.js"]`).forEach(t=>t.remove()))}function ze(e=Date.now()){if(!(typeof window>"u"))try{window.sessionStorage.setItem(w,String(e))}catch{window[w]=e}}function M(){if(!(typeof window>"u")){try{window.sessionStorage.removeItem(w)}catch{}delete window[w]}}function ae(e=Date.now()){if(typeof window>"u")return!1;let t=null;try{const n=window.sessionStorage.getItem(w);t=n?Number(n):null}catch{t=null}if(!Number.isFinite(t)){const n=window[w];t=typeof n=="number"?n:Number(n)}return!Number.isFinite(t)||e-t>18e5?(M(),!1):!0}const N="sirsoft-pay_kginicis",Xe=N,Ze="payment-window-closed",se="__sirsoftKginicisPaymentCloseListenerInstalled",L="__sirsoftKginicisActiveStandardPaymentCloseContext",ce=20,Qe=100,O={info:(...e)=>console.info(`[${N}]`,...e),warn:(...e)=>console.warn(`[${N}]`,...e)};function et(e){if(!e||typeof e!="object")return!1;const t=e;return t.source===Xe&&t.type===Ze}function $(){return/\/shop\/checkout\/?$/.test(window.location.pathname)}function P(){return window}function tt(){const e=P()[L];return!e||typeof e!="object"?null:e}function nt(e){return/^https?:\/\//i.test(e)||e.startsWith("/api/")?e:e.startsWith("/plugins/")?`/api${e}`:e.startsWith("plugins/")?`/api/${e}`:e}function rt(e){e.closeReportUrl&&(P()[L]={...e,reported:!1})}function de(){delete P()[L]}function le(){de()}async function ot(e="payment-window-closed"){const t=tt();if(!t||t.reported||!$())return;t.reported=!0;const n={oid:t.oid,price:t.price,buyer_email:t.buyer_email??"",buyer_phone:t.buyer_phone??"",payment_method:t.payment_method??"",reason:e};try{const r=window.G7Core?.api;typeof r?.post=="function"?await r.post(t.closeReportUrl,n):await fetch(nt(t.closeReportUrl),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(n),keepalive:!0})}catch(r){O.warn("failed to report KG payment window close",{reason:e,error:r})}finally{de()}}function ue(e="payment-window-closed",t=!0){if(!$())return!1;const r=window.G7Core?.state?.setLocal;return typeof r!="function"?(t&&O.warn("G7Core.state.setLocal not available while resetting payment submit state"),!1):(ie(),qe(),r({isSubmittingOrder:!1}),O.info("checkout submit state reset after KG payment close",{reason:e}),!0)}function it(e,t=!1){let n=0;const r=()=>{if(n++,!(t&&!ae())){if(ue(e,n>=ce)){t&&M();return}!$()||n>=ce||window.setTimeout(r,Qe)}};r()}function I(e){ae()&&it(e,!0)}function at(){if(typeof window>"u")return;const e=P();e[se]||(window.addEventListener("message",t=>{t.origin===window.location.origin&&et(t.data)&&(ot(t.data.reason),ue(t.data.reason))}),window.addEventListener("pagehide",()=>{le()}),window.addEventListener("beforeunload",()=>{le()}),window.addEventListener("pageshow",t=>{I(t.persisted?"mobile-payment-bfcache-return":"mobile-payment-page-show")}),window.addEventListener("focus",()=>{I("mobile-payment-window-focus")}),document.addEventListener("visibilitychange",()=>{document.visibilityState==="visible"&&I("mobile-payment-visibility-return")}),e[se]=!0,I("mobile-payment-listener-installed"))}function me(){if(typeof navigator>"u")return!1;const e=navigator;if(e.userAgentData?.mobile!==void 0)return e.userAgentData.mobile;const t=(e.userAgent||"").toLowerCase(),n=((e.userAgentData?.platform??e.platform)||"").toLowerCase();if(/android|iphone|ipad|ipod|windows phone|iemobile|blackberry|opera mini|mobile safari/.test(t)||/iphone|ipad|ipod|ios/.test(n))return!0;const r=e.maxTouchPoints??0;return/macintosh|mac os x/.test(t)&&r>1}function st(e){return new Promise((t,n)=>{if(document.querySelector(`script[src="${e}"]`)){t();return}const r=document.createElement("script");r.src=e,r.async=!0,r.onload=()=>t(),r.onerror=()=>n(new Error(`Failed to load script: ${e}`)),document.head.appendChild(r)})}function fe(e,t){if(!t.startsWith("kginicis_"))return e;const n=new URL(e,window.location.origin);return n.searchParams.set("selectedPaymentMethod",t),n.toString()}function ct(e){const t=(e??"").trim().toUpperCase();return t===""||t==="WON"?"KRW":t}function pe(e,t,n="utf-8",r){const o=document.createElement("form");r&&(o.id=r),o.method="POST",o.action=e,o.acceptCharset=n,o.style.display="none";for(const[i,s]of Object.entries(t)){const a=document.createElement("input");a.type="hidden",a.name=i,a.value=s,o.appendChild(a)}document.body.appendChild(o),o.submit()}const dt={card:"Card",vbank:"VBank",bank:"DirectBank",phone:"HPP",kginicis_samsung_pay:"onlyssp",kginicis_naverpay:"onlynaverpay",kginicis_lLine truncated
|
||||
(function(){"use strict";const x="kginicis_pay_form_",M="__sirsoftKginicisReloadStandardPaySdk",w="__sirsoftKginicisMobilePaymentReturnPending";function ce(){if(typeof document>"u")return 0;const e=document.querySelectorAll(`form[id^="${x}"]`);return e.forEach(t=>t.remove()),e.length}function ze(){typeof window>"u"||(window[M]=!0)}function Xe(){if(typeof window>"u")return!1;const e=window,t=e[M]===!0;return delete e[M],t}function Ze(e){typeof window>"u"||typeof document>"u"||(window.INIStdPay=void 0,document.querySelectorAll(`script[src="${e}"], script[src*="/INIStdPay_third-party.js"]`).forEach(t=>t.remove()))}function Qe(e=Date.now()){if(!(typeof window>"u"))try{window.sessionStorage.setItem(w,String(e))}catch{window[w]=e}}function N(){if(!(typeof window>"u")){try{window.sessionStorage.removeItem(w)}catch{}delete window[w]}}function de(e=Date.now()){if(typeof window>"u")return!1;let t=null;try{const n=window.sessionStorage.getItem(w);t=n?Number(n):null}catch{t=null}if(!Number.isFinite(t)){const n=window[w];t=typeof n=="number"?n:Number(n)}return!Number.isFinite(t)||e-t>18e5?(N(),!1):!0}const L="sirsoft-pay_kginicis",et=L,tt="payment-window-closed",le="__sirsoftKginicisPaymentCloseListenerInstalled",I="__sirsoftKginicisActiveStandardPaymentCloseContext",ue=20,nt=100,O={info:(...e)=>console.info(`[${L}]`,...e),warn:(...e)=>console.warn(`[${L}]`,...e)};function rt(e){if(!e||typeof e!="object")return!1;const t=e;return t.source===et&&t.type===tt}function $(){return/\/shop\/checkout\/?$/.test(window.location.pathname)}function C(){return window}function ot(){const e=C()[I];return!e||typeof e!="object"?null:e}function it(e){return/^https?:\/\//i.test(e)||e.startsWith("/api/")?e:e.startsWith("/plugins/")?`/api${e}`:e.startsWith("plugins/")?`/api/${e}`:e}const D="g7:sirsoft-pay_kginicis:pendingClose";function G(){try{return window.sessionStorage??null}catch{return null}}function at(e){if(e.closeReportUrl){C()[I]={...e,reported:!1};try{G()?.setItem(D,JSON.stringify({...e,reported:!1}))}catch{}}}function K(){delete C()[I];try{G()?.removeItem(D)}catch{}}function st(){try{const e=G()?.getItem(D);if(!e)return null;const t=JSON.parse(e);return t&&typeof t.oid=="string"&&t.oid!==""&&t.closeReportUrl?t:null}catch{return null}}async function ct(){const e=st();if(!e)return;let t;try{t=new URLSearchParams(window.location.search)}catch{return}const n=t.get("orderId")??"";if(n!==""&&n!==e.oid)return;if(/\/(complete|success)(\/|$|\?)/.test(window.location.pathname)){K();return}const r=t.get("error")??"",o=t.get("message")??"";r===""&&n===""||(C()[I]={...e,reported:!1},await fe(o!==""?o:r||"payment-window-closed",!1))}function me(){K()}async function fe(e="payment-window-closed",t=!0){const n=ot();if(!n||n.reported||t&&!$())return;n.reported=!0;const r={oid:n.oid,price:n.price,buyer_email:n.buyer_email??"",buyer_phone:n.buyer_phone??"",payment_method:n.payment_method??"",reason:e};try{const o=window.G7Core?.api;typeof o?.post=="function"?await o.post(n.closeReportUrl,r):await fetch(it(n.closeReportUrl),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(r),keepalive:!0})}catch(o){O.warn("failed to report KG payment window close",{reason:e,error:o})}finally{K()}}function pe(e="payment-window-closed",t=!0){if(!$())return!1;const r=window.G7Core?.state?.setLocal;return typeof r!="function"?(t&&O.warn("G7Core.state.setLocal not available while resetting payment submit state"),!1):(ce(),ze(),r({isSubmittingOrder:!1}),O.info("checkout submit state reset after KG payment close",{reason:e}),!0)}function dt(e,t=!1){let n=0;const r=()=>{if(n++,!(t&&!de())){if(pe(e,n>=ue)){t&&N();return}!$()||n>=ue||window.setTimeout(r,nt)}};r()}function v(e){de()&&dt(e,!0)}function lt(){if(typeof window>"u")return;const e=C();e[le]||(window.addEventListener("message",t=>{t.origin===window.location.origin&&rt(t.data)&&(fe(t.data.reason),pe(t.data.reason))}),window.addEventListener("pagehide",()=>{me()}),window.addEventListener("beforeunload",()=>{me()}),window.addEventListener("pageshow",t=>{v(t.persisted?"mobile-payment-bfcache-return":"mobile-payment-page-show")}),window.addEventListener("focus",()=>{v("mobile-payment-window-focus")}),document.addEventListener("visibilitychange",()=>{document.visibilityState==="visible"&&v("mobile-payment-visibility-return")}),e[le]=!0,v("mobile-payment-listener-installed"))}function ye(){if(typeof navigator>"u")return!1;const e=navigator;if(e.userAgentData?.mobile!==void 0)return e.userAgentData.mobile;const t=(e.userAgent||"").toLowerCase(),n=((e.userAgentData?.platform??e.platform)||"").toLowerCase();if(/android|iphone|ipad|ipod|windows phone|iemobile|blackberry|opera mini|mobile safari/.test(t)||/iphone|ipad|ipod|ios/.test(n))return!0;const r=e.maxTouchPoints??0;return/macintosh|mac os x/.test(t)&&r>1}function ut(e){return new Promise((t,n)=>{if(document.querySelector(`script[src="${e}"]`)){t();return}const r=document.createElement("script");r.src=e,r.async=!0,r.onload=()=>t(),r.onerror=(Line truncated
|
||||
<div class="row">
|
||||
<dt>${E(i.label)}</dt>
|
||||
<dd>${E(i.value)}</dd>
|
||||
<dt>${S(i.label)}</dt>
|
||||
<dd>${S(i.value)}</dd>
|
||||
</div>
|
||||
`).join("");t.document.open(),t.document.write(`<!doctype html>
|
||||
<html lang="ko">
|
||||
<head>
|
||||
<meta charset="utf-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1">
|
||||
<title>${E(n)}</title>
|
||||
<title>${S(n)}</title>
|
||||
<style>
|
||||
body {
|
||||
margin: 0;
|
||||
@@ -81,10 +81,10 @@
|
||||
</head>
|
||||
<body>
|
||||
<main>
|
||||
<h1>${E(n)}</h1>
|
||||
${r?`<p class="notice">${E(r)}</p>`:""}
|
||||
<h1>${S(n)}</h1>
|
||||
${r?`<p class="notice">${S(r)}</p>`:""}
|
||||
<dl>${o}</dl>
|
||||
<div class="actions"><button type="button" onclick="window.print()">인쇄</button></div>
|
||||
</main>
|
||||
</body>
|
||||
</html>`),t.document.close()}function E(e){return e.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'")}const D="sirsoft-pay_kginicis",be="__kginicisOrderShowInjectorInstalled",K="kginicis-mp-receipt-row",ke=/^(?:\/mypage\/orders\/([^/]+)|\/shop\/guest\/orders\/([^/]+))$/,G=new Map;function Tt(e){try{const n=window.G7Core?.getState,i=n?.()?.currentDataContext?.order?.data;return i&&(i.order_number===e||i.id!==void 0&&String(i.id)===e)?i:null}catch{return null}}function xt(){const e=document.getElementById("order_payment_info_panel");if(e)return Array.from(e.children).find(r=>r.className?.includes("space-y"))??e;const t=Array.from(document.querySelectorAll("h3")).find(r=>{const o=r.textContent?.trim()??"";return o.includes("결제 정보")||/^Payment Information$/i.test(o)});if(!t)return null;const n=t.parentElement?.parentElement;return n?Array.from(n.children).find(r=>r.className?.includes("space-y"))??n:null}function Rt(e,t){if(!t)return!1;const n=Array.from(e.querySelectorAll("div"));for(const r of n){const o=Array.from(r.children).filter(a=>a instanceof HTMLElement&&a.tagName==="SPAN");if(o.length<2)continue;const i=o[0].textContent?.trim();if(i!=="결제 방법"&&i!=="결제수단"&&i!=="Payment Method")continue;const s=o[o.length-1];return s.textContent?.trim()===t?(r.dataset.kginicisPaymentMethodRow="true",!0):(s.textContent=t,s.dataset.kginicisPaymentMethodPatched="true",r.dataset.kginicisPaymentMethodRow="true",!0)}return!1}function Mt(e,t){const n=document.createElement("div");n.id=K,n.className="flex items-center justify-between",n.dataset.kginicisReceiptRow="mypage-order";const r=document.createElement("span");r.className="text-gray-500 dark:text-gray-400 text-sm",r.textContent=vt(t);const o=document.createElement("button");return o.type="button",o.dataset.kginicisReceiptButton="mypage-order",o.className="inline-flex items-center gap-1 text-sm text-blue-600 dark:text-blue-400 hover:underline disabled:opacity-50",o.textContent=A(t),o.addEventListener("click",async()=>{o.disabled=!0,o.textContent="로딩 중...";const i=await v(e);o.disabled=!1,o.textContent=A(i??t),C(i)&&we(i)}),n.appendChild(r),n.appendChild(o),n}async function Nt(e,t){const n=Tt(e),r=n?.payment;if(r&&(r.pg_provider!=="kginicis"||!r.transaction_id))return!0;const o=n?.order_number??(t?e:null);if(!o)return!1;if(!t&&n&&!r)return!0;const i=xt();if(!i)return!1;const{status:s,info:a}=await ge(o);if(!t&&s===404)return!0;const c=r?.payment_status==="paid",u=a?.receipt_type==="cbt_confirmation";if(r&&!c&&!u)return!0;if(!r&&!C(a))return!1;const d=Rt(i,a?.payment_method_display_label);return!document.getElementById(K)&&C(a)&&(i.appendChild(Mt(o,a)),console.info(`[${D}] receipt button injected on mypage order show`)),d&&console.info(`[${D}] payment method display patched on mypage order show`),!!(document.getElementById(K)||d)}function Lt(e,t){if(G.has(e))return;let n=0;const r=window.setInterval(()=>{n++,Nt(e,t).then(o=>{(o||n>=30)&&(window.clearInterval(r),G.delete(e))})},400);G.set(e,r)}function Ot(){const e=location.pathname.match(ke);if(e){const t=e[1],n=e[2],r=t??n;r&&Lt(r,n!==void 0)}}function $t(){if(typeof window>"u")return;const e=window;if(e[be])return;e[be]=!0,console.info(`[${D}] mypage order show injector installed`);let t=null;const n=(a=1500)=>{t!==null&&window.clearTimeout(t),t=window.setTimeout(()=>{t=null,Ot()},a)};document.readyState==="loading"?document.addEventListener("DOMContentLoaded",()=>n()):n();const r=history.pushState.bind(history);history.pushState=(...a)=>{r(...a),n(600)};const o=history.replaceState.bind(history);history.replaceState=(...a)=>{o(...a),n(600)},window.addEventListener("popstate",()=>n(500));const i=document.getElementById("app")??document.body;new MutationObserver(()=>{ke.test(location.pathname)&&n(250)}).observe(i,{childList:!0,subtree:!0})}const j="sirsoft-pay_kginicis",Ce="__kginicisAdminPaymentDisplayInjectorInstalled",Dt=/^\/admin\/ecommerce\/orders\/([^/]+)$/;function Kt(){return localStorage.getItem("auth_token")}async function Gt(e){const t=Kt();if(!t)return null;try{const n=await fetch(`/api/plugins/${j}/admin/orders/${e}/transaction-status`,{headers:{Authorization:`Bearer ${t}`,Accept:"application/json"}});if(!n.ok)return null;const r=await n.json();return("data"in r?r.data:r)??null}catch{return null}}function jt(e){return Array.from(e.children).filter(t=>t instanceof HTMLElement)}function Yt(e,t){let n=!1;const r=Array.from(e.querySelectorAll("div"));for(const o of r){const i=jt(o),s=i.findIndex(l=>l.textContent?.trim()==="결제수단");if(s<0)continue;const a=i.slice(s+1).find(l=>l.textContent?.trim()&&l.textContent.trim()!=="결제수단");if(!a)continue;const c=i.slice(s+2).find(l=>/^\(.+\)$/.test(l.textContent?.trim()??"")),u=c?.textContent?.trim().replace(/^\(|\)$/g,"")??"",d=u&&t.endsWith(")")?t.replace(/\)$/,`, ${u})`):t;a.textContent?.trim()!==d&&(a.textContent=d,a.dataset.kginicisPaymentMethodPatched="true"),o.dataLine truncated
|
||||
</html>`),t.document.close()}function S(e){return e.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'")}const j="sirsoft-pay_kginicis",Ee="__kginicisOrderShowInjectorInstalled",Y="kginicis-mp-receipt-row",Se=/^(?:\/mypage\/orders\/([^/]+)|\/shop\/guest\/orders\/([^/]+))$/,B=new Map;function Nt(e){try{const n=window.G7Core?.getState,i=n?.()?.currentDataContext?.order?.data;return i&&(i.order_number===e||i.id!==void 0&&String(i.id)===e)?i:null}catch{return null}}function Lt(){const e=document.getElementById("order_payment_info_panel");if(e)return Array.from(e.children).find(r=>r.className?.includes("space-y"))??e;const t=Array.from(document.querySelectorAll("h3")).find(r=>{const o=r.textContent?.trim()??"";return o.includes("결제 정보")||/^Payment Information$/i.test(o)});if(!t)return null;const n=t.parentElement?.parentElement;return n?Array.from(n.children).find(r=>r.className?.includes("space-y"))??n:null}function Ot(e,t){if(!t)return!1;const n=Array.from(e.querySelectorAll("div"));for(const r of n){const o=Array.from(r.children).filter(a=>a instanceof HTMLElement&&a.tagName==="SPAN");if(o.length<2)continue;const i=o[0].textContent?.trim();if(i!=="결제 방법"&&i!=="결제수단"&&i!=="Payment Method")continue;const s=o[o.length-1];return s.textContent?.trim()===t?(r.dataset.kginicisPaymentMethodRow="true",!0):(s.textContent=t,s.dataset.kginicisPaymentMethodPatched="true",r.dataset.kginicisPaymentMethodRow="true",!0)}return!1}function $t(e,t){const n=document.createElement("div");n.id=Y,n.className="flex items-center justify-between",n.dataset.kginicisReceiptRow="mypage-order";const r=document.createElement("span");r.className="text-gray-500 dark:text-gray-400 text-sm",r.textContent=xt(t);const o=document.createElement("button");return o.type="button",o.dataset.kginicisReceiptButton="mypage-order",o.className="inline-flex items-center gap-1 text-sm text-blue-600 dark:text-blue-400 hover:underline disabled:opacity-50",o.textContent=T(t),o.addEventListener("click",async()=>{o.disabled=!0,o.textContent="로딩 중...";const i=await A(e);o.disabled=!1,o.textContent=T(i??t),E(i)&&Ce(i)}),n.appendChild(r),n.appendChild(o),n}async function Dt(e,t){const n=Nt(e),r=n?.payment;if(r&&(r.pg_provider!=="kginicis"||!r.transaction_id))return!0;const o=n?.order_number??(t?e:null);if(!o)return!1;if(!t&&n&&!r)return!0;const i=Lt();if(!i)return!1;const{status:s,info:a}=await ke(o);if(!t&&s===404)return!0;const c=r?.payment_status==="paid",u=a?.receipt_type==="cbt_confirmation";if(r&&!c&&!u)return!0;if(!r&&!E(a))return!1;const d=Ot(i,a?.payment_method_display_label);return!document.getElementById(Y)&&E(a)&&(i.appendChild($t(o,a)),console.info(`[${j}] receipt button injected on mypage order show`)),d&&console.info(`[${j}] payment method display patched on mypage order show`),!!(document.getElementById(Y)||d)}function Gt(e,t){if(B.has(e))return;let n=0;const r=window.setInterval(()=>{n++,Dt(e,t).then(o=>{(o||n>=30)&&(window.clearInterval(r),B.delete(e))})},400);B.set(e,r)}function Kt(){const e=location.pathname.match(Se);if(e){const t=e[1],n=e[2],r=t??n;r&&Gt(r,n!==void 0)}}function jt(){if(typeof window>"u")return;const e=window;if(e[Ee])return;e[Ee]=!0,console.info(`[${j}] mypage order show injector installed`);let t=null;const n=(a=1500)=>{t!==null&&window.clearTimeout(t),t=window.setTimeout(()=>{t=null,Kt()},a)};document.readyState==="loading"?document.addEventListener("DOMContentLoaded",()=>n()):n();const r=history.pushState.bind(history);history.pushState=(...a)=>{r(...a),n(600)};const o=history.replaceState.bind(history);history.replaceState=(...a)=>{o(...a),n(600)},window.addEventListener("popstate",()=>n(500));const i=document.getElementById("app")??document.body;new MutationObserver(()=>{Se.test(location.pathname)&&n(250)}).observe(i,{childList:!0,subtree:!0})}const U="sirsoft-pay_kginicis",Pe="__kginicisAdminPaymentDisplayInjectorInstalled",Yt=/^\/admin\/ecommerce\/orders\/([^/]+)$/;function Bt(){return localStorage.getItem("auth_token")}async function Ut(e){const t=Bt();if(!t)return null;try{const n=await fetch(`/api/plugins/${U}/admin/orders/${e}/transaction-status`,{headers:{Authorization:`Bearer ${t}`,Accept:"application/json"}});if(!n.ok)return null;const r=await n.json();return("data"in r?r.data:r)??null}catch{return null}}function Jt(e){return Array.from(e.children).filter(t=>t instanceof HTMLElement)}function Ht(e,t){let n=!1;const r=Array.from(e.querySelectorAll("div"));for(const o of r){const i=Jt(o),s=i.findIndex(l=>l.textContent?.trim()==="결제수단");if(s<0)continue;const a=i.slice(s+1).find(l=>l.textContent?.trim()&&l.textContent.trim()!=="결제수단");if(!a)continue;const c=i.slice(s+2).find(l=>/^\(.+\)$/.test(l.textContent?.trim()??"")),u=c?.textContent?.trim().replace(/^\(|\)$/g,"")??"",d=u&&t.endsWith(")")?t.replace(/\)$/,`, ${u})`):t;a.textContent?.trim()!==d&&(a.textContent=d,a.dataset.kginicisPaymentMethodPatched="true"),o.dataLine truncated
|
||||
@@ -225,6 +225,8 @@ _단건 응답: `data` 객체의 필드._
|
||||
|
||||
PC 표준결제창(KRW)에서 사용자가 결제를 완료하지 않고 창을 닫았을 때 프론트엔드가 이를 서버에 보고하는 엔드포인트로, 해당 주문의 결제 실패/취소 이력을 기록합니다. `OrderProcessingService::failPayment()` 로 주문을 `USER_CANCEL` 사유로 실패 처리하고 `recordPaymentCancellation()` 으로 취소 이력을 남기며, 간편결제 선택 정보가 있으면 결제 메타에 병합합니다. 인증은 불필요하나(결제창 컨텍스트에서 호출) FormRequest 검증과 `oid` 기준 IP별 분당 20회 레이트리밋, 주문 존재·통화 KRW·구매자 일치·금액 일치를 검증하고, 이미 결제 가능 상태가 아니거나(`order_not_payable`) 이미 결제 완료(`payment_already_paid`)면 성공 응답에 `status: ignored` 로 무시 처리해 결제 성공 콜백과의 경쟁 상태를 차단합니다. 검증 규칙 위반 시 422, 레이트리밋 초과 429, 주문 미존재 404, 구매자 검증 실패 403 으로 응답합니다.
|
||||
|
||||
이 엔드포인트가 **주문을 실패로 전이시키는 유일한 결제창 경로**입니다. 브라우저 리턴 콜백(PC `/payment/callback`, 모바일 `/payment/mobile/callback`, 해외결제 `/payment/cbt/callback`)은 PG 서명도 IP 증명도 없고 주문번호도 요청자가 고른 값이므로, 서버 승인이 실패해도 주문 상태를 바꾸지 않고 실패 URL 로 되돌려 보내기만 합니다. 정당한 결제창 닫힘은 구매자 대조를 통과한 이 요청으로만 기록됩니다.
|
||||
|
||||
|
||||
### POST /api/plugins/sirsoft-pay_kginicis/payment/mobile/signature
|
||||
<!-- @generated:start:api.plugins.sirsoft-pay_kginicis.payment.mobile.signature -->
|
||||
|
||||
+121
@@ -9,6 +9,7 @@ import {
|
||||
clearStandardPaymentCloseReportContext,
|
||||
installPaymentCloseMessageListener,
|
||||
markStandardPaymentCloseReportContext,
|
||||
reportStandardPaymentFailureOnReturn,
|
||||
resetCheckoutSubmittingState,
|
||||
} from '../paymentCloseMessageListener';
|
||||
|
||||
@@ -217,3 +218,123 @@ describe('paymentCloseMessageListener', () => {
|
||||
expect(hasMobilePaymentReturnPending()).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
/**
|
||||
* 결제 실패 화면 복귀 시 보고
|
||||
*
|
||||
* 브라우저 리턴 콜백(PC·모바일·해외결제)은 PG 서명도 IP 증명도 없어 주문 상태를 바꾸지 않는다.
|
||||
* 승인이 거절된 정당한 실패는 이 경로(소유권 대조 close-report)로만 기록된다.
|
||||
* 전체 페이지 이동으로 window 컨텍스트가 사라지므로 sessionStorage 로 이어받는다.
|
||||
*/
|
||||
describe('결제 실패 화면 복귀 보고', () => {
|
||||
const CONTEXT = {
|
||||
closeReportUrl: '/plugins/sirsoft-pay_kginicis/payment/close-report',
|
||||
oid: 'ORD-KGI-RETURN-001',
|
||||
price: 10000,
|
||||
buyer_email: 'buyer@example.com',
|
||||
buyer_phone: '01012345678',
|
||||
};
|
||||
|
||||
/**
|
||||
* 화면 주소를 바꿔 결제 리턴 상황을 재현한다.
|
||||
*/
|
||||
function setLocation(pathname: string, search: string): void {
|
||||
Object.defineProperty(window, 'location', {
|
||||
configurable: true,
|
||||
value: { pathname, search, origin: 'https://shop.example' },
|
||||
});
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
window.sessionStorage.clear();
|
||||
clearStandardPaymentCloseReportContext();
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
delete windowRecord().G7Core;
|
||||
vi.restoreAllMocks();
|
||||
window.sessionStorage.clear();
|
||||
clearStandardPaymentCloseReportContext();
|
||||
});
|
||||
|
||||
it('실패 화면으로 돌아오면 저장해 둔 구매자 정보로 보고한다', async () => {
|
||||
const apiPost = vi.fn().mockResolvedValue({ success: true });
|
||||
windowRecord().G7Core = { api: { post: apiPost } };
|
||||
|
||||
markStandardPaymentCloseReportContext(CONTEXT);
|
||||
// 전체 페이지 이동으로 window 컨텍스트가 사라진 상황을 재현한다.
|
||||
delete windowRecord()['__sirsoftKginicisActiveStandardPaymentCloseContext'];
|
||||
|
||||
setLocation('/shop/checkout', '?error=9999&message=fail&orderId=ORD-KGI-RETURN-001');
|
||||
|
||||
await reportStandardPaymentFailureOnReturn();
|
||||
|
||||
expect(apiPost).toHaveBeenCalledWith(
|
||||
'/plugins/sirsoft-pay_kginicis/payment/close-report',
|
||||
expect.objectContaining({ oid: 'ORD-KGI-RETURN-001', price: 10000 }),
|
||||
);
|
||||
});
|
||||
|
||||
it('두 번 호출해도 한 번만 보고한다', async () => {
|
||||
const apiPost = vi.fn().mockResolvedValue({ success: true });
|
||||
windowRecord().G7Core = { api: { post: apiPost } };
|
||||
|
||||
markStandardPaymentCloseReportContext(CONTEXT);
|
||||
setLocation('/shop/checkout', '?error=9999&orderId=ORD-KGI-RETURN-001');
|
||||
|
||||
await reportStandardPaymentFailureOnReturn();
|
||||
await reportStandardPaymentFailureOnReturn();
|
||||
|
||||
expect(apiPost).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it('다른 주문번호로 돌아왔으면 보고하지 않는다', async () => {
|
||||
const apiPost = vi.fn();
|
||||
windowRecord().G7Core = { api: { post: apiPost } };
|
||||
|
||||
markStandardPaymentCloseReportContext(CONTEXT);
|
||||
setLocation('/shop/checkout', '?error=9999&orderId=ORD-KGI-OTHER');
|
||||
|
||||
await reportStandardPaymentFailureOnReturn();
|
||||
|
||||
expect(apiPost).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('결제 완료 화면으로 돌아오면 보고하지 않고 저장분만 지운다', async () => {
|
||||
const apiPost = vi.fn();
|
||||
windowRecord().G7Core = { api: { post: apiPost } };
|
||||
|
||||
markStandardPaymentCloseReportContext(CONTEXT);
|
||||
setLocation('/shop/orders/ORD-KGI-RETURN-001/complete', '');
|
||||
|
||||
await reportStandardPaymentFailureOnReturn();
|
||||
|
||||
expect(apiPost).not.toHaveBeenCalled();
|
||||
expect(window.sessionStorage.getItem('g7:sirsoft-pay_kginicis:pendingClose')).toBeNull();
|
||||
});
|
||||
|
||||
it('상점이 실패 주소를 바꿔 체크아웃 경로가 아니어도 보고한다', async () => {
|
||||
const apiPost = vi.fn().mockResolvedValue({ success: true });
|
||||
windowRecord().G7Core = { api: { post: apiPost } };
|
||||
|
||||
markStandardPaymentCloseReportContext(CONTEXT);
|
||||
delete windowRecord()['__sirsoftKginicisActiveStandardPaymentCloseContext'];
|
||||
|
||||
setLocation('/store/payment-failed', '?error=9999&orderId=ORD-KGI-RETURN-001');
|
||||
|
||||
await reportStandardPaymentFailureOnReturn();
|
||||
|
||||
expect(apiPost).toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('저장분이 없으면 아무것도 보내지 않는다', async () => {
|
||||
const apiPost = vi.fn();
|
||||
windowRecord().G7Core = { api: { post: apiPost } };
|
||||
|
||||
setLocation('/shop/checkout', '?error=9999&orderId=ORD-KGI-RETURN-001');
|
||||
|
||||
await reportStandardPaymentFailureOnReturn();
|
||||
|
||||
expect(apiPost).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
@@ -4,7 +4,10 @@ import { installMypageOrderShowInjector } from './mypageOrderShowInjector';
|
||||
import { installAdminOrderPaymentDisplayInjector } from './adminOrderPaymentDisplayInjector';
|
||||
import { installOrderCompleteReceiptInjector } from './orderCompleteReceiptInjector';
|
||||
import { installVbankInfoInjector } from './vbankInfoInjector';
|
||||
import { installPaymentCloseMessageListener } from './paymentCloseMessageListener';
|
||||
import {
|
||||
installPaymentCloseMessageListener,
|
||||
reportStandardPaymentFailureOnReturn,
|
||||
} from './paymentCloseMessageListener';
|
||||
import { installCheckoutJpyPaymentMethodRestrictor } from './checkoutJpyPaymentMethodRestrictor';
|
||||
import { installAdminPaymentMethodBrandInjector } from './adminPaymentMethodBrandInjector';
|
||||
|
||||
@@ -95,6 +98,11 @@ installOrderCompleteReceiptInjector();
|
||||
installVbankInfoInjector();
|
||||
installPaymentCloseMessageListener();
|
||||
|
||||
// 결제 실패로 돌아온 화면이면 서버에 보고한다. 브라우저 리턴 콜백(PC·모바일·해외결제)은
|
||||
// PG 서명도 IP 증명도 없어 주문 상태를 바꾸지 않으므로, 소유권을 대조하는 close-report 가
|
||||
// 정당한 결제 실패를 기록하는 유일한 경로다. 저장해 둔 정보가 없으면 아무 일도 하지 않는다.
|
||||
void reportStandardPaymentFailureOnReturn();
|
||||
|
||||
initPlugin();
|
||||
|
||||
(window as Record<string, unknown>).__SirsoftKginicis = {
|
||||
|
||||
@@ -76,6 +76,26 @@ function resolveApiUrl(url: string): string {
|
||||
return url;
|
||||
}
|
||||
|
||||
/**
|
||||
* 결제 실패 화면으로 돌아왔을 때 보고에 쓸 컨텍스트를 남겨 두는 저장소 키.
|
||||
*
|
||||
* window 전역만 쓰면 결제창이 전체 페이지 이동으로 열리고 돌아올 때 컨텍스트가 소실된다.
|
||||
* sessionStorage 는 같은 탭에서 외부 도메인을 다녀와도 유지되므로 함께 저장한다.
|
||||
*/
|
||||
const PENDING_CLOSE_STORAGE_KEY = 'g7:sirsoft-pay_kginicis:pendingClose';
|
||||
|
||||
/**
|
||||
* sessionStorage 접근은 브라우저 설정(사이트 데이터 차단·시크릿 모드)에 따라 예외를 던진다.
|
||||
* 보고는 편의 장치이므로 실패해도 결제 흐름을 막지 않는다.
|
||||
*/
|
||||
function safeSessionStorage(): Storage | null {
|
||||
try {
|
||||
return window.sessionStorage ?? null;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
export function markStandardPaymentCloseReportContext(
|
||||
context: StandardPaymentCloseReportContext,
|
||||
): void {
|
||||
@@ -87,10 +107,99 @@ export function markStandardPaymentCloseReportContext(
|
||||
...context,
|
||||
reported: false,
|
||||
};
|
||||
|
||||
// 전체 페이지 이동(모바일·PC 리턴 콜백)을 건너 살아남도록 함께 보관한다.
|
||||
try {
|
||||
safeSessionStorage()?.setItem(
|
||||
PENDING_CLOSE_STORAGE_KEY,
|
||||
JSON.stringify({ ...context, reported: false }),
|
||||
);
|
||||
} catch {
|
||||
// 저장 실패는 무시 — 만료 자동 정리가 최종 안전망이다.
|
||||
}
|
||||
}
|
||||
|
||||
export function clearStandardPaymentCloseReportContext(): void {
|
||||
delete windowRecord()[ACTIVE_STANDARD_PAYMENT_CLOSE_CONTEXT_KEY];
|
||||
|
||||
try {
|
||||
safeSessionStorage()?.removeItem(PENDING_CLOSE_STORAGE_KEY);
|
||||
} catch {
|
||||
// 무시
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 저장해 둔 보고용 컨텍스트를 읽습니다.
|
||||
*
|
||||
* @returns 저장된 컨텍스트, 없거나 형식이 깨졌으면 null
|
||||
*/
|
||||
function readPendingCloseFromStorage(): StandardPaymentCloseReportContext | null {
|
||||
try {
|
||||
const raw = safeSessionStorage()?.getItem(PENDING_CLOSE_STORAGE_KEY);
|
||||
if (!raw) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const parsed = JSON.parse(raw) as StandardPaymentCloseReportContext;
|
||||
|
||||
return parsed && typeof parsed.oid === 'string' && parsed.oid !== '' && parsed.closeReportUrl
|
||||
? parsed
|
||||
: null;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 결제 실패 화면으로 돌아왔으면 저장해 둔 정보로 서버에 보고합니다.
|
||||
*
|
||||
* 브라우저 리턴 콜백(PC·모바일·해외결제)은 PG 서명도 IP 증명도 없어 주문 상태를 바꾸지 않는다.
|
||||
* 소유권을 대조하는 close-report 만이 정당한 결제 실패를 기록할 수 있으므로, 실패 화면에
|
||||
* 도착한 이 시점에 그 경로로 보고한다. 플러그인 부팅 시 1회 호출한다.
|
||||
*/
|
||||
export async function reportStandardPaymentFailureOnReturn(): Promise<void> {
|
||||
const pending = readPendingCloseFromStorage();
|
||||
if (!pending) {
|
||||
return;
|
||||
}
|
||||
|
||||
let params: URLSearchParams;
|
||||
try {
|
||||
params = new URLSearchParams(window.location.search);
|
||||
} catch {
|
||||
return;
|
||||
}
|
||||
|
||||
const orderIdInUrl = params.get('orderId') ?? '';
|
||||
|
||||
// 저장분과 화면의 주문번호가 다르면 이번 이동과 무관한 잔여물이다.
|
||||
if (orderIdInUrl !== '' && orderIdInUrl !== pending.oid) {
|
||||
return;
|
||||
}
|
||||
|
||||
// 결제 완료 화면으로 돌아왔으면 보고 대상이 아니다 — 성공 확정은 서버가 이미 했다.
|
||||
if (/\/(complete|success)(\/|$|\?)/.test(window.location.pathname)) {
|
||||
clearStandardPaymentCloseReportContext();
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
const code = params.get('error') ?? '';
|
||||
const message = params.get('message') ?? '';
|
||||
|
||||
// 실패 표시가 전혀 없으면 결제창을 열기만 하고 돌아온 경우일 수 있다 — 판단하지 않는다.
|
||||
if (code === '' && orderIdInUrl === '') {
|
||||
return;
|
||||
}
|
||||
|
||||
// window 전역 컨텍스트를 복원해 기존 보고 경로를 그대로 태운다 (중복 보고 가드 포함).
|
||||
windowRecord()[ACTIVE_STANDARD_PAYMENT_CLOSE_CONTEXT_KEY] = { ...pending, reported: false };
|
||||
|
||||
await reportStandardPaymentWindowClosed(
|
||||
message !== '' ? message : code || 'payment-window-closed',
|
||||
false,
|
||||
);
|
||||
}
|
||||
|
||||
export function markStandardPaymentCompletionStarted(): void {
|
||||
@@ -99,9 +208,12 @@ export function markStandardPaymentCompletionStarted(): void {
|
||||
|
||||
export async function reportStandardPaymentWindowClosed(
|
||||
reason = 'payment-window-closed',
|
||||
requireCheckoutPage = true,
|
||||
): Promise<void> {
|
||||
// 결제창 닫힘 메시지 경로는 체크아웃 화면에서만 유효하다. 반면 리턴 콜백에서 돌아온 경우는
|
||||
// 상점이 실패 주소를 바꿨을 수 있어 화면 경로로 판정할 수 없다 — 그때는 이 검사를 건너뛴다.
|
||||
const context = getActiveStandardPaymentCloseContext();
|
||||
if (!context || context.reported || !isCheckoutPage()) {
|
||||
if (!context || context.reported || (requireCheckoutPage && !isCheckoutPage())) {
|
||||
return;
|
||||
}
|
||||
|
||||
|
||||
@@ -198,8 +198,9 @@ class CbtCallbackController
|
||||
'result_msg' => $resultMsg,
|
||||
]);
|
||||
|
||||
$this->orderService->failPayment($order, $resultCode, $resultMsg);
|
||||
|
||||
// 승인이 성립하지 않았다 — 실제로 결제된 것이 없으므로 주문 상태를 바꾸지 않는다.
|
||||
// 브라우저 실패(authResultCode)는 이미 무변경으로 하드닝되어 있으나, 서버 승인
|
||||
// 실패 분기는 여전히 비인증 입력(sid + oid)으로 도달할 수 있어 같은 통로가 열려 있었다.
|
||||
return redirect($this->resolveFailUrl($this->buildCbtFailureRedirectParams(
|
||||
(string) $resultCode,
|
||||
(string) $resultMsg,
|
||||
|
||||
@@ -203,8 +203,10 @@ class MobileCallbackController
|
||||
'P_RMESG1' => $result['P_RMESG1'] ?? '',
|
||||
]);
|
||||
|
||||
$this->orderService->failPayment($order, $resultStatus, $result['P_RMESG1'] ?? '');
|
||||
|
||||
// 승인이 성립하지 않았다 — 실제로 결제된 것이 없으므로 주문 상태를 바꾸지 않는다.
|
||||
// 비인증 브라우저 콜백이라 주문번호(P_OID)와 P_TID 는 요청자가 고른 값이고,
|
||||
// 그 조합으로 만든 "승인 실패" 로 타인의 결제대기 주문을 취소시킬 수 있다.
|
||||
// 정당한 결제창 닫힘은 소유권을 검증하는 close-report 가 기록한다.
|
||||
return redirect($this->resolveFailUrl([
|
||||
'error' => $resultStatus,
|
||||
'message' => $result['P_RMESG1'] ?? '',
|
||||
|
||||
@@ -255,8 +255,11 @@ class PaymentCallbackController
|
||||
'result_msg' => $pgResponse['resultMsg'] ?? '',
|
||||
]);
|
||||
|
||||
$this->orderService->failPayment($order, $pgResultCode, $pgResponse['resultMsg'] ?? '');
|
||||
|
||||
// 승인이 성립하지 않았다 — 실제로 결제된 것이 없으므로 주문 상태를 바꾸지 않는다.
|
||||
// 이 엔드포인트는 PG 서명도 IP 증명도 없는 비인증 브라우저 POST 이고 주문번호(moid)도
|
||||
// 요청자가 고른 값이라, "승인 실패" 는 남의 주문번호와 위조 authToken 을 보내기만 해도
|
||||
// 만들어낼 수 있는 상태다. 그것을 근거로 실패 처리하면 타인의 결제대기 주문이 취소된다.
|
||||
// 정당한 결제창 닫힘은 소유권을 검증하는 close-report 가 기록한다.
|
||||
return redirect($this->resolveFailUrl([
|
||||
'error' => $pgResultCode,
|
||||
'message' => $pgResponse['resultMsg'] ?? '',
|
||||
|
||||
+43
@@ -294,10 +294,53 @@ class PaymentCallbackControllerTest extends PluginTestCase
|
||||
], 200),
|
||||
]);
|
||||
|
||||
$statusBefore = $order->order_status;
|
||||
|
||||
$response = $this->post('/plugins/sirsoft-pay_kginicis/payment/callback', $params);
|
||||
|
||||
$response->assertRedirect();
|
||||
$this->assertStringContainsString('error=9999', $response->headers->get('Location'));
|
||||
|
||||
// 계약 변경(KVE-2026-2018 형제): 승인이 성립하지 않은 비인증 브라우저 콜백은
|
||||
// 주문 상태를 바꾸지 않는다. 정당한 결제창 닫힘은 close-report 가 기록한다.
|
||||
$order->refresh();
|
||||
$this->assertEquals($statusBefore, $order->order_status, '비인증 콜백이 주문 상태를 바꿨습니다.');
|
||||
$this->assertNotEquals(OrderStatusEnum::CANCELLED, $order->order_status);
|
||||
}
|
||||
|
||||
/**
|
||||
* 무인증 위조 콜백으로 타인의 결제대기 주문을 취소할 수 없다.
|
||||
*
|
||||
* 공격자는 로그인하지 않고 피해자의 주문번호(moid)와 위조 authToken 만으로 이 엔드포인트를
|
||||
* 친다. 서버 승인은 당연히 실패하는데, 그 실패를 주문 실패로 오인 처리하면 남의 주문이 취소된다.
|
||||
*/
|
||||
public function test_forged_unauthenticated_callback_cannot_cancel_another_users_order(): void
|
||||
{
|
||||
$victimOrder = $this->createTestOrder(50000);
|
||||
$this->mockPluginSettings();
|
||||
|
||||
$params = $this->makeCallbackParams($victimOrder->order_number, 50000);
|
||||
$params['authToken'] = 'FORGED_AUTH_TOKEN';
|
||||
|
||||
Http::fake([
|
||||
'fcstdpay.inicis.com/api/payAuth' => Http::response([
|
||||
'resultCode' => '9999',
|
||||
'resultMsg' => '인증정보가 올바르지 않습니다',
|
||||
], 200),
|
||||
'*' => Http::response('OK', 200),
|
||||
]);
|
||||
|
||||
$response = $this->post('/plugins/sirsoft-pay_kginicis/payment/callback', $params);
|
||||
|
||||
$response->assertRedirect();
|
||||
|
||||
$victimOrder->refresh();
|
||||
$this->assertEquals(
|
||||
OrderStatusEnum::PENDING_ORDER,
|
||||
$victimOrder->order_status,
|
||||
'무인증 위조 콜백이 피해자의 주문을 취소시켰습니다.'
|
||||
);
|
||||
$this->assertArrayNotHasKey('payment_failure_code', $victimOrder->order_meta ?? []);
|
||||
}
|
||||
|
||||
public function test_auth_callback_sends_net_cancel_and_redirects_to_fail_on_authorize_http_error(): void
|
||||
|
||||
@@ -0,0 +1,102 @@
|
||||
/**
|
||||
* KG이니시스 플러그인 Playwright E2E 설정.
|
||||
*
|
||||
* 코어 `playwright.config.ts` 와 동일한 base URL 해석 우선순위를 따른다 — 플러그인도 활성 호스트가
|
||||
* 가변(개발자/CI/운영 환경별로 다른 도메인)이므로 하드코딩 회피.
|
||||
*
|
||||
* Base URL 해석:
|
||||
* 1. PLAYWRIGHT_BASE_URL 환경변수 (CI/명시적 오버라이드)
|
||||
* 2. .env (코어 루트) 의 APP_URL — 단 localhost 류는 fallback 부적합
|
||||
* 3. 그 외 — 명시 에러
|
||||
*
|
||||
* 실행 예시:
|
||||
* PowerShell — $env:PLAYWRIGHT_BASE_URL='https://g7.dev'; npm run test:e2e
|
||||
* Bash — PLAYWRIGHT_BASE_URL=https://g7.dev npm run test:e2e
|
||||
*
|
||||
* 플러그인은 코어 fixture 의 `issueToken` / `authenticatePage` 헬퍼를 재사용 — 권한 식별자는
|
||||
* `sirsoft-pay_kginicis.*` 등 임의 string.
|
||||
*/
|
||||
import { defineConfig, devices } from '@playwright/test';
|
||||
import { readFileSync, existsSync } from 'node:fs';
|
||||
import { dirname, resolve } from 'node:path';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
|
||||
// ESM 환경(package.json "type": "module")에서는 __dirname 이 정의되지 않으므로
|
||||
// import.meta.url 로 재구성한다.
|
||||
const __dirname = dirname(fileURLToPath(import.meta.url));
|
||||
|
||||
/**
|
||||
* 코어 루트 (artisan / .env / Playwright 산출물의 기준 경로).
|
||||
*
|
||||
* 확장 config 는 확장 디렉토리에서 실행되지만, 산출물을 그 안에 쓰면 Windows 에서
|
||||
* `plugin:update` 의 디렉토리 이동이 열린 핸들에 걸려 실패한다.
|
||||
* 산출물은 코어 루트 아래로 모아 update 경로와 분리한다 (.gitignore 가 이미 덮는 위치).
|
||||
*/
|
||||
const CORE_ROOT = process.env.G7_ROOT || resolve(__dirname, '../../../../../');
|
||||
|
||||
/** 확장별 산출물 격리 — 확장끼리 리포트를 덮어쓰지 않도록 slug 로 네임스페이스. */
|
||||
const ARTIFACT_SLUG = 'plugins/sirsoft-pay_kginicis';
|
||||
|
||||
function readEnvFile(filePath: string, key: string): string | null {
|
||||
if (!existsSync(filePath)) return null;
|
||||
const content = readFileSync(filePath, { encoding: 'utf-8' });
|
||||
const pattern = new RegExp(`^${key}=(.*)$`, 'm');
|
||||
const match = content.match(pattern);
|
||||
if (!match) return null;
|
||||
let value = match[1].trim();
|
||||
if ((value.startsWith('"') && value.endsWith('"')) || (value.startsWith("'") && value.endsWith("'"))) {
|
||||
value = value.slice(1, -1);
|
||||
}
|
||||
return value || null;
|
||||
}
|
||||
|
||||
function resolveBaseUrl(): string {
|
||||
if (process.env.PLAYWRIGHT_BASE_URL) {
|
||||
return process.env.PLAYWRIGHT_BASE_URL;
|
||||
}
|
||||
const appUrl = readEnvFile(resolve(CORE_ROOT, '.env'), 'APP_URL');
|
||||
if (appUrl && !/^https?:\/\/localhost(:\d+)?\/?$/i.test(appUrl)) {
|
||||
return appUrl;
|
||||
}
|
||||
throw new Error(
|
||||
'KG이니시스 플러그인 E2E base URL 미설정. PLAYWRIGHT_BASE_URL 환경변수를 지정하거나 코어 .env 의 APP_URL 을 활성 호스트로 설정하세요.'
|
||||
);
|
||||
}
|
||||
|
||||
export default defineConfig({
|
||||
testDir: './specs',
|
||||
outputDir: resolve(CORE_ROOT, 'test-results', ARTIFACT_SLUG),
|
||||
fullyParallel: true,
|
||||
forbidOnly: !!process.env.CI,
|
||||
retries: process.env.CI ? 2 : 0,
|
||||
workers: process.env.CI ? 1 : undefined,
|
||||
reporter: [
|
||||
['html', { outputFolder: resolve(CORE_ROOT, 'playwright-report', ARTIFACT_SLUG), open: 'never' }],
|
||||
['list'],
|
||||
],
|
||||
use: {
|
||||
// 실제 브라우저 UA 를 지정한다.
|
||||
//
|
||||
// Playwright 기본 UA 에는 `HeadlessChrome` 이 들어 있어 `SeoMiddleware` 의 봇 판정에
|
||||
// 걸린다. 그러면 공개 사용자 경로 요청이 SPA 가 아니라 **검색엔진용 정적 HTML** 을
|
||||
// 받는다 — `window.G7Core` 도 엔진 스크립트도 없는 화면이다. 그 상태에서도 서버가
|
||||
// 심은 글꼴·아이콘은 정상이라 "페이지가 잘 뜬다" 로 보이고, 정작 재려던 SPA 동작
|
||||
// (테마 적용·핸들러·확장 번들 로드)은 한 번도 실행되지 않은 채 통과한다.
|
||||
//
|
||||
// 봇 경로를 의도적으로 재는 spec 은 UA 가 아니라 `?_escaped_fragment_=` 로 유발하므로
|
||||
// 여기서 실제 UA 를 고정해도 그 검증은 그대로 동작한다.
|
||||
userAgent:
|
||||
'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/140.0.0.0 Safari/537.36',
|
||||
baseURL: resolveBaseUrl(),
|
||||
// spec 이 한국어 화면 문구를 단언하므로 로케일을 고정한다.
|
||||
// 로케일 우선순위는 localStorage g7_locale → 서버 응답값 → 'ko' 이고, 서버값은 미인증
|
||||
// 요청에서 Accept-Language 로 결정된다(SetLocale 미들웨어). Playwright 의 locale 옵션이
|
||||
// 그 헤더를 만들므로, 지정하지 않으면 첫 페이지 로드가 en-US 로 나가 화면이 영어로 렌더되고
|
||||
// 엔진이 그 값을 localStorage 에 저장해 이후 인증해도 세션 전체가 영어로 고정된다.
|
||||
locale: 'ko-KR',
|
||||
trace: 'retain-on-failure',
|
||||
screenshot: 'only-on-failure',
|
||||
ignoreHTTPSErrors: true,
|
||||
},
|
||||
projects: [{ name: 'chromium', use: { ...devices['Desktop Chrome'] } }],
|
||||
});
|
||||
+114
@@ -0,0 +1,114 @@
|
||||
/**
|
||||
* E2E: 결제 실패 화면 복귀 시 close-report 보고 회귀 가드
|
||||
*
|
||||
* @scenario payment_failure_return_reports_to_close_report
|
||||
* @effects close_report_posted_on_failure_return, no_report_without_pending_context,
|
||||
* no_report_on_success_return
|
||||
*
|
||||
* 배경: 브라우저 리턴 콜백(PC·모바일·해외결제)은 PG 서명도 IP 증명도 없고 주문번호가
|
||||
* 요청자가 고른 값이라, 승인 실패를 근거로 주문을 취소하면 남의 주문번호를 아는 것만으로
|
||||
* 그 주문이 취소된다. 그래서 콜백에서 주문 상태 변경을 걷어냈고, 정당한 결제 실패는
|
||||
* 구매자 정보를 대조하는 close-report 가 기록하도록 바꿨다.
|
||||
*
|
||||
* 결제창은 전체 페이지 이동으로 열리고 돌아와 JS 컨텍스트가 소실되므로, 결제 요청 직전에
|
||||
* sessionStorage 에 남긴 정보로 실패 화면에서 보고한다. 이 spec 은 그 복귀 보고가 실제
|
||||
* 브라우저에서 발화하는지를 지킨다 — 발화하지 않으면 정당한 결제 실패가 어디에도 기록되지
|
||||
* 않는데, 화면에는 아무 증상도 나타나지 않는다.
|
||||
*
|
||||
* PG 결제창 자체는 자동화할 수 없으므로, 결제 요청 직전 상태(sessionStorage 마커)를 직접
|
||||
* 심어 "실패 화면으로 돌아온 순간" 부터를 재현한다. 서버 응답(403/404 등)은 이 spec 의
|
||||
* 관심사가 아니다 — 브라우저가 보고를 보내는지가 계약이다.
|
||||
*/
|
||||
import { expect, test } from '@playwright/test';
|
||||
|
||||
const STORAGE_KEY = 'g7:sirsoft-pay_kginicis:pendingClose';
|
||||
|
||||
const CLOSE_REPORT_URL = '/api/plugins/sirsoft-pay_kginicis/payment/close-report';
|
||||
|
||||
const ORDER_NUMBER = 'E2E-KGI-FAILRETURN-0001';
|
||||
|
||||
/**
|
||||
* 결제 요청 직전에 저장되는 보고용 컨텍스트를 심는다.
|
||||
*/
|
||||
const PENDING_CONTEXT = {
|
||||
closeReportUrl: '/plugins/sirsoft-pay_kginicis/payment/close-report',
|
||||
oid: ORDER_NUMBER,
|
||||
price: 10000,
|
||||
buyer_email: 'e2e-buyer@example.com',
|
||||
buyer_phone: '01012345678',
|
||||
payment_method: 'card',
|
||||
reported: false,
|
||||
};
|
||||
|
||||
test.describe('KG이니시스 결제 실패 복귀 보고', () => {
|
||||
test('실패 화면으로 돌아오면 close-report 로 보고한다', async ({ page }) => {
|
||||
// 오리진을 확보한 뒤 sessionStorage 를 심는다 (하드코딩 회피).
|
||||
await page.goto('/shop/checkout');
|
||||
await page.evaluate(
|
||||
([key, value]) => window.sessionStorage.setItem(key, value),
|
||||
[STORAGE_KEY, JSON.stringify(PENDING_CONTEXT)] as const,
|
||||
);
|
||||
|
||||
const reportRequest = page.waitForRequest(
|
||||
(request) => request.url().includes(CLOSE_REPORT_URL) && request.method() === 'POST',
|
||||
{ timeout: 20_000 },
|
||||
);
|
||||
|
||||
// 결제 승인이 거절되어 실패 URL 로 돌아온 상황.
|
||||
await page.goto(`/shop/checkout?error=9999&message=fail&orderId=${ORDER_NUMBER}`);
|
||||
|
||||
const request = await reportRequest;
|
||||
const body = request.postDataJSON() as Record<string, unknown>;
|
||||
|
||||
expect(body.oid).toBe(ORDER_NUMBER);
|
||||
expect(body.price).toBe(10000);
|
||||
// 소유권 대조에 쓰이는 구매자 정보가 실려야 서버가 자격을 판정할 수 있다.
|
||||
expect(body.buyer_email).toBe('e2e-buyer@example.com');
|
||||
expect(body.buyer_phone).toBe('01012345678');
|
||||
});
|
||||
|
||||
test('저장해 둔 정보가 없으면 보고하지 않는다', async ({ page }) => {
|
||||
await page.goto('/shop/checkout');
|
||||
await page.evaluate((key) => window.sessionStorage.removeItem(key), STORAGE_KEY);
|
||||
|
||||
let reported = false;
|
||||
page.on('request', (request) => {
|
||||
if (request.url().includes(CLOSE_REPORT_URL) && request.method() === 'POST') {
|
||||
reported = true;
|
||||
}
|
||||
});
|
||||
|
||||
await page.goto(`/shop/checkout?error=9999&orderId=${ORDER_NUMBER}`);
|
||||
await page.waitForLoadState('networkidle', { timeout: 20_000 });
|
||||
|
||||
// 결제창을 연 적이 없는데 실패 파라미터만 붙은 주소로 들어온 경우다 — 보고 대상이 아니다.
|
||||
expect(reported).toBe(false);
|
||||
});
|
||||
|
||||
test('보고 후에는 저장분이 지워져 중복 보고하지 않는다', async ({ page }) => {
|
||||
await page.goto('/shop/checkout');
|
||||
await page.evaluate(
|
||||
([key, value]) => window.sessionStorage.setItem(key, value),
|
||||
[STORAGE_KEY, JSON.stringify(PENDING_CONTEXT)] as const,
|
||||
);
|
||||
|
||||
await page.goto(`/shop/checkout?error=9999&orderId=${ORDER_NUMBER}`);
|
||||
await page.waitForLoadState('networkidle', { timeout: 20_000 });
|
||||
|
||||
const remaining = await page.evaluate((key) => window.sessionStorage.getItem(key), STORAGE_KEY);
|
||||
expect(remaining).toBeNull();
|
||||
|
||||
// 같은 주소를 다시 열어도 보고가 반복되지 않는다.
|
||||
let reportedAgain = false;
|
||||
page.on('request', (request) => {
|
||||
if (request.url().includes(CLOSE_REPORT_URL) && request.method() === 'POST') {
|
||||
reportedAgain = true;
|
||||
}
|
||||
});
|
||||
|
||||
await page.goto(`/shop/checkout?error=9999&orderId=${ORDER_NUMBER}`);
|
||||
await page.waitForLoadState('networkidle', { timeout: 20_000 });
|
||||
|
||||
expect(reportedAgain).toBe(false);
|
||||
});
|
||||
});
|
||||
+36
-3
@@ -1,6 +1,6 @@
|
||||
# audit:allow test-scenario-coverage reason: Phase 2 SSoT — 본 매니페스트는 KG 이니시스 콜백 보안 매트릭스의 명세 문서. 단위 테스트(ValidatesTimestampFreshnessTest 13건) 가 freshness 핵심 경로를 커버하며, replay/net-cancel 의 cross product 전체 자동 검증은 Phase 3 (침투 PoC) 에서 처리.
|
||||
|
||||
feature: 콜백 보안 방어 (replay attack / signature timestamp freshness / post-approve net cancel)
|
||||
feature: 콜백 보안 방어 (replay attack / signature timestamp freshness / post-approve net cancel / 비인증 브라우저 콜백의 주문 변조)
|
||||
|
||||
description: |
|
||||
KG 이니시스 결제 콜백 처리 경로의 3가지 핵심 보안 위협에 대한 방어 매트릭스.
|
||||
@@ -18,8 +18,9 @@ description: |
|
||||
|
||||
axes:
|
||||
context: [authCallback_card, vbankNotify, mobileApproval_card, mobileVbankNotify, cbtCallback]
|
||||
threat: [replay, stale_timestamp, post_approve_failure]
|
||||
callback_state: [first_arrival, second_arrival_same_tid, signature_expired, signature_fresh, domain_succeeds, domain_fails]
|
||||
threat: [replay, stale_timestamp, post_approve_failure, forged_browser_callback]
|
||||
callback_state: [first_arrival, second_arrival_same_tid, signature_expired, signature_fresh, domain_succeeds, domain_fails, authorize_not_yet_attempted, authorize_failed, authorize_succeeded]
|
||||
caller: [pg_server_verified, unauthenticated_browser, ownership_verified_buyer]
|
||||
|
||||
exclusions:
|
||||
- { threat: replay, callback_state: signature_expired, reason: "replay 시나리오는 timestamp 와 무관" }
|
||||
@@ -38,6 +39,26 @@ exclusions:
|
||||
- { threat: post_approve_failure, context: vbankNotify, reason: "vbank 입금통보는 post-approve 단계 없음 (PG 측 비동기 입금)" }
|
||||
- { threat: post_approve_failure, context: mobileVbankNotify, reason: "vbank 입금통보는 post-approve 단계 없음" }
|
||||
- { threat: post_approve_failure, context: cbtCallback, reason: "CBT 는 별도 일본 결제 API — net cancel 로직 동일 아님 (수동 정산 분기)" }
|
||||
- { threat: forged_browser_callback, callback_state: first_arrival, reason: "위조 콜백은 도착 차수가 아니라 승인 성립 여부로 갈린다" }
|
||||
- { threat: forged_browser_callback, callback_state: second_arrival_same_tid, reason: "동일" }
|
||||
- { threat: forged_browser_callback, callback_state: signature_expired, reason: "위조 축은 timestamp 신선도 단계가 아니다" }
|
||||
- { threat: forged_browser_callback, callback_state: signature_fresh, reason: "동일" }
|
||||
- { threat: forged_browser_callback, callback_state: domain_succeeds, reason: "도메인 처리 이전에 승인 성립 여부로 판정한다" }
|
||||
- { threat: forged_browser_callback, callback_state: domain_fails, reason: "동일" }
|
||||
- { threat: replay, callback_state: authorize_not_yet_attempted, reason: "승인 성립 축은 위조 콜백 전용 — replay 는 도착 차수 분기" }
|
||||
- { threat: replay, callback_state: authorize_failed, reason: "동일" }
|
||||
- { threat: replay, callback_state: authorize_succeeded, reason: "동일" }
|
||||
- { threat: stale_timestamp, callback_state: authorize_not_yet_attempted, reason: "timestamp 는 승인 이전 별개 게이트" }
|
||||
- { threat: stale_timestamp, callback_state: authorize_failed, reason: "동일" }
|
||||
- { threat: stale_timestamp, callback_state: authorize_succeeded, reason: "동일" }
|
||||
- { threat: post_approve_failure, callback_state: authorize_not_yet_attempted, reason: "정의상 승인 이후 분기" }
|
||||
- { threat: post_approve_failure, callback_state: authorize_failed, reason: "동일" }
|
||||
- { threat: post_approve_failure, callback_state: authorize_succeeded, reason: "post-approve 실패는 domain_fails 로 표현한다" }
|
||||
- { caller: ownership_verified_buyer, threat: replay, reason: "close-report 는 결제창 콜백이 아니라 별도 소유권 검증 엔드포인트" }
|
||||
- { caller: ownership_verified_buyer, threat: stale_timestamp, reason: "동일 — PG 서명 타임스탬프를 받지 않는다" }
|
||||
- { caller: ownership_verified_buyer, threat: post_approve_failure, reason: "동일 — 승인 단계가 없다" }
|
||||
- { caller: pg_server_verified, threat: forged_browser_callback, reason: "위조 축의 전제가 비인증 브라우저 입력이다" }
|
||||
- { caller: unauthenticated_browser, threat: stale_timestamp, reason: "타임스탬프 신선도는 PG 서명 페이로드 축" }
|
||||
|
||||
effects:
|
||||
# Replay defense — PreventsReplayCallback trait
|
||||
@@ -63,6 +84,17 @@ effects:
|
||||
- timestamp_long_length_rejected
|
||||
- signature_endpoint_returns_422_on_stale
|
||||
|
||||
# 비인증 브라우저 콜백의 주문 변조 차단 (KVE-2026-2018 형제)
|
||||
- unauthenticated_callback_cannot_cancel_another_users_order
|
||||
- browser_result_code_alone_never_transitions_order_state
|
||||
- pc_auth_callback_failure_branch_does_not_call_fail_payment
|
||||
- mobile_callback_failure_branch_does_not_call_fail_payment
|
||||
- cbt_callback_server_authorize_failure_does_not_call_fail_payment
|
||||
- pg_side_net_cancel_is_kept_because_it_targets_the_pg_not_the_order
|
||||
- legitimate_failure_is_recorded_by_ownership_verified_close_report
|
||||
- close_report_rejects_buyer_mismatch
|
||||
- normal_approval_still_completes_the_order
|
||||
|
||||
# Post-approve net cancel
|
||||
- post_approve_failure_triggers_auto_cancel
|
||||
- net_cancel_sends_pg_cancel_api_call
|
||||
@@ -71,6 +103,7 @@ effects:
|
||||
|
||||
test_files:
|
||||
- plugins/_bundled/sirsoft-pay_kginicis/tests/Unit/Concerns/ValidatesTimestampFreshnessTest.php
|
||||
- plugins/_bundled/sirsoft-pay_kginicis/tests/Feature/Controllers/PaymentCallbackControllerTest.php
|
||||
|
||||
manual_verification:
|
||||
- description: "Replay PoC — vbankNotify 두 번 전송"
|
||||
|
||||
@@ -136,6 +136,11 @@ OS 판별 후 `executeCliWindows()`/`executeCliLinux()` 로 분기 → CLI 인
|
||||
| 동일 `transaction_id` 콜백을 매번 재처리 | `PreventsReplayCallback::wasAlreadyPaid()` 로 이미 `paid` 상태면 멱등 응답 | KCP 서버의 재전송·사용자의 새로고침으로 같은 콜백이 두 번 오면 결제완료 알림·마일리지가 중복 적립될 수 있다 |
|
||||
| 에스크로 공통통보의 `tx_cd`/`cl_status` 매핑을 컨트롤러 밖(리스너 등)에서 다시 판정 | `EscrowCommonNotifyController` 의 매핑표(§핵심 흐름)를 SSoT 로 유지 | 판정 로직이 두 곳에 있으면 KCP 가 새 `cl_status` 값을 보낼 때 한쪽만 갱신되어 조용히 어긋난다 |
|
||||
| 라이브 사이트 키(`live_site_key`)를 로그·에러 메시지에 노출 | 운영 키는 항상 마스킹하거나 로그 대상에서 제외 | 노출되면 제3자가 결제창 요청을 위조할 수 있다 |
|
||||
| 승인 성립 전 실패 분기(브라우저 결과코드·금액 불일치·CLI 승인 거절)에서 `failPayment()` 호출 | 로그 + `resolveFailUrl()` 만. 주문 상태는 건드리지 않는다 | `authCallback` 은 PG 서명도 IP 증명도 없는 비인증 브라우저 POST 이고 `ordr_idxx` 도 요청자가 고른 값이다. 승인 실패는 남의 주문번호와 위조 암호문만으로 만들어낼 수 있으므로, 그것을 근거로 실패 처리하면 타인의 결제대기 주문이 취소된다 |
|
||||
| catch 블록에서 `$approvedTno` 확인 없이 주문을 실패 처리 | `hasApproval($approvedTno)` 가 참일 때만 — tno 는 승인 성공 후에만 채워진다 | 승인 전에 터진 예외까지 반영하면 위 금지 패턴과 같은 통로가 catch 경로로 다시 열린다 |
|
||||
| 정당한 결제 실패 기록을 콜백에서 처리 | 소유권을 검증하는 `close-report`(`requestMatchesOrderBuyer`) 경유 | 구매자 이메일·전화 대조를 통과한 요청만 주문 상태를 바꿔야 한다 |
|
||||
| 결제창 컨텍스트(구매자 정보)를 메모리에만 보관 | `rememberPendingClose()` 로 sessionStorage 에 남기고, 부팅 시 `reportPaymentFailureOnReturn()` 으로 보고 | 결제창은 전체 페이지 이동으로 열리고 돌아와 JS 컨텍스트가 소실된다. 승인 거절은 fail URL 리다이렉트로 끝나므로, 남겨 둔 정보가 없으면 정당한 결제 실패가 어디에도 기록되지 않는다 |
|
||||
| 실패 화면에서 보고가 닿지 못한 주문을 방치 | 이커머스 모듈의 만료 주문 자동 정리가 최종 안전망 | 브라우저를 바로 닫으면 보고가 나가지 않는다. 두 경로가 함께 있어야 선차감 마일리지가 무기한 묶이지 않는다 |
|
||||
<!-- @intent END -->
|
||||
|
||||
## 7. 테스트 실행
|
||||
|
||||
@@ -6,8 +6,15 @@
|
||||
|
||||
## [1.0.4] - 2026-08-31
|
||||
|
||||
### Security
|
||||
|
||||
- 제3자가 남의 주문번호만 알면 결제창을 거치지 않고도 그 주문을 취소시킬 수 있던 문제를 수정했습니다. 결제 결과 콜백은 로그인도 서명 확인도 거치지 않는 경로여서, 위조한 결제 정보를 보내 승인을 일부러 실패시키면 그 주문이 결제 실패로 처리되었습니다. 이제 실제 결제 승인이 이루어진 뒤의 실패만 주문에 반영하며, 승인 전 단계의 실패는 결제 화면으로 되돌려 보내기만 합니다. 구매자가 결제창을 닫아 생기는 정상적인 결제 실패는 종전처럼 기록됩니다. (KISA 측에서 제보해주셨습니다 — KVE-2026-2018)
|
||||
- 같은 결제 결과 콜백에서 가상계좌 경로를 통해서도 남의 주문을 건드릴 수 있던 문제를 수정했습니다. 결제수단을 가상계좌라고 주장하는 값을 요청에 섞으면, 카드로 주문한 건도 결제사 확인을 거치지 않는 경로로 흘러 그 주문이 취소되거나 위조된 입금 계좌가 그 주문에 기록될 수 있었습니다. 이제 결제수단은 요청에 실려 온 값이 아니라 주문에 저장된 값으로만 판단하며, 가상계좌 발급이 확인되지 않은 경우에는 주문을 그대로 두고 결제 화면으로 되돌려 보냅니다.
|
||||
- 취소된 주문을 다시 결제 대기 상태로 되돌리는 처리가, 결제사 승인이 확인되기 전에 이루어지던 문제를 수정했습니다. 주문번호만 알면 남의 취소된 주문을 되살릴 수 있었습니다. 이제 승인이나 계좌 발급이 확인된 뒤에만 되돌립니다.
|
||||
|
||||
### Added
|
||||
|
||||
- 결제가 거절되어 실패 화면으로 돌아오면 그 사실이 자동으로 서버에 기록됩니다. 구매자 본인인지 확인한 뒤에만 주문을 실패로 처리하므로, 남의 주문번호를 아는 것만으로는 그 주문을 건드릴 수 없습니다.
|
||||
- 개발자와 AI 에이전트를 위한 문서를 추가했습니다. 확장 폴더의 `AGENTS.md`(설계 의도·확장점·수정 시 확인할 것)와 `README.md`(도입·운영 안내), `docs/`(상세 문서)로 구성됩니다.
|
||||
- 확장 문서에 「레이아웃 편집기 스펙」 항목을 추가했습니다. 이 확장이 레이아웃 편집기에 무엇을 선언했는지와, 화면 요소나 데이터를 추가할 때 편집기 쪽에서 함께 해야 할 일을 담습니다.
|
||||
- 문서의 제품 표기를 「그누보드7」로 통일했습니다.
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"$schema": "https://json-schema.org/draft/2020-12/schema",
|
||||
"identifier": "sirsoft-pay_nhnkcp",
|
||||
"version": "1.0.1",
|
||||
"version": "1.0.4",
|
||||
"components": {
|
||||
"basic": [],
|
||||
"composite": [],
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
(function(){"use strict";function Le(e){return/^https?:\/\//i.test(e)||e.startsWith("/api/")?e:e.startsWith("/plugins/")?`/api${e}`:e.startsWith("plugins/")?`/api/${e}`:e}function Oe(e){return e.trim().slice(0,160)}function Ke(e){if(e)return e.replace(/\/payment\/close-report$/,"/payment/retry")}async function te(e,t,n=!1){const o=window.G7Core?.api;if(typeof o?.post=="function"){await o.post(e,t);return}const r=await fetch(Le(e),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t),keepalive:n});if(!r.ok){let a=`NHN KCP payment request failed (${r.status})`;try{const s=await r.json(),i=Array.isArray(s?.errors?.message)?s.errors.message[0]:s?.error??s?.message;typeof i=="string"&&i.trim()!==""&&(a=i)}catch{}throw new Error(a)}}async function je(e){const t=Ke(e.closeReportUrl);t&&await te(t,{oid:e.oid,price:Number(e.price),buyer_email:e.buyer_email??"",buyer_phone:e.buyer_phone??"",payment_method:e.payment_method??""})}async function Be(e,t="kcp-window-closed"){if(!e.closeReportUrl)return;const n={oid:e.oid,price:Number(e.price),buyer_email:e.buyer_email??"",buyer_phone:e.buyer_phone??"",payment_method:e.payment_method??"",reason:Oe(t)||"kcp-window-closed"};try{await te(e.closeReportUrl,n,!0)}catch(o){console.warn("[sirsoft-pay_nhnkcp] failed to report payment window close",o)}}const De="nhnkcp_applepay";function S(e){return e===De}function x(){if(typeof navigator>"u")return!1;const e=navigator,t=(e.userAgent||"").toLowerCase(),n=((e.userAgentData?.platform??e.platform)||"").toLowerCase(),o=e.maxTouchPoints??0;return/iphone|ipad|ipod/.test(t)||/iphone|ipad|ipod|ios/.test(n)?!0:/macintosh|mac os x/.test(t)&&o>1}function M(){return((typeof document<"u"?document.documentElement.lang:"")||"").toLowerCase().startsWith("ko")?"애플페이는 IOS 기기에 모바일결제만 가능합니다.":"Apple Pay is available only for mobile payments on iOS devices."}function T(e){return(e??"KRW").trim().toUpperCase()||"KRW"}function He(e){return T(e)==="KRW"}function Fe(e){const t=T(e);return((typeof document<"u"?document.documentElement.lang:"")||"").toLowerCase().startsWith("ko")?`NHN KCP는 KRW 결제만 지원합니다. (${t})`:`NHN KCP supports KRW payments only. (${t})`}function qe(e){const t=Math.max(0,Math.round(Number(e.amount??0))),n=Math.min(Math.max(0,Math.round(Number(e.tax_free_amount??0))),t);if(n<=0)return{};const o=Math.max(0,Math.round(Number(e.tax_amount??0))),r=Math.max(0,Math.round(Number(e.vat_amount??0))),a=Math.max(0,t-n),s=a>0&&o>0&&r>0?Math.min(a,Math.round(a*(r/o))):0,i=a-s;return{tax_flag:"TG03",comm_tax_mny:String(i),comm_vat_mny:String(s),comm_free_mny:String(n)}}class R extends Error{constructor(t){super(t??"결제가 취소되었습니다."),this.name="KcpCancelledError"}}const Ue={card:"100000000000",bank_transfer:"010000000000",virtual_account:"001000000000",mobile:"000010000000",bank:"010000000000",vbank:"001000000000",phone:"000010000000"},ne={nhnkcp_payco:{payco_direct:"Y"},nhnkcp_naverpay:{naverpay_direct:"Y"},nhnkcp_naverpay_point:{naverpay_direct:"Y",naverpay_point_direct:"Y"},nhnkcp_kakaopay:{kakaopay_direct:"Y"},nhnkcp_applepay:{applepay_direct:"Y"}};function Ye(e,t){const n=e.toLowerCase();return!t||!Object.prototype.hasOwnProperty.call(ne,n)?{}:{param_opt_1:n,nhnkcp_easy_pay_method:n}}function Ge(e){if(!e.isConnected)return!0;const t=window.getComputedStyle(e);if(t.display==="none"||t.visibility==="hidden")return!0;const n=e.getBoundingClientRect();return n.width<=0||n.height<=0}function We(e,t){let n=!1,o,r;const a=()=>{n=!0,r&&(r.disconnect(),r=void 0),o!==void 0&&(window.clearInterval(o),o=void 0)},s=()=>{n||!Ge(e)||(a(),t())},i=document.body??document.documentElement;return i&&typeof MutationObserver<"u"&&(r=new MutationObserver(s),r.observe(i,{attributes:!0,attributeFilter:["class","hidden","style"],childList:!0,subtree:!0})),o=window.setInterval(s,300),a}function ze(){if(typeof navigator>"u")return!1;if(x())return!0;const e=navigator;if(e.userAgentData?.mobile!==void 0)return e.userAgentData.mobile;const t=(navigator.userAgent||"").toLowerCase();return!!(/android|iphone|ipod|windows phone|iemobile|blackberry|opera mini|mobile safari/.test(t)||(navigator.maxTouchPoints??0)>1&&!t.includes("windows")&&!t.includes("macintosh"))}async function Je(e,t){const{pgPaymentData:n,paymentMethod:o}=e.params||{};if(!n){console.error("[sirsoft-pay_nhnkcp] pgPaymentData is required");return}const r=o??n.payment_method??n.pay_method??"card",a=typeof r=="string"&&r.startsWith("nhnkcp_"),s=window.G7Core;let i=null;try{if(!He(n.currency)){const u=Fe(n.currency);s?.state?.setLocal?.({paymentErrorMessage:u,isSubmittingOrder:!1,paymentMethod:r}),s?.modal?.open?.("nhnkcp_payment_error_modal");return}if(S(r)&&!x()){const u=M();s?.state?.setLocal?.({paymentErrorMessage:u,isSubmittingOrder:!1,paymentMethod:r}),s?.modal?.open?.("nhnkcp_payment_error_modal");return}const c=await s.api.get("/modules/sirsoft-ecommerce/payments/client-config/nhnkcp");if(!c.data){console.error("[Line truncated
|
||||
(function(){"use strict";function De(e){return/^https?:\/\//i.test(e)||e.startsWith("/api/")?e:e.startsWith("/plugins/")?`/api${e}`:e.startsWith("plugins/")?`/api/${e}`:e}function Be(e){return e.trim().slice(0,160)}function He(e){if(e)return e.replace(/\/payment\/close-report$/,"/payment/retry")}async function oe(e,t,n=!1){const o=window.G7Core?.api;if(typeof o?.post=="function"){await o.post(e,t);return}const r=await fetch(De(e),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t),keepalive:n});if(!r.ok){let a=`NHN KCP payment request failed (${r.status})`;try{const s=await r.json(),i=Array.isArray(s?.errors?.message)?s.errors.message[0]:s?.error??s?.message;typeof i=="string"&&i.trim()!==""&&(a=i)}catch{}throw new Error(a)}}async function Fe(e){const t=He(e.closeReportUrl);t&&await oe(t,{oid:e.oid,price:Number(e.price),buyer_email:e.buyer_email??"",buyer_phone:e.buyer_phone??"",payment_method:e.payment_method??""})}const S="g7:sirsoft-pay_nhnkcp:pendingClose";function M(){try{return window.sessionStorage??null}catch{return null}}function Ue(e){const t=M();if(t)try{t.setItem(S,JSON.stringify(e))}catch{}}function re(){const e=M();if(e)try{e.removeItem(S)}catch{}}function qe(){const e=M();if(!e)return null;try{const t=e.getItem(S);if(!t)return null;const n=JSON.parse(t);return n&&typeof n.oid=="string"&&n.oid!==""?n:null}catch{return null}}async function Ge(){const e=qe();if(!e)return;let t;try{t=new URLSearchParams(window.location.search)}catch{return}const n=t.get("orderId")??"";if(n!==""&&n!==e.oid)return;if(/\/(complete|success)(\/|$|\?)/.test(window.location.pathname)){re();return}const o=t.get("error")??"",r=t.get("message")??"";o===""&&n===""||(re(),await ae(e,r!==""?r:o))}async function ae(e,t="kcp-window-closed"){if(!e.closeReportUrl)return;const n={oid:e.oid,price:Number(e.price),buyer_email:e.buyer_email??"",buyer_phone:e.buyer_phone??"",payment_method:e.payment_method??"",reason:Be(t)||"kcp-window-closed"};try{await oe(e.closeReportUrl,n,!0)}catch(o){console.warn("[sirsoft-pay_nhnkcp] failed to report payment window close",o)}}const Ye="nhnkcp_applepay";function T(e){return e===Ye}function x(){if(typeof navigator>"u")return!1;const e=navigator,t=(e.userAgent||"").toLowerCase(),n=((e.userAgentData?.platform??e.platform)||"").toLowerCase(),o=e.maxTouchPoints??0;return/iphone|ipad|ipod/.test(t)||/iphone|ipad|ipod|ios/.test(n)?!0:/macintosh|mac os x/.test(t)&&o>1}function R(){return((typeof document<"u"?document.documentElement.lang:"")||"").toLowerCase().startsWith("ko")?"애플페이는 IOS 기기에 모바일결제만 가능합니다.":"Apple Pay is available only for mobile payments on iOS devices."}function L(e){return(e??"KRW").trim().toUpperCase()||"KRW"}function We(e){return L(e)==="KRW"}function ze(e){const t=L(e);return((typeof document<"u"?document.documentElement.lang:"")||"").toLowerCase().startsWith("ko")?`NHN KCP는 KRW 결제만 지원합니다. (${t})`:`NHN KCP supports KRW payments only. (${t})`}function Je(e){const t=Math.max(0,Math.round(Number(e.amount??0))),n=Math.min(Math.max(0,Math.round(Number(e.tax_free_amount??0))),t);if(n<=0)return{};const o=Math.max(0,Math.round(Number(e.tax_amount??0))),r=Math.max(0,Math.round(Number(e.vat_amount??0))),a=Math.max(0,t-n),s=a>0&&o>0&&r>0?Math.min(a,Math.round(a*(r/o))):0,i=a-s;return{tax_flag:"TG03",comm_tax_mny:String(i),comm_vat_mny:String(s),comm_free_mny:String(n)}}class $ extends Error{constructor(t){super(t??"결제가 취소되었습니다."),this.name="KcpCancelledError"}}const Ve={card:"100000000000",bank_transfer:"010000000000",virtual_account:"001000000000",mobile:"000010000000",bank:"010000000000",vbank:"001000000000",phone:"000010000000"},se={nhnkcp_payco:{payco_direct:"Y"},nhnkcp_naverpay:{naverpay_direct:"Y"},nhnkcp_naverpay_point:{naverpay_direct:"Y",naverpay_point_direct:"Y"},nhnkcp_kakaopay:{kakaopay_direct:"Y"},nhnkcp_applepay:{applepay_direct:"Y"}};function Qe(e,t){const n=e.toLowerCase();return!t||!Object.prototype.hasOwnProperty.call(se,n)?{}:{param_opt_1:n,nhnkcp_easy_pay_method:n}}function Xe(e){if(!e.isConnected)return!0;const t=window.getComputedStyle(e);if(t.display==="none"||t.visibility==="hidden")return!0;const n=e.getBoundingClientRect();return n.width<=0||n.height<=0}function Ze(e,t){let n=!1,o,r;const a=()=>{n=!0,r&&(r.disconnect(),r=void 0),o!==void 0&&(window.clearInterval(o),o=void 0)},s=()=>{n||!Xe(e)||(a(),t())},i=document.body??document.documentElement;return i&&typeof MutationObserver<"u"&&(r=new MutationObserver(s),r.observe(i,{attributes:!0,attributeFilter:["class","hidden","style"],childList:!0,subtree:!0})),o=window.setInterval(s,300),a}function et(){if(typeof navigator>"u")return!1;if(x())return!0;const e=navigator;if(e.userAgentData?.mobile!==void 0)return e.userAgentData.mobile;const t=(navigator.userAgent||"").toLowerCase();return!!(/android|iphone|ipod|windows phone|iemobile|blackberry|opera mini|mobile safari/.test(t)||(navigator.maxTouchPoints??0)>1&&!t.includLine truncated
|
||||
<script src="${e.sdk_url}"><\/script>
|
||||
</head><body style="margin:0;padding:0;background:transparent;">
|
||||
<form name="order_info">${c}</form>
|
||||
@@ -14,4 +14,4 @@ try {
|
||||
window.__kcpFail && window.__kcpFail(e);
|
||||
}
|
||||
<\/script>
|
||||
</body></html>`),X.close(),y=window.setTimeout(()=>{N(new Error("KCP SDK load timeout"))},15e3),f.__kcpReady=()=>{y!==void 0&&(clearTimeout(y),y=void 0)}})}const Xe={nhnkcp_payco:"PAYCO",nhnkcp_naverpay:"네이버페이",nhnkcp_naverpay_point:"네이버페이 포인트",nhnkcp_kakaopay:"카카오페이",nhnkcp_applepay:"Apple Pay"},Ze="0 0 0 2px #ffffff, 0 0 0 5px rgba(0,0,0,0.55)";function oe(){return document.querySelector(".nhnkcp-easy-pay-btns")??null}function re(){const e=oe();e&&e.querySelectorAll("button").forEach(t=>{t.style.boxShadow="",t.style.outline=""})}function et(e){const t=oe();if(!t)return;const n=Xe[e];t.querySelectorAll("button").forEach(o=>{o.textContent?.trim()===n?(o.style.boxShadow=Ze,o.style.outline="none"):(o.style.boxShadow="",o.style.outline="")})}function tt(e){const t=e.params?.paymentMethod;if(!t)return;const n=window.G7Core;if(S(t)&&!x()){const r=M();n?.state?.setLocal?.({paymentErrorMessage:r,isSubmittingOrder:!1}),n?.modal?.open?.("nhnkcp_payment_error_modal"),re();return}const o=typeof t=="string"&&t.startsWith("nhnkcp_");n?.state?.setLocal?.({paymentMethod:t}),o?et(t):re()}function nt(e){const t=document.createElement("textarea");t.value=e,t.setAttribute("readonly","readonly"),t.style.position="fixed",t.style.left="-9999px",t.style.top="0",document.body.appendChild(t),t.select();try{document.execCommand("copy")}finally{t.remove()}}async function ot(e){const t=String(e.params?.text??"");if(t!==""){if(navigator.clipboard&&typeof navigator.clipboard.writeText=="function"){await navigator.clipboard.writeText(t);return}nt(t)}}const ae={requestPayment:Je,setPaymentMethod:tt,copyToClipboard:ot},se="/api/modules/sirsoft-ecommerce/user/orders",$="sirsoft-pay_nhnkcp",ie={info:(...e)=>console.info(`[${$}]`,...e),warn:(...e)=>console.warn(`[${$}]`,...e),error:(...e)=>console.error(`[${$}]`,...e)};function rt(e){return typeof e=="string"?e:e instanceof URL?e.toString():typeof Request<"u"&&e instanceof Request?e.url:String(e)}function at(e,t){return t?.method?t.method.toUpperCase():typeof Request<"u"&&e instanceof Request?e.method.toUpperCase():"GET"}function st(e,t){if(t!=="POST")return!1;const n=e.split("?")[0].split("#")[0];return n===se||n.endsWith(se)}function it(e){try{return JSON.parse(e).payment_method}catch{return}}function ct(e){return new Response(JSON.stringify({success:!1,message:e,error:e,errors:{payment_method:[e]}}),{status:422,statusText:"Unprocessable Content",headers:{"Content-Type":"application/json"}})}function dt(){if(typeof window>"u"||typeof window.fetch!="function")return;const e="__sirsoftNhnkcpInterceptorInstalled",t=window;if(t[e])return;t[e]=!0;const n=window.fetch.bind(window);window.fetch=async function(r,a){const s=rt(r),i=at(r,a);if(!st(s,i))return n(r,a);let c;if(a?.body&&typeof a.body=="string"&&(c=it(a.body)),S(c)&&!x()){const d=M();return ie.warn(d),ct(d)}return n(r,a)},ie.info("order request interceptor installed (Apple Pay device guard)")}const L="sirsoft-pay_nhnkcp",ce="__kcpOcReceiptInjectorInstalled",de="kcp-oc-receipt-btn",lt=/^\/shop\/orders\/([^/]+)\/complete$/;function le(){return localStorage.getItem("auth_token")}async function ut(e){const t=le();if(!t)return null;try{const n=await fetch(`/api/modules/sirsoft-ecommerce/user/orders/${e}`,{headers:{Authorization:`Bearer ${t}`,Accept:"application/json"}});return n.ok?(await n.json())?.data?.payment??null:null}catch{return null}}async function O(e){const t=le();if(!t)return null;try{const n=await fetch(`/api/plugins/${L}/user/orders/${e}/receipt`,{headers:{Authorization:`Bearer ${t}`,Accept:"application/json"}});return n.ok?await n.json():null}catch{return null}}function ue(e,t,n){const o=document.createElement("button");return o.type="button",o.className=t,o.textContent=e,o.addEventListener("click",()=>n(o)),o}function pt(e){if(!e)return!1;const t=Array.from(document.querySelectorAll("div"));for(const n of t){const o=Array.from(n.children).filter(s=>s instanceof HTMLElement&&s.tagName==="SPAN");if(o.length<2)continue;const r=o[0].textContent?.trim();if(r!=="결제 방법"&&r!=="결제수단"&&r!=="결제 방식")continue;const a=o[o.length-1];return a.textContent?.trim()===e?(n.dataset.nhnkcpPaymentMethodRow="true",!0):(a.textContent=e,a.dataset.nhnkcpPaymentMethodPatched="true",n.dataset.nhnkcpPaymentMethodRow="true",!0)}return!1}async function mt(e){if(document.getElementById(de))return;const t=await ut(e);if(!t||t.pg_provider!=="nhnkcp"||!t.transaction_id||!t.paid_at)return;const n=Array.from(document.querySelectorAll('button[type="button"]')).find(c=>c.className.includes("bg-blue-600"));if(!n?.parentElement)return;const o=await O(e);pt(o?.payment_method_display_label);const r=n.parentElement,a=ue("영수증 조회",n.className.replace(/bg-blue-\d+/g,"bg-green-600").replace(/hover:bg-blue-\d+/g,"hover:bg-green-700"),async c=>{c.disabled=!0,c.textContent="로딩 중...";const d=await O(e);if(c.disabled=!1,c.textContent="영수증 조회",d){const l=window.KcpReceiptPopup;l&&new l({url:d.reLine truncated
|
||||
</body></html>`),ee.close(),y=window.setTimeout(()=>{N(new Error("KCP SDK load timeout"))},15e3),f.__kcpReady=()=>{y!==void 0&&(clearTimeout(y),y=void 0)}})}const rt={nhnkcp_payco:"PAYCO",nhnkcp_naverpay:"네이버페이",nhnkcp_naverpay_point:"네이버페이 포인트",nhnkcp_kakaopay:"카카오페이",nhnkcp_applepay:"Apple Pay"},at="0 0 0 2px #ffffff, 0 0 0 5px rgba(0,0,0,0.55)";function ie(){return document.querySelector(".nhnkcp-easy-pay-btns")??null}function ce(){const e=ie();e&&e.querySelectorAll("button").forEach(t=>{t.style.boxShadow="",t.style.outline=""})}function st(e){const t=ie();if(!t)return;const n=rt[e];t.querySelectorAll("button").forEach(o=>{o.textContent?.trim()===n?(o.style.boxShadow=at,o.style.outline="none"):(o.style.boxShadow="",o.style.outline="")})}function it(e){const t=e.params?.paymentMethod;if(!t)return;const n=window.G7Core;if(T(t)&&!x()){const r=R();n?.state?.setLocal?.({paymentErrorMessage:r,isSubmittingOrder:!1}),n?.modal?.open?.("nhnkcp_payment_error_modal"),ce();return}const o=typeof t=="string"&&t.startsWith("nhnkcp_");n?.state?.setLocal?.({paymentMethod:t}),o?st(t):ce()}function ct(e){const t=document.createElement("textarea");t.value=e,t.setAttribute("readonly","readonly"),t.style.position="fixed",t.style.left="-9999px",t.style.top="0",document.body.appendChild(t),t.select();try{document.execCommand("copy")}finally{t.remove()}}async function dt(e){const t=String(e.params?.text??"");if(t!==""){if(navigator.clipboard&&typeof navigator.clipboard.writeText=="function"){await navigator.clipboard.writeText(t);return}ct(t)}}const de={requestPayment:tt,setPaymentMethod:it,copyToClipboard:dt},le="/api/modules/sirsoft-ecommerce/user/orders",O="sirsoft-pay_nhnkcp",ue={info:(...e)=>console.info(`[${O}]`,...e),warn:(...e)=>console.warn(`[${O}]`,...e),error:(...e)=>console.error(`[${O}]`,...e)};function lt(e){return typeof e=="string"?e:e instanceof URL?e.toString():typeof Request<"u"&&e instanceof Request?e.url:String(e)}function ut(e,t){return t?.method?t.method.toUpperCase():typeof Request<"u"&&e instanceof Request?e.method.toUpperCase():"GET"}function pt(e,t){if(t!=="POST")return!1;const n=e.split("?")[0].split("#")[0];return n===le||n.endsWith(le)}function mt(e){try{return JSON.parse(e).payment_method}catch{return}}function ft(e){return new Response(JSON.stringify({success:!1,message:e,error:e,errors:{payment_method:[e]}}),{status:422,statusText:"Unprocessable Content",headers:{"Content-Type":"application/json"}})}function yt(){if(typeof window>"u"||typeof window.fetch!="function")return;const e="__sirsoftNhnkcpInterceptorInstalled",t=window;if(t[e])return;t[e]=!0;const n=window.fetch.bind(window);window.fetch=async function(r,a){const s=lt(r),i=ut(r,a);if(!pt(s,i))return n(r,a);let c;if(a?.body&&typeof a.body=="string"&&(c=mt(a.body)),T(c)&&!x()){const d=R();return ue.warn(d),ft(d)}return n(r,a)},ue.info("order request interceptor installed (Apple Pay device guard)")}const K="sirsoft-pay_nhnkcp",pe="__kcpOcReceiptInjectorInstalled",me="kcp-oc-receipt-btn",ht=/^\/shop\/orders\/([^/]+)\/complete$/;function fe(){return localStorage.getItem("auth_token")}async function _t(e){const t=fe();if(!t)return null;try{const n=await fetch(`/api/modules/sirsoft-ecommerce/user/orders/${e}`,{headers:{Authorization:`Bearer ${t}`,Accept:"application/json"}});return n.ok?(await n.json())?.data?.payment??null:null}catch{return null}}async function j(e){const t=fe();if(!t)return null;try{const n=await fetch(`/api/plugins/${K}/user/orders/${e}/receipt`,{headers:{Authorization:`Bearer ${t}`,Accept:"application/json"}});return n.ok?await n.json():null}catch{return null}}function ye(e,t,n){const o=document.createElement("button");return o.type="button",o.className=t,o.textContent=e,o.addEventListener("click",()=>n(o)),o}function gt(e){if(!e)return!1;const t=Array.from(document.querySelectorAll("div"));for(const n of t){const o=Array.from(n.children).filter(s=>s instanceof HTMLElement&&s.tagName==="SPAN");if(o.length<2)continue;const r=o[0].textContent?.trim();if(r!=="결제 방법"&&r!=="결제수단"&&r!=="결제 방식")continue;const a=o[o.length-1];return a.textContent?.trim()===e?(n.dataset.nhnkcpPaymentMethodRow="true",!0):(a.textContent=e,a.dataset.nhnkcpPaymentMethodPatched="true",n.dataset.nhnkcpPaymentMethodRow="true",!0)}return!1}async function wt(e){if(document.getElementById(me))return;const t=await _t(e);if(!t||t.pg_provider!=="nhnkcp"||!t.transaction_id||!t.paid_at)return;const n=Array.from(document.querySelectorAll('button[type="button"]')).find(c=>c.className.includes("bg-blue-600"));if(!n?.parentElement)return;const o=await j(e);gt(o?.payment_method_display_label);const r=n.parentElement,a=ye("영수증 조회",n.className.replace(/bg-blue-\d+/g,"bg-green-600").replace(/hover:bg-blue-\d+/g,"hover:bg-green-700"),async c=>{c.disabled=!0,c.textContent="로딩 중...";const d=await j(e);if(c.disabled=!1,c.textContent="영수증 조회",d){const l=window.KcpReceiptPopup;l&&new l({url:d.rLine truncated
|
||||
@@ -4,6 +4,7 @@
|
||||
|
||||
| 문서 | 도메인 | 설명 |
|
||||
| --- | --- | --- |
|
||||
| [payment.md](payment.md) | `payment` | 브라우저 리턴 콜백·결제창 닫힘 보고·결제 재시도. 주문 상태를 바꾸는 경로가 하나뿐인 이유 |
|
||||
| [vbank.md](vbank.md) | `payment` | 가상계좌 입금통보·에스크로 공통통보 수신 경로와 발신 서버(IP) 확인 |
|
||||
| [admin-orders.md](admin-orders.md) | `admin` | 관리자 주문 연동 경로 전체와 각 경로의 요구 권한 |
|
||||
| [transaction-status.md](transaction-status.md) | `admin` | 관리자 주문 상세의 거래 상태·취소·환불 조회 |
|
||||
@@ -0,0 +1,198 @@
|
||||
# Payment API 레퍼런스
|
||||
|
||||
> **소유**: 플러그인 `sirsoft-pay_nhnkcp`. 이 문서는 결제창과 주고받는 세 경로 — 브라우저 리턴 콜백, 결제창 닫힘 보고, 결제 재시도 준비 — 를 서술한다. NHN KCP 서버가 직접 보내는 통보(가상계좌·에스크로) 경로는 [vbank.md](vbank.md) 가 소유한다.
|
||||
|
||||
---
|
||||
|
||||
## TL;DR (5초 요약)
|
||||
|
||||
```text
|
||||
1. 브라우저 리턴 콜백은 주문 상태를 바꾸지 않는다 — 승인 전 실패는 실패 URL 로 되돌려 보내기만 한다
|
||||
2. 주문을 실패로 전이시키는 결제창 경로는 close-report 하나뿐이다 (구매자·금액 대조를 통과한 요청)
|
||||
3. 승인(tno) 이후에 터진 실패만 콜백이 주문에 반영한다
|
||||
4. close-report / retry 는 인증 불필요하나 구매자 대조 + 금액 대조 + IP·주문번호별 분당 20회 제한
|
||||
5. 결제 성공 콜백과의 경쟁은 주문 락 + `status: ignored` 로 차단한다
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 주문 상태를 바꾸는 경로는 하나뿐이다
|
||||
|
||||
이 플러그인에서 **주문을 결제 실패로 전이시키는 결제창 경로는 `POST /api/plugins/sirsoft-pay_nhnkcp/payment/close-report` 하나**다.
|
||||
|
||||
브라우저 리턴 콜백(`POST /plugins/sirsoft-pay_nhnkcp/payment/callback`)은 PG 서명도 발신 IP 증명도 없고, 주문번호(`ordr_idxx`)·금액(`good_mny`)·결과코드(`res_cd`)가 전부 **요청자가 고른 값**이다. 그 입력을 근거로 주문을 실패 처리하면, 남의 주문번호와 임의 금액·위조 결과코드를 담은 POST 한 번으로 **타인의 결제대기 주문을 취소시킬 수 있다** (KVE-2026-2018).
|
||||
|
||||
그래서 콜백은 승인이 성립하기 전의 실패에서는 주문 상태를 건드리지 않고 실패 URL 로 되돌려 보내기만 한다.
|
||||
|
||||
| 시점 | 판정 근거 | 주문 상태 |
|
||||
| --- | --- | --- |
|
||||
| 금액 불일치 (승인 전) | 브라우저가 보낸 `good_mny` | **변경 없음** — 실패 URL 리다이렉트 |
|
||||
| 승인 실패 (`res_cd` 비정상) | 브라우저가 보낸 결과코드 | **변경 없음** — 실패 URL 리다이렉트 |
|
||||
| 승인 이후의 예외 (금액 불일치·후속 처리 실패) | KCP 승인 응답의 `tno` 존재 | **실패 처리 + 자동 취소** |
|
||||
|
||||
승인 여부는 `PaymentCallbackController::hasApproval()` 이 `tno`(승인 확정 시에만 채워지는 거래번호) 로 판정한다. `tno` 가 비어 있으면 승인 전에 흐름이 끊긴 것이므로 그 시점까지의 입력은 주문 상태 변경의 근거가 될 수 없다.
|
||||
|
||||
정당한 결제창 닫힘은 구매자 대조를 통과한 close-report 요청으로만 기록된다.
|
||||
|
||||
> 형제 플러그인도 같은 규약이다 — `sirsoft-pay_kginicis` · `sirsoft-tosspayments` 의 `docs/api/payment.md` 를 참조.
|
||||
|
||||
---
|
||||
|
||||
## POST /api/plugins/sirsoft-pay_nhnkcp/payment/close-report
|
||||
|
||||
- **라우트명**: `api.plugins.sirsoft-pay_nhnkcp.payment.close-report`
|
||||
- **컨트롤러**: `Plugins\Sirsoft\PayNhnkcp\Controllers\PaymentCloseReportController@store`
|
||||
- **인증/권한**: 공개 (인증 불필요 — 결제창 컨텍스트에서 호출)
|
||||
|
||||
**요청 파라미터**
|
||||
|
||||
| 이름 | 위치 | 타입 | 필수 | 허용값 | 용도 |
|
||||
| --- | --- | --- | --- | --- | --- |
|
||||
| oid | body | string | 예 | max 40 | 결제창을 닫은 대상 주문의 주문번호. 서버가 이 값으로 주문을 조회해 결제 실패/취소 이력을 기록한다. |
|
||||
| price | body | integer | 예 | min 1 | 주문 결제 금액. 저장된 주문 청구액과 일치하는지 검증해 위변조된 닫힘 보고를 차단한다. |
|
||||
| buyer_email | body | string | 아니오 | max 255 | 구매자 이메일. 주문 배송지의 주문자 이메일이 있으면 **일치해야 한다**(불일치·미제공 시 403). |
|
||||
| buyer_phone | body | string | 아니오 | max 30 | 구매자 전화번호. 주문 배송지의 주문자 전화가 있으면 숫자만 추출해 **일치해야 한다**(불일치·미제공 시 403). |
|
||||
| payment_method | body | string | 아니오 | max 50 | 사용자가 결제창에서 선택했던 간편결제 등 결제수단 식별값. 결제 메타에 병합해 어떤 수단에서 창을 닫았는지 남긴다. |
|
||||
| reason | body | string | 아니오 | max 160 | 결제창 닫힘 사유 문자열. 비어 있으면 기본 문구로 대체되어 취소 이력에 기록된다. |
|
||||
|
||||
**요청 예시**
|
||||
|
||||
```http
|
||||
POST /api/plugins/sirsoft-pay_nhnkcp/payment/close-report HTTP/1.1
|
||||
Host: api.example.com
|
||||
Accept: application/json
|
||||
Content-Type: application/json
|
||||
|
||||
{
|
||||
"oid": "ORD20260902001",
|
||||
"price": 10000,
|
||||
"buyer_email": "buyer@example.com",
|
||||
"buyer_phone": "010-1234-5678",
|
||||
"payment_method": "kakaopay",
|
||||
"reason": "사용자가 결제창을 닫음"
|
||||
}
|
||||
```
|
||||
|
||||
**응답 필드** (`data` 내부)
|
||||
|
||||
| 필드 | 타입 | 값 | 용도/설명 |
|
||||
| --- | --- | --- | --- |
|
||||
| status | string | `recorded` \| `ignored` | 닫힘 보고 처리 결과. `recorded` = 주문을 `USER_CANCEL` 로 실패 처리하고 취소 이력을 남김. `ignored` = 결제 성공 콜백과의 경쟁 등으로 처리하지 않고 무시. |
|
||||
| reason | string | `order_not_payable` \| `payment_already_paid` \| `callback_in_progress` | `status: ignored` 일 때만 포함되는 무시 사유. 주문이 이미 결제 가능 상태가 아님 / 결제가 이미 완료됨 / 같은 주문의 승인 콜백이 락을 쥐고 처리 중임. |
|
||||
|
||||
**응답 예시**
|
||||
|
||||
```json
|
||||
{
|
||||
"success": true,
|
||||
"message": "성공적으로 처리되었습니다.",
|
||||
"data": {
|
||||
"status": "recorded"
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
**에러 응답**
|
||||
|
||||
| 상태코드 | 의미 | 발생 조건 |
|
||||
| --- | --- | --- |
|
||||
| 403 | Forbidden | 요청의 구매자 정보(`buyer_email` / `buyer_phone`)가 주문의 주문자와 일치하지 않는 경우 |
|
||||
| 404 | Not Found | `oid` 에 해당하는 주문이 없는 경우 |
|
||||
| 422 | Unprocessable Entity | 요청 파라미터가 검증 규칙을 위반한 경우, 주문 통화가 청구 가능한 통화가 아닌 경우, 금액이 주문 청구액과 불일치하는 경우 |
|
||||
| 429 | Too Many Requests | 동일 IP·`oid` 조합에서 분당 20회를 초과해 요청한 경우 |
|
||||
|
||||
**설명**
|
||||
|
||||
PC 표준결제창에서 사용자가 결제를 완료하지 않고 창을 닫았을 때 프론트엔드가 이를 서버에 보고하는 엔드포인트다. `OrderProcessingService::failPayment()` 로 주문을 `USER_CANCEL` 사유로 실패 처리하고 취소 이력을 남기며, 간편결제 선택 정보가 있으면 결제 메타에 병합한다.
|
||||
|
||||
인증은 불필요하지만 **이 경로가 주문 상태를 바꾸는 유일한 결제창 경로**이므로 방어가 네 겹이다 — FormRequest 검증, `oid` 기준 IP별 분당 20회 레이트리밋, 주문의 주문자 정보(이메일·전화) 대조, 주문 청구액과의 금액 대조.
|
||||
|
||||
승인 콜백(`authCallback`)과 같은 주문 락을 공유한다. 카드 주문은 승인 직전까지 주문 상태가 결제 전이라 상태 가드를 통과하므로, 결제가 이미 완료된 경우(`payment_already_paid`)를 별도로 차단해 결제 성공과 닫힘 보고가 경쟁할 때 옵션 상태가 어긋나는 것을 막는다. 락 획득에 실패하면 `callback_in_progress` 로 무시한다.
|
||||
|
||||
---
|
||||
|
||||
## POST /api/plugins/sirsoft-pay_nhnkcp/payment/retry
|
||||
|
||||
- **라우트명**: `api.plugins.sirsoft-pay_nhnkcp.payment.retry`
|
||||
- **컨트롤러**: `Plugins\Sirsoft\PayNhnkcp\Controllers\PaymentRetryController@store`
|
||||
- **인증/권한**: 공개 (인증 불필요 — 결제 실패 화면에서 호출)
|
||||
|
||||
**요청 파라미터**
|
||||
|
||||
| 이름 | 위치 | 타입 | 필수 | 허용값 | 용도 |
|
||||
| --- | --- | --- | --- | --- | --- |
|
||||
| oid | body | string | 예 | max 40 | 재결제할 주문의 주문번호. |
|
||||
| price | body | integer | 예 | min 1 | 주문 결제 금액. 저장된 주문 청구액과 일치해야 한다. |
|
||||
| buyer_email | body | string | 아니오 | max 255 | 구매자 이메일. close-report 와 동일한 주문자 대조에 사용된다. |
|
||||
| buyer_phone | body | string | 아니오 | max 30 | 구매자 전화번호. 동일. |
|
||||
| payment_method | body | string | 아니오 | max 50 | 재시도 시 선택한 결제수단 식별값. |
|
||||
|
||||
**응답 필드** (`data` 내부)
|
||||
|
||||
| 필드 | 타입 | 값 | 용도/설명 |
|
||||
| --- | --- | --- | --- |
|
||||
| status | string | `ready` \| `restored` | `ready` = 주문이 이미 결제 가능 상태라 복구할 것이 없음. `restored` = 실패/취소 상태였던 주문을 같은 주문번호로 재결제 가능하도록 되돌림. |
|
||||
|
||||
**응답 예시**
|
||||
|
||||
```json
|
||||
{
|
||||
"success": true,
|
||||
"message": "성공적으로 처리되었습니다.",
|
||||
"data": {
|
||||
"status": "restored"
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
**에러 응답**
|
||||
|
||||
| 상태코드 | 의미 | 발생 조건 |
|
||||
| --- | --- | --- |
|
||||
| 403 | Forbidden | 요청의 구매자 정보가 주문의 주문자와 일치하지 않는 경우 |
|
||||
| 404 | Not Found | `oid` 에 해당하는 주문이 없는 경우 |
|
||||
| 409 | Conflict | 주문이 재결제 가능한 상태가 아닌 경우 (이미 결제 완료·배송 진행 등) |
|
||||
| 422 | Unprocessable Entity | 요청 파라미터 검증 위반, 청구 불가 통화, 금액 불일치 |
|
||||
| 429 | Too Many Requests | 동일 IP·`oid` 조합에서 분당 20회 초과 |
|
||||
|
||||
**설명**
|
||||
|
||||
결제에 실패했거나 결제창을 닫아 취소된 주문을 **같은 주문번호로** 다시 결제할 수 있는 상태로 되돌린다. close-report 와 동일한 대조(주문자·금액·레이트리밋)를 거치므로, 남의 주문번호만으로 상태를 되돌릴 수 없다.
|
||||
|
||||
---
|
||||
|
||||
## POST /plugins/sirsoft-pay_nhnkcp/payment/callback
|
||||
|
||||
- **라우트명**: `web.plugins.sirsoft-pay_nhnkcp.payment.callback`
|
||||
- **컨트롤러**: `Plugins\Sirsoft\PayNhnkcp\Controllers\PaymentCallbackController@authCallback`
|
||||
- **인증/권한**: 공개 · CSRF 검증 제외 (KCP 표준결제창이 브라우저 POST 로 리턴) · **IP 화이트리스트 미적용** (정상 사용자의 임의 IP 에서 도달)
|
||||
|
||||
**요청 파라미터** (KCP 결제창이 브라우저 POST 로 전달)
|
||||
|
||||
| 이름 | 타입 | 필수 | 용도 |
|
||||
| --- | --- | --- | --- |
|
||||
| ordr_idxx | string | 예 | 주문번호 |
|
||||
| res_cd | string | 예(nullable 허용) | KCP 인증 결과코드 |
|
||||
| res_msg | string | 아니오 | KCP 결과 메시지 |
|
||||
| enc_data / enc_info | string | 아니오 | 승인 요청에 쓰는 암호화 데이터·정보 |
|
||||
| tno | string | 아니오 | 거래번호. **승인이 확정된 뒤에만 채워진다** — 주문 상태 변경 가부의 판정 기준 |
|
||||
| good_mny | numeric | 아니오 | 결제 금액 (min 1) |
|
||||
| use_pay_method | string | 아니오 | 사용된 결제수단 |
|
||||
| nhnkcp_easy_pay_method | string | 아니오 | 간편결제 수단 식별값 (max 50) |
|
||||
| bankname · bank_name · account · depositor · account_holder · va_date | string | 아니오 | 모바일 가상계좌 콜백이 평문으로 전달하는 계좌 정보 변종 키 |
|
||||
|
||||
**응답**
|
||||
|
||||
JSON 이 아니라 **리다이렉트**다. 성공 시 상점 성공 페이지로, 실패 시 실패 페이지로 이동하며 실패 사유를 쿼리스트링(`error` · `message` · `orderId`)으로 전달한다. 쿼리 규약과 예외 원문 비노출 원칙은 [vbank.md "결제 실패 리다이렉트 규약"](vbank.md) 에 있다.
|
||||
|
||||
고정 `error` 값: `amount_mismatch` · `callback_locked` · `cli_exception` · `confirm_failed` · `currency_not_supported` · `invalid_payment_currency` · `order_not_found` · `order_not_retryable` · `vbank_save_failed`.
|
||||
|
||||
이 밖에 KCP 가 돌려준 결과코드(`res_cd`)가 그대로 실리는 분기가 있다. 화면이 `error` 로 분기할 때는 위 고정값만 신뢰하고, 그 밖의 값은 미확정 실패로 다룬다.
|
||||
|
||||
**설명**
|
||||
|
||||
KCP 표준결제창이 인증을 마치고 브라우저를 통해 가맹점으로 되돌려 보내는 경로다. 서버는 여기서 승인(approve)을 요청하고, 성공하면 주문을 결제 완료로 확정한다.
|
||||
|
||||
이 문서 상단 **"주문 상태를 바꾸는 경로는 하나뿐이다"** 가 이 엔드포인트의 핵심 계약이다 — 승인 전에 판정되는 실패(금액 불일치·인증 결과코드 비정상)에서는 주문 상태를 바꾸지 않는다. 승인이 이미 일어난 뒤(`tno` 존재)의 실패만 주문에 반영하고, 그 경우 KCP 측에 잔존한 승인을 자동 취소한다.
|
||||
|
||||
이 엔드포인트를 수정할 때는 실패 분기마다 **"이 판정의 근거가 브라우저가 보낸 값인가"** 를 먼저 확인한다. 근거가 브라우저 입력뿐이면 주문 상태를 바꾸지 않는다.
|
||||
@@ -14,9 +14,9 @@
|
||||
| `sirsoft-pay_nhnkcp.escrow.purchase_cancelled` | action | — | `src/Controllers/EscrowCommonNotifyController.php:97` |
|
||||
| `sirsoft-pay_nhnkcp.escrow.purchase_confirmed` | action | — | `src/Controllers/EscrowCommonNotifyController.php:96` |
|
||||
| `sirsoft-pay_nhnkcp.payment.after_cancel` | action | KCP 결제 취소 완료 후 | `src/Services/NhnKcpApiService.php:250` |
|
||||
| `sirsoft-pay_nhnkcp.payment.after_confirm` | action | KCP 결제 승인 확인 완료 후 | `src/Controllers/PaymentCallbackController.php:279` |
|
||||
| `sirsoft-pay_nhnkcp.payment.after_confirm` | action | KCP 결제 승인 확인 완료 후 | `src/Controllers/PaymentCallbackController.php:276` |
|
||||
| `sirsoft-pay_nhnkcp.payment.before_cancel` | action | KCP 결제 취소 API 호출 전 (본인인증 등 확장 지점) | `src/Services/NhnKcpApiService.php:229` |
|
||||
| `sirsoft-pay_nhnkcp.payment.before_confirm` | action | KCP 결제 승인 확인 전 | `src/Controllers/PaymentCallbackController.php:274` |
|
||||
| `sirsoft-pay_nhnkcp.payment.before_confirm` | action | KCP 결제 승인 확인 전 | `src/Controllers/PaymentCallbackController.php:271` |
|
||||
<!-- @generated:hooks-published END -->
|
||||
|
||||
<!-- @intent START -->
|
||||
|
||||
+120
-2
@@ -1,5 +1,10 @@
|
||||
import { afterEach, describe, expect, it, vi } from 'vitest';
|
||||
import { preparePaymentRetry, reportPaymentWindowClosed } from '../paymentCloseReport';
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
import {
|
||||
preparePaymentRetry,
|
||||
rememberPendingClose,
|
||||
reportPaymentFailureOnReturn,
|
||||
reportPaymentWindowClosed,
|
||||
} from '../paymentCloseReport';
|
||||
|
||||
function windowRecord(): Record<string, any> {
|
||||
return window as unknown as Record<string, any>;
|
||||
@@ -90,3 +95,116 @@ describe('paymentCloseReport', () => {
|
||||
})).rejects.toThrow('Order is not retryable for NHN KCP payment.');
|
||||
});
|
||||
});
|
||||
|
||||
/**
|
||||
* 결제 실패 화면 복귀 시 보고
|
||||
*
|
||||
* 브라우저 리턴 콜백(authCallback)은 PG 서명도 IP 증명도 없어 주문 상태를 바꾸지 않는다.
|
||||
* 승인이 거절된 정당한 실패는 이 경로(소유권 대조 close-report)로만 기록된다.
|
||||
*/
|
||||
describe('결제 실패 화면 복귀 보고', () => {
|
||||
const CONTEXT = {
|
||||
closeReportUrl: '/plugins/sirsoft-pay_nhnkcp/payment/close-report',
|
||||
oid: 'ORD-KCP-RETURN-001',
|
||||
price: 10000,
|
||||
buyer_email: 'buyer@example.com',
|
||||
buyer_phone: '01012345678',
|
||||
};
|
||||
|
||||
/**
|
||||
* 화면 주소를 바꿔 결제 리턴 상황을 재현한다.
|
||||
*/
|
||||
function setLocation(pathname: string, search: string): void {
|
||||
Object.defineProperty(window, 'location', {
|
||||
configurable: true,
|
||||
value: { pathname, search, origin: 'https://shop.example' },
|
||||
});
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
window.sessionStorage.clear();
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
delete windowRecord().G7Core;
|
||||
vi.restoreAllMocks();
|
||||
window.sessionStorage.clear();
|
||||
});
|
||||
|
||||
it('실패 화면으로 돌아오면 저장해 둔 구매자 정보로 보고한다', async () => {
|
||||
const apiPost = vi.fn().mockResolvedValue({ success: true });
|
||||
windowRecord().G7Core = { api: { post: apiPost } };
|
||||
|
||||
rememberPendingClose(CONTEXT);
|
||||
setLocation('/shop/checkout', '?error=9999&message=%EC%8B%A4%ED%8C%A8&orderId=ORD-KCP-RETURN-001');
|
||||
|
||||
await reportPaymentFailureOnReturn();
|
||||
|
||||
expect(apiPost).toHaveBeenCalledWith(
|
||||
'/plugins/sirsoft-pay_nhnkcp/payment/close-report',
|
||||
expect.objectContaining({ oid: 'ORD-KCP-RETURN-001', price: 10000 }),
|
||||
);
|
||||
});
|
||||
|
||||
it('두 번 호출해도 한 번만 보고한다', async () => {
|
||||
const apiPost = vi.fn().mockResolvedValue({ success: true });
|
||||
windowRecord().G7Core = { api: { post: apiPost } };
|
||||
|
||||
rememberPendingClose(CONTEXT);
|
||||
setLocation('/shop/checkout', '?error=9999&orderId=ORD-KCP-RETURN-001');
|
||||
|
||||
await reportPaymentFailureOnReturn();
|
||||
await reportPaymentFailureOnReturn();
|
||||
|
||||
expect(apiPost).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it('다른 주문번호로 돌아왔으면 보고하지 않는다', async () => {
|
||||
const apiPost = vi.fn();
|
||||
windowRecord().G7Core = { api: { post: apiPost } };
|
||||
|
||||
rememberPendingClose(CONTEXT);
|
||||
setLocation('/shop/checkout', '?error=9999&orderId=ORD-KCP-OTHER');
|
||||
|
||||
await reportPaymentFailureOnReturn();
|
||||
|
||||
expect(apiPost).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('결제 완료 화면으로 돌아오면 보고하지 않고 저장분만 지운다', async () => {
|
||||
const apiPost = vi.fn();
|
||||
windowRecord().G7Core = { api: { post: apiPost } };
|
||||
|
||||
rememberPendingClose(CONTEXT);
|
||||
setLocation('/shop/orders/ORD-KCP-RETURN-001/complete', '');
|
||||
|
||||
await reportPaymentFailureOnReturn();
|
||||
|
||||
expect(apiPost).not.toHaveBeenCalled();
|
||||
expect(window.sessionStorage.getItem('g7:sirsoft-pay_nhnkcp:pendingClose')).toBeNull();
|
||||
});
|
||||
|
||||
it('저장분이 없으면 아무것도 보내지 않는다', async () => {
|
||||
const apiPost = vi.fn();
|
||||
windowRecord().G7Core = { api: { post: apiPost } };
|
||||
|
||||
setLocation('/shop/checkout', '?error=9999&orderId=ORD-KCP-RETURN-001');
|
||||
|
||||
await reportPaymentFailureOnReturn();
|
||||
|
||||
expect(apiPost).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('실패 표시가 없으면 판단하지 않고 저장분을 남겨 둔다', async () => {
|
||||
const apiPost = vi.fn();
|
||||
windowRecord().G7Core = { api: { post: apiPost } };
|
||||
|
||||
rememberPendingClose(CONTEXT);
|
||||
setLocation('/shop/checkout', '');
|
||||
|
||||
await reportPaymentFailureOnReturn();
|
||||
|
||||
expect(apiPost).not.toHaveBeenCalled();
|
||||
expect(window.sessionStorage.getItem('g7:sirsoft-pay_nhnkcp:pendingClose')).not.toBeNull();
|
||||
});
|
||||
});
|
||||
@@ -3,6 +3,7 @@
|
||||
import {
|
||||
PaymentCloseReportContext,
|
||||
preparePaymentRetry,
|
||||
rememberPendingClose,
|
||||
reportPaymentWindowClosed,
|
||||
} from '../paymentCloseReport';
|
||||
import {
|
||||
@@ -291,6 +292,11 @@ export async function requestPaymentHandler(action: any, _context?: any): Promis
|
||||
|
||||
await preparePaymentRetry(closeReportContext);
|
||||
|
||||
// 결제창은 전체 페이지 이동으로 열리고 돌아오므로, 실패 화면에서 서버에 보고할 때 쓸
|
||||
// 구매자 정보를 미리 남겨 둔다. 브라우저 리턴 콜백은 인증이 없어 주문 상태를 바꾸지 않고,
|
||||
// 소유권을 대조하는 close-report 만이 정당한 결제 실패를 기록할 수 있다.
|
||||
rememberPendingClose(closeReportContext);
|
||||
|
||||
if (isMobileDevice()) {
|
||||
await handleMobilePayment(G7Core, pgPaymentData, paymentMethod, isEasyPay, callbackUrl);
|
||||
} else {
|
||||
|
||||
@@ -5,6 +5,7 @@ import { installMypageOrderShowInjector } from './mypageOrderShowInjector';
|
||||
import { installAdminApplePayNoticeInjector } from './adminApplePayNoticeInjector';
|
||||
import { installAdminPaymentMethodBrandInjector } from './adminPaymentMethodBrandInjector';
|
||||
import { installAdminOrderPaymentDisplayInjector } from './adminOrderPaymentDisplayInjector';
|
||||
import { reportPaymentFailureOnReturn } from './paymentCloseReport';
|
||||
|
||||
class KcpReceiptPopup {
|
||||
constructor(params: { url?: string; cash_url?: string }) {
|
||||
@@ -60,6 +61,11 @@ function registerHandlers(): number {
|
||||
}
|
||||
|
||||
function initPlugin(): void {
|
||||
// 결제 실패로 돌아온 화면이면 서버에 보고한다. 브라우저 리턴 콜백은 PG 서명도 IP 증명도
|
||||
// 없어 주문 상태를 바꾸지 않으므로, 소유권을 대조하는 close-report 가 정당한 결제 실패를
|
||||
// 기록하는 유일한 경로다. 저장해 둔 정보가 없으면 아무 일도 하지 않는다.
|
||||
void reportPaymentFailureOnReturn();
|
||||
|
||||
const doInit = () => {
|
||||
const count = registerHandlers();
|
||||
|
||||
|
||||
@@ -81,6 +81,133 @@ export async function preparePaymentRetry(context: PaymentCloseReportContext): P
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* 결제 실패 화면으로 돌아왔을 때 보고에 쓸 구매자 정보를 남겨 두는 저장소 키.
|
||||
*
|
||||
* 결제창은 전체 페이지 이동으로 열리고 돌아오므로 JS 컨텍스트가 소실된다. sessionStorage 는
|
||||
* 같은 탭에서 외부 도메인을 다녀와도 유지되므로, 결제 요청 직전에 저장해 두었다가 꺼내 쓴다.
|
||||
*/
|
||||
const PENDING_CLOSE_STORAGE_KEY = 'g7:sirsoft-pay_nhnkcp:pendingClose';
|
||||
|
||||
/**
|
||||
* sessionStorage 접근은 브라우저 설정(사이트 데이터 차단·시크릿 모드)에 따라 예외를 던진다.
|
||||
* 보고는 편의 장치이므로 실패해도 결제 흐름을 막지 않는다.
|
||||
*/
|
||||
function safeSessionStorage(): Storage | null {
|
||||
try {
|
||||
return window.sessionStorage ?? null;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 결제창을 열기 직전에 보고용 컨텍스트를 저장합니다.
|
||||
*
|
||||
* @param context 결제창 닫힘 보고에 필요한 주문·구매자 정보
|
||||
*/
|
||||
export function rememberPendingClose(context: PaymentCloseReportContext): void {
|
||||
const storage = safeSessionStorage();
|
||||
if (!storage) {
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
storage.setItem(PENDING_CLOSE_STORAGE_KEY, JSON.stringify(context));
|
||||
} catch {
|
||||
// 저장 실패는 무시 — 만료 자동 정리가 최종 안전망이다.
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 저장해 둔 보고용 컨텍스트를 지웁니다.
|
||||
*/
|
||||
export function forgetPendingClose(): void {
|
||||
const storage = safeSessionStorage();
|
||||
if (!storage) {
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
storage.removeItem(PENDING_CLOSE_STORAGE_KEY);
|
||||
} catch {
|
||||
// 무시
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 저장해 둔 보고용 컨텍스트를 읽습니다.
|
||||
*
|
||||
* @returns 저장된 컨텍스트, 없거나 형식이 깨졌으면 null
|
||||
*/
|
||||
function readPendingClose(): PaymentCloseReportContext | null {
|
||||
const storage = safeSessionStorage();
|
||||
if (!storage) {
|
||||
return null;
|
||||
}
|
||||
|
||||
try {
|
||||
const raw = storage.getItem(PENDING_CLOSE_STORAGE_KEY);
|
||||
if (!raw) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const parsed = JSON.parse(raw) as PaymentCloseReportContext;
|
||||
|
||||
return parsed && typeof parsed.oid === 'string' && parsed.oid !== '' ? parsed : null;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 결제 실패 화면으로 돌아왔으면 저장해 둔 정보로 서버에 보고합니다.
|
||||
*
|
||||
* 브라우저 리턴 콜백(`authCallback`)은 PG 서명도 IP 증명도 없어 주문 상태를 바꾸지 않는다.
|
||||
* 소유권을 대조하는 close-report 만이 정당한 결제 실패를 기록할 수 있으므로, 실패 화면에
|
||||
* 도착한 이 시점에 그 경로로 보고한다. 플러그인 부팅 시 1회 호출한다.
|
||||
*/
|
||||
export async function reportPaymentFailureOnReturn(): Promise<void> {
|
||||
const pending = readPendingClose();
|
||||
if (!pending) {
|
||||
return;
|
||||
}
|
||||
|
||||
let params: URLSearchParams;
|
||||
try {
|
||||
params = new URLSearchParams(window.location.search);
|
||||
} catch {
|
||||
return;
|
||||
}
|
||||
|
||||
const orderIdInUrl = params.get('orderId') ?? '';
|
||||
|
||||
// 저장분과 화면의 주문번호가 다르면 이번 이동과 무관한 잔여물이다.
|
||||
if (orderIdInUrl !== '' && orderIdInUrl !== pending.oid) {
|
||||
return;
|
||||
}
|
||||
|
||||
// 결제 완료 화면으로 돌아왔으면 보고 대상이 아니다 — 성공 확정은 서버가 이미 했다.
|
||||
if (/\/(complete|success)(\/|$|\?)/.test(window.location.pathname)) {
|
||||
forgetPendingClose();
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
const code = params.get('error') ?? '';
|
||||
const message = params.get('message') ?? '';
|
||||
|
||||
// 실패 표시가 전혀 없으면 결제창을 열기만 하고 돌아온 경우일 수 있다 — 판단하지 않는다.
|
||||
if (code === '' && orderIdInUrl === '') {
|
||||
return;
|
||||
}
|
||||
|
||||
// 중복 보고를 막기 위해 요청 전에 먼저 지운다.
|
||||
forgetPendingClose();
|
||||
|
||||
await reportPaymentWindowClosed(pending, message !== '' ? message : code);
|
||||
}
|
||||
|
||||
export async function reportPaymentWindowClosed(
|
||||
context: PaymentCloseReportContext,
|
||||
reason = 'kcp-window-closed',
|
||||
|
||||
+103
-58
@@ -200,18 +200,18 @@ class PaymentCallbackController
|
||||
$callbackLock = $this->acquireOrderCallbackLock('authCallback', $ordrIdxx);
|
||||
$order = $order->fresh('payment') ?? $order;
|
||||
|
||||
if ($order->order_status === OrderStatusEnum::CANCELLED) {
|
||||
$restored = $this->restoreRetryableKcpOrder($order, $goodMny > 0 ? $goodMny : null);
|
||||
if (! $restored) {
|
||||
Log::warning('KCP: cancelled order is not retryable', ['ordr_idxx' => $ordrIdxx]);
|
||||
// 취소 주문 재결제 — 여기서는 되살리지 않고 "되살릴 수 있는가" 만 읽는다.
|
||||
// 되살리기는 상태 변경이고 이 시점의 입력은 전부 비인증 브라우저 값이라,
|
||||
// 여기서 수행하면 주문번호만 아는 제3자가 남의 취소 주문을 결제대기로
|
||||
// 되돌릴 수 있다. 실제 되살리기는 승인·발급이 확정된 뒤에 수행한다.
|
||||
if ($order->order_status === OrderStatusEnum::CANCELLED
|
||||
&& ! $this->isRetryableKcpFailure($order, $order->payment)) {
|
||||
Log::warning('KCP: cancelled order is not retryable', ['ordr_idxx' => $ordrIdxx]);
|
||||
|
||||
return redirect($this->resolveFailUrl([
|
||||
'error' => 'order_not_retryable',
|
||||
'orderId' => $ordrIdxx,
|
||||
]));
|
||||
}
|
||||
|
||||
$order = $order->fresh('payment') ?? $order;
|
||||
return redirect($this->resolveFailUrl([
|
||||
'error' => 'order_not_retryable',
|
||||
'orderId' => $ordrIdxx,
|
||||
]));
|
||||
}
|
||||
|
||||
if (($order->payment?->isPaid() ?? false) || $order->order_status === OrderStatusEnum::PAYMENT_COMPLETE) {
|
||||
@@ -252,21 +252,20 @@ class PaymentCallbackController
|
||||
'actual' => $goodMny,
|
||||
]);
|
||||
|
||||
$failedOrder = $this->orderService->failPayment($order, 'AMOUNT_MISMATCH', 'KCP callback amount mismatch');
|
||||
$this->markKcpPaymentFailureRecord(
|
||||
$failedOrder,
|
||||
'AMOUNT_MISMATCH',
|
||||
'KCP callback amount mismatch',
|
||||
'amount_mismatch',
|
||||
);
|
||||
|
||||
// 승인 전이다 — 이 시점의 입력은 전부 브라우저가 보낸 값이고 이 엔드포인트는
|
||||
// PG 서명도 IP 증명도 없다. 주문번호도 요청자가 고른 값이므로, 금액 불일치를
|
||||
// 근거로 주문을 실패 처리하면 남의 주문번호와 임의 금액만으로 그 주문을
|
||||
// 취소시킬 수 있다. 상태는 바꾸지 않고 결제창으로 되돌린다.
|
||||
// 정당한 결제창 닫힘은 소유권을 검증하는 close-report 가 기록한다.
|
||||
return redirect($this->resolveFailUrl(['error' => 'amount_mismatch', 'orderId' => $ordrIdxx]));
|
||||
}
|
||||
|
||||
// 가상계좌: 계좌 발급 완료 처리 (실제 입금은 vbankNotify에서 처리)
|
||||
// KCP 콜백의 use_pay_method=VCNT 또는 주문의 payment_method=vbank 로 감지
|
||||
$isVbank = ($validated['use_pay_method'] ?? '') === 'VCNT'
|
||||
|| (bool) $order->payment?->isVirtualAccount();
|
||||
// 분기 판정은 주문에 저장된 결제수단만 본다 — 요청의 use_pay_method 를 함께 보면
|
||||
// 비인증 브라우저가 use_pay_method=VCNT 한 줄로 카드 주문을 가상계좌 분기로 몰아
|
||||
// 승인 검증이 없는 경로를 고를 수 있다 (KVE-2026-2018 동일 계열).
|
||||
// 결제창은 결제수단을 확정한 뒤 열리므로 정상 흐름은 주문 값만으로 판정된다.
|
||||
$isVbank = (bool) $order->payment?->isVirtualAccount();
|
||||
if ($isVbank) {
|
||||
return $this->handleVbankIssued($validated, $order, $encData, $encInfo, $ordrIdxx, $custIp, $request);
|
||||
}
|
||||
@@ -287,14 +286,11 @@ class PaymentCallbackController
|
||||
'res_msg' => $pgResponse['res_msg'] ?? '',
|
||||
]);
|
||||
|
||||
$failedOrder = $this->orderService->failPayment($order, $pgResCd, $pgResponse['res_msg'] ?? '');
|
||||
$this->markKcpPaymentFailureRecord(
|
||||
$failedOrder,
|
||||
$pgResCd,
|
||||
$pgResponse['res_msg'] ?? '',
|
||||
'approval_failed',
|
||||
);
|
||||
|
||||
// 승인이 성립하지 않았다 — 실제로 결제된 것이 없으므로 주문 상태를 바꾸지 않는다.
|
||||
// 이 엔드포인트는 비인증 브라우저 POST 라 "승인 실패" 는 공격자가 남의 주문번호와
|
||||
// 위조 암호문을 보내기만 해도 만들어낼 수 있는 상태다. 그것을 근거로 실패 처리하면
|
||||
// 타인의 결제대기 주문을 임의로 취소시킬 수 있다 (KVE-2026-2018).
|
||||
// 실제 승인이 일어난 뒤의 실패만 아래 catch 블록에서 주문에 반영한다.
|
||||
return redirect($this->resolveFailUrl([
|
||||
'error' => $pgResCd,
|
||||
'message' => $pgResponse['res_msg'] ?? '',
|
||||
@@ -324,6 +320,16 @@ class PaymentCallbackController
|
||||
$approvedTno = $tno;
|
||||
$approvedAmtForCancel = $approvedAmt;
|
||||
|
||||
// 승인이 확정된 뒤에만 취소 주문을 되살린다. 실패하면 예외로 아래 catch 에 넘겨
|
||||
// PG 잔존 승인을 자동 취소한다(사용자 환불 보장).
|
||||
if ($order->order_status === OrderStatusEnum::CANCELLED) {
|
||||
if (! $this->restoreRetryableKcpOrder($order, $approvedAmt)) {
|
||||
throw new \RuntimeException('cancelled order is not retryable after approval');
|
||||
}
|
||||
|
||||
$order = $order->fresh('payment') ?? $order;
|
||||
}
|
||||
|
||||
$isEscrow = ($pgResponse['escw_yn'] ?? '') === 'Y';
|
||||
$easyPayMeta = $this->resolveEasyPayMeta($validated);
|
||||
|
||||
@@ -397,7 +403,10 @@ class PaymentCallbackController
|
||||
// Approve 가 이미 KCP 측에서 발생했으면 자동 취소로 PG 잔존 승인 해제
|
||||
$this->autoCancelIfApproved($approvedTno, $ordrIdxx, $approvedAmtForCancel, 'amount_mismatch');
|
||||
|
||||
if ($order instanceof Order) {
|
||||
// 주문 상태를 바꾸는 것은 KCP 승인이 실제로 일어난 뒤의 실패뿐이다. tno 가 비어 있으면
|
||||
// 승인 전에 터진 예외이고, 그 시점의 입력은 전부 비인증 브라우저가 보낸 값이라
|
||||
// 남의 주문을 취소시키는 통로가 된다.
|
||||
if ($order instanceof Order && $this->hasApproval($approvedTno)) {
|
||||
$failedOrder = $this->orderService->failPayment($order, 'AMOUNT_MISMATCH', $e->getMessage());
|
||||
$this->markKcpPaymentFailureRecord(
|
||||
$failedOrder,
|
||||
@@ -417,7 +426,8 @@ class PaymentCallbackController
|
||||
|
||||
$this->autoCancelIfApproved($approvedTno, $ordrIdxx, $approvedAmtForCancel, 'confirm_failed');
|
||||
|
||||
if ($order instanceof Order) {
|
||||
// 승인 이후의 후속 처리 실패만 주문에 반영한다 (위 amount_mismatch catch 와 동일 기준).
|
||||
if ($order instanceof Order && $this->hasApproval($approvedTno)) {
|
||||
$failedOrder = $this->orderService->failPayment($order, 'CONFIRM_FAILED', $e->getMessage());
|
||||
$this->markKcpPaymentFailureRecord(
|
||||
$failedOrder,
|
||||
@@ -577,8 +587,11 @@ class PaymentCallbackController
|
||||
* Mobile SmartPhone Pay: enc_data 없이 평문 필드(bankname/account/depositor/va_date)가
|
||||
* 콜백 POST 에 직접 포함되므로 CLI 호출을 건너뛰고 요청에서 직접 읽음.
|
||||
*
|
||||
* 발급 성공 = res_cd == 0000 AND bankname/account 가 모두 채워진 경우만.
|
||||
* 그 외 (CLI 9502 / 예외 / 평문 필드 결락) 는 발급 실패로 판정해 failPayment + fail URL.
|
||||
* 발급 성공 = bankname/account 가 모두 채워진 경우만 (정상 res_cd 는 결제수단별로 다르다).
|
||||
* 그 외 (CLI 9502 / 예외 / 평문 필드 결락) 는 발급 실패로 판정하되 **주문 상태는 바꾸지
|
||||
* 않고** fail URL 로 되돌려 보낸다 — 이 엔드포인트는 비인증 브라우저 POST 라, 발급 미완을
|
||||
* 근거로 실패 처리하면 주문번호만 아는 제3자가 남의 주문을 취소시킬 수 있다
|
||||
* (KVE-2026-2018 과 동일 기준). 정당한 실패는 소유권을 검증하는 close-report 가 기록한다.
|
||||
*/
|
||||
private function handleVbankIssued(
|
||||
array $validated,
|
||||
@@ -615,14 +628,10 @@ class PaymentCallbackController
|
||||
'error' => $e->getMessage(),
|
||||
]);
|
||||
|
||||
$failedOrder = $this->orderService->failPayment($order, 'cli_exception', $e->getMessage());
|
||||
$this->markKcpPaymentFailureRecord(
|
||||
$failedOrder,
|
||||
'cli_exception',
|
||||
$e->getMessage(),
|
||||
'vbank_cli_exception',
|
||||
);
|
||||
|
||||
// 승인이 성립하지 않았다 — 주문 상태를 바꾸지 않는다. 이 엔드포인트는 비인증
|
||||
// 브라우저 POST 라, CLI 실패를 근거로 실패 처리하면 남의 주문번호와 위조 입력만으로
|
||||
// 그 주문을 취소시킬 수 있다 (카드 경로와 동일 기준 · KVE-2026-2018).
|
||||
// 정당한 결제 실패는 소유권을 검증하는 close-report 가 기록한다.
|
||||
return redirect($this->resolveFailUrl([
|
||||
'error' => 'cli_exception',
|
||||
'message' => __('sirsoft-pay_nhnkcp::messages.errors.payment_failed'),
|
||||
@@ -660,14 +669,12 @@ class PaymentCallbackController
|
||||
'is_mobile' => $isMobile,
|
||||
]);
|
||||
|
||||
$failedOrder = $this->orderService->failPayment($order, $effectiveCode, $effectiveMsg);
|
||||
$this->markKcpPaymentFailureRecord(
|
||||
$failedOrder,
|
||||
$effectiveCode,
|
||||
$effectiveMsg,
|
||||
'vbank_issuance_failed',
|
||||
);
|
||||
|
||||
// 발급이 성립하지 않았다 — 주문 상태를 바꾸지 않는다.
|
||||
// 모바일 분기의 $pgResponse 는 콜백 POST 평문을 그대로 옮긴 값이라 PG 서버 호출이
|
||||
// 아예 없고, PC 분기의 CLI 실패도 위조 암호문으로 유도할 수 있다. 어느 쪽이든
|
||||
// 비인증 브라우저 입력이므로 이를 근거로 실패 처리하면 주문번호만 아는 제3자가
|
||||
// 남의 결제대기 주문을 취소시킬 수 있다 (카드 경로와 동일 기준 · KVE-2026-2018).
|
||||
// 정당한 발급 실패는 소유권을 검증하는 close-report 가 기록한다.
|
||||
return redirect($this->resolveFailUrl([
|
||||
'error' => $effectiveCode,
|
||||
'message' => $effectiveMsg,
|
||||
@@ -693,8 +700,28 @@ class PaymentCallbackController
|
||||
]);
|
||||
}
|
||||
|
||||
// 취소 주문 재결제 — 되살리기는 상태 변경이므로 PG 서버가 발급을 확인해 준 PC 분기에서만
|
||||
// 수행한다. 모바일 분기는 서버 호출이 없어 발급 증거가 콜백 평문뿐이라, 되살리면
|
||||
// 주문번호만 아는 제3자가 남의 취소 주문을 되돌릴 수 있다.
|
||||
if ($order->order_status === OrderStatusEnum::CANCELLED) {
|
||||
if ($isMobile || ! $this->restoreRetryableKcpOrder($order, null)) {
|
||||
Log::warning('KCP: cancelled vbank order not restored (no server-side issuance proof)', [
|
||||
'ordr_idxx' => $ordrIdxx,
|
||||
'is_mobile' => $isMobile,
|
||||
]);
|
||||
|
||||
return redirect($this->resolveFailUrl([
|
||||
'error' => 'order_not_retryable',
|
||||
'orderId' => $ordrIdxx,
|
||||
]));
|
||||
}
|
||||
|
||||
$order = $order->fresh('payment') ?? $order;
|
||||
}
|
||||
|
||||
// 가상계좌 발급 정보를 OrderPayment vbank 전용 컬럼에 저장 (PENDING_PAYMENT 상태 유지).
|
||||
// 저장 실패 시도 부분 저장으로 사용자에게 잘못된 정보가 노출되지 않도록 failPayment 처리.
|
||||
// 저장이 실패하면 부분 저장으로 잘못된 계좌가 노출되지 않도록 실패로 되돌린다. 단
|
||||
// failPayment 는 PG 서버가 발급을 확인해 준 PC 분기에서만 부른다 (아래 catch 참조).
|
||||
try {
|
||||
$expireRaw = $pgResponse['va_date'] ?? null;
|
||||
$vbankDueAt = null;
|
||||
@@ -735,13 +762,17 @@ class PaymentCallbackController
|
||||
'error' => $e->getMessage(),
|
||||
]);
|
||||
|
||||
$failedOrder = $this->orderService->failPayment($order, 'vbank_save_failed', $e->getMessage());
|
||||
$this->markKcpPaymentFailureRecord(
|
||||
$failedOrder,
|
||||
'vbank_save_failed',
|
||||
$e->getMessage(),
|
||||
'vbank_save_failed',
|
||||
);
|
||||
// PG 서버가 발급을 확인해 준 PC 분기에서만 주문에 반영한다. 모바일 분기의 발급 데이터는
|
||||
// 콜백 평문이라 위조할 수 있어, 저장 실패를 근거로 주문을 취소시키는 통로가 된다.
|
||||
if (! $isMobile) {
|
||||
$failedOrder = $this->orderService->failPayment($order, 'vbank_save_failed', $e->getMessage());
|
||||
$this->markKcpPaymentFailureRecord(
|
||||
$failedOrder,
|
||||
'vbank_save_failed',
|
||||
$e->getMessage(),
|
||||
'vbank_save_failed',
|
||||
);
|
||||
}
|
||||
|
||||
return redirect($this->resolveFailUrl([
|
||||
'error' => 'vbank_save_failed',
|
||||
@@ -850,6 +881,20 @@ class PaymentCallbackController
|
||||
* cancel 자체가 실패해도 사용자 응답 흐름은 막지 않음 — 로깅만 수행하고
|
||||
* 운영자가 KCP 가맹점 관리자에서 수동 처리하도록 신호.
|
||||
*/
|
||||
/**
|
||||
* KCP 승인이 실제로 발생했는지 판정합니다.
|
||||
*
|
||||
* tno 는 승인 응답이 성공한 뒤에만 채워진다. 비어 있으면 승인 전에 흐름이 끊긴 것이고,
|
||||
* 그 시점까지의 입력은 전부 비인증 브라우저가 보낸 값이라 주문 상태 변경의 근거가 될 수 없다.
|
||||
*
|
||||
* @param string|null $approvedTno 승인 확정 시 기록되는 거래번호
|
||||
* @return bool 승인이 발생했으면 true
|
||||
*/
|
||||
private function hasApproval(?string $approvedTno): bool
|
||||
{
|
||||
return $approvedTno !== null && $approvedTno !== '';
|
||||
}
|
||||
|
||||
private function autoCancelIfApproved(
|
||||
?string $tno,
|
||||
string $ordrIdxx,
|
||||
|
||||
+274
-117
@@ -3,6 +3,8 @@
|
||||
namespace Plugins\Sirsoft\PayNhnkcp\Tests\Feature\Controllers;
|
||||
|
||||
use App\Models\User;
|
||||
use App\Services\PluginSettingsService;
|
||||
use Illuminate\Testing\TestResponse;
|
||||
use Modules\Sirsoft\Ecommerce\Database\Factories\OrderFactory;
|
||||
use Modules\Sirsoft\Ecommerce\Database\Factories\OrderPaymentFactory;
|
||||
use Modules\Sirsoft\Ecommerce\Enums\OrderStatusEnum;
|
||||
@@ -23,22 +25,22 @@ class PaymentCallbackControllerTest extends PluginTestCase
|
||||
private function makeCliResponse(string $tno, string $ordrIdxx, int $amount, string $resCd = '0000'): array
|
||||
{
|
||||
return [
|
||||
'res_cd' => $resCd,
|
||||
'res_msg' => $resCd === '0000' ? '정상처리' : '승인실패',
|
||||
'tno' => $tno,
|
||||
'ordr_idxx' => $ordrIdxx,
|
||||
'good_mny' => $amount,
|
||||
'app_no' => 'APP12345',
|
||||
'card_no' => '4330****1234',
|
||||
'card_name' => '신한카드',
|
||||
'quota' => '00',
|
||||
'use_pay_method' => 'CARD',
|
||||
'app_time' => now()->format('YmdHis'),
|
||||
'res_cd' => $resCd,
|
||||
'res_msg' => $resCd === '0000' ? '정상처리' : '승인실패',
|
||||
'tno' => $tno,
|
||||
'ordr_idxx' => $ordrIdxx,
|
||||
'good_mny' => $amount,
|
||||
'app_no' => 'APP12345',
|
||||
'card_no' => '4330****1234',
|
||||
'card_name' => '신한카드',
|
||||
'quota' => '00',
|
||||
'use_pay_method' => 'CARD',
|
||||
'app_time' => now()->format('YmdHis'),
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array{taxable?: int, vat?: int, taxFree?: int} $tax
|
||||
* @param array{taxable?: int, vat?: int, taxFree?: int} $tax
|
||||
*/
|
||||
private function createTestOrder(
|
||||
int $totalAmount = 50000,
|
||||
@@ -46,45 +48,45 @@ class PaymentCallbackControllerTest extends PluginTestCase
|
||||
PaymentMethodEnum $paymentMethod = PaymentMethodEnum::CARD,
|
||||
): Order {
|
||||
$taxable = $tax['taxable'] ?? $totalAmount;
|
||||
$vat = $tax['vat'] ?? (int) round($taxable * 10 / 110);
|
||||
$vat = $tax['vat'] ?? (int) round($taxable * 10 / 110);
|
||||
$taxFree = $tax['taxFree'] ?? 0;
|
||||
|
||||
$user = User::factory()->create();
|
||||
|
||||
$order = OrderFactory::new()->create([
|
||||
'user_id' => $user->id,
|
||||
'order_number' => 'ORD-TEST-' . random_int(10000, 99999),
|
||||
'order_status' => OrderStatusEnum::PENDING_ORDER,
|
||||
'subtotal_amount' => $totalAmount,
|
||||
'total_discount_amount' => 0,
|
||||
'total_coupon_discount_amount' => 0,
|
||||
'user_id' => $user->id,
|
||||
'order_number' => 'ORD-TEST-'.random_int(10000, 99999),
|
||||
'order_status' => OrderStatusEnum::PENDING_ORDER,
|
||||
'subtotal_amount' => $totalAmount,
|
||||
'total_discount_amount' => 0,
|
||||
'total_coupon_discount_amount' => 0,
|
||||
'total_product_coupon_discount_amount' => 0,
|
||||
'total_order_coupon_discount_amount' => 0,
|
||||
'total_code_discount_amount' => 0,
|
||||
'base_shipping_amount' => 0,
|
||||
'extra_shipping_amount' => 0,
|
||||
'shipping_discount_amount' => 0,
|
||||
'total_shipping_amount' => 0,
|
||||
'total_amount' => $totalAmount,
|
||||
'total_due_amount' => $totalAmount,
|
||||
'total_points_used_amount' => 0,
|
||||
'total_deposit_used_amount' => 0,
|
||||
'total_paid_amount' => 0,
|
||||
'total_tax_amount' => $taxable,
|
||||
'total_vat_amount' => $vat,
|
||||
'total_tax_free_amount' => $taxFree,
|
||||
'currency' => 'KRW',
|
||||
'currency_snapshot' => self::krwCurrencySnapshot(),
|
||||
'total_code_discount_amount' => 0,
|
||||
'base_shipping_amount' => 0,
|
||||
'extra_shipping_amount' => 0,
|
||||
'shipping_discount_amount' => 0,
|
||||
'total_shipping_amount' => 0,
|
||||
'total_amount' => $totalAmount,
|
||||
'total_due_amount' => $totalAmount,
|
||||
'total_points_used_amount' => 0,
|
||||
'total_deposit_used_amount' => 0,
|
||||
'total_paid_amount' => 0,
|
||||
'total_tax_amount' => $taxable,
|
||||
'total_vat_amount' => $vat,
|
||||
'total_tax_free_amount' => $taxFree,
|
||||
'currency' => 'KRW',
|
||||
'currency_snapshot' => self::krwCurrencySnapshot(),
|
||||
]);
|
||||
|
||||
OrderPaymentFactory::new()->create([
|
||||
'order_id' => $order->id,
|
||||
'payment_status' => PaymentStatusEnum::READY,
|
||||
'payment_method' => $paymentMethod,
|
||||
'pg_provider' => 'nhnkcp',
|
||||
'paid_amount_local' => 0,
|
||||
'paid_at' => null,
|
||||
'transaction_id' => null,
|
||||
'order_id' => $order->id,
|
||||
'payment_status' => PaymentStatusEnum::READY,
|
||||
'payment_method' => $paymentMethod,
|
||||
'pg_provider' => 'nhnkcp',
|
||||
'paid_amount_local' => 0,
|
||||
'paid_at' => null,
|
||||
'transaction_id' => null,
|
||||
'card_approval_number' => null,
|
||||
]);
|
||||
|
||||
@@ -137,18 +139,18 @@ class PaymentCallbackControllerTest extends PluginTestCase
|
||||
private function mockPluginSettings(array $overrides = []): void
|
||||
{
|
||||
$defaults = [
|
||||
'is_test_mode' => true,
|
||||
'test_site_cd' => self::TEST_SITE_CD,
|
||||
'test_site_key' => self::TEST_SITE_KEY,
|
||||
'live_site_cd' => '',
|
||||
'live_site_key' => '',
|
||||
'is_test_mode' => true,
|
||||
'test_site_cd' => self::TEST_SITE_CD,
|
||||
'test_site_key' => self::TEST_SITE_KEY,
|
||||
'live_site_cd' => '',
|
||||
'live_site_key' => '',
|
||||
'redirect_success_url' => '/shop/orders/{orderId}/complete',
|
||||
'redirect_fail_url' => '/shop/checkout',
|
||||
'redirect_fail_url' => '/shop/checkout',
|
||||
];
|
||||
|
||||
$mock = $this->createMock(\App\Services\PluginSettingsService::class);
|
||||
$mock = $this->createMock(PluginSettingsService::class);
|
||||
$mock->method('get')->willReturn(array_merge($defaults, $overrides));
|
||||
$this->app->instance(\App\Services\PluginSettingsService::class, $mock);
|
||||
$this->app->instance(PluginSettingsService::class, $mock);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -168,14 +170,14 @@ class PaymentCallbackControllerTest extends PluginTestCase
|
||||
private function makeCallbackParams(string $ordrIdxx, int $goodMny, array $overrides = []): array
|
||||
{
|
||||
return array_merge([
|
||||
'res_cd' => '0000',
|
||||
'res_msg' => '정상처리',
|
||||
'tno' => 'KCP_TNO_' . uniqid(),
|
||||
'ordr_idxx' => $ordrIdxx,
|
||||
'good_mny' => $goodMny,
|
||||
'enc_data' => base64_encode('encrypted_payment_data'),
|
||||
'enc_info' => base64_encode('encrypted_info'),
|
||||
'use_pay_method' => 'CARD',
|
||||
'res_cd' => '0000',
|
||||
'res_msg' => '정상처리',
|
||||
'tno' => 'KCP_TNO_'.uniqid(),
|
||||
'ordr_idxx' => $ordrIdxx,
|
||||
'good_mny' => $goodMny,
|
||||
'enc_data' => base64_encode('encrypted_payment_data'),
|
||||
'enc_info' => base64_encode('encrypted_info'),
|
||||
'use_pay_method' => 'CARD',
|
||||
], $overrides);
|
||||
}
|
||||
|
||||
@@ -211,7 +213,7 @@ class PaymentCallbackControllerTest extends PluginTestCase
|
||||
$order = $this->createTestOrder(50000);
|
||||
$this->mockPluginSettings();
|
||||
|
||||
$tno = 'KCP_TNO_' . uniqid();
|
||||
$tno = 'KCP_TNO_'.uniqid();
|
||||
$this->mockApiService($this->makeCliResponse($tno, $order->order_number, 50000));
|
||||
|
||||
$response = $this->post(
|
||||
@@ -410,8 +412,8 @@ class PaymentCallbackControllerTest extends PluginTestCase
|
||||
{
|
||||
// 11,000원 = 공급가 10,000 + 부가세 1,000 (전액 과세)
|
||||
$amount = 11000;
|
||||
$vat = (int) round($amount * 10 / 110); // 1,000
|
||||
$order = $this->createTestOrder($amount, ['taxable' => $amount, 'vat' => $vat, 'taxFree' => 0]);
|
||||
$vat = (int) round($amount * 10 / 110); // 1,000
|
||||
$order = $this->createTestOrder($amount, ['taxable' => $amount, 'vat' => $vat, 'taxFree' => 0]);
|
||||
$this->mockPluginSettings();
|
||||
|
||||
$tno = 'KCP_TNO_TAXABLE';
|
||||
@@ -435,7 +437,7 @@ class PaymentCallbackControllerTest extends PluginTestCase
|
||||
{
|
||||
// 10,000원 전액 비과세 (도서, 농산물, 의료 등 면세 상품)
|
||||
$amount = 10000;
|
||||
$order = $this->createTestOrder($amount, ['taxable' => 0, 'vat' => 0, 'taxFree' => $amount]);
|
||||
$order = $this->createTestOrder($amount, ['taxable' => 0, 'vat' => 0, 'taxFree' => $amount]);
|
||||
$this->mockPluginSettings();
|
||||
|
||||
$tno = 'KCP_TNO_TAXFREE';
|
||||
@@ -461,9 +463,9 @@ class PaymentCallbackControllerTest extends PluginTestCase
|
||||
// 21,000원 = 과세 11,000(공급가 10,000 + 부가세 1,000) + 비과세 10,000
|
||||
$taxable = 11000;
|
||||
$taxFree = 10000;
|
||||
$total = $taxable + $taxFree;
|
||||
$vat = (int) round($taxable * 10 / 110); // 1,000
|
||||
$order = $this->createTestOrder($total, ['taxable' => $taxable, 'vat' => $vat, 'taxFree' => $taxFree]);
|
||||
$total = $taxable + $taxFree;
|
||||
$vat = (int) round($taxable * 10 / 110); // 1,000
|
||||
$order = $this->createTestOrder($total, ['taxable' => $taxable, 'vat' => $vat, 'taxFree' => $taxFree]);
|
||||
$this->mockPluginSettings();
|
||||
|
||||
$tno = 'KCP_TNO_MIXED';
|
||||
@@ -486,7 +488,7 @@ class PaymentCallbackControllerTest extends PluginTestCase
|
||||
$this->mockPluginSettings();
|
||||
|
||||
$response = $this->post('/plugins/sirsoft-pay_nhnkcp/payment/callback', $this->makeCallbackParams('ORD-TEST-99999', 50000, [
|
||||
'res_cd' => '8001',
|
||||
'res_cd' => '8001',
|
||||
'res_msg' => '사용자 취소',
|
||||
]));
|
||||
|
||||
@@ -499,8 +501,8 @@ class PaymentCallbackControllerTest extends PluginTestCase
|
||||
$this->mockPluginSettings();
|
||||
|
||||
$response = $this->post('/plugins/sirsoft-pay_nhnkcp/payment/callback', [
|
||||
'res_cd' => '3001',
|
||||
'res_msg' => '사용자취소',
|
||||
'res_cd' => '3001',
|
||||
'res_msg' => '사용자취소',
|
||||
'ordr_idxx' => 'ORD-TEST-CANCEL',
|
||||
]);
|
||||
|
||||
@@ -539,7 +541,7 @@ class PaymentCallbackControllerTest extends PluginTestCase
|
||||
$this->mockPluginSettings();
|
||||
|
||||
$response = $this->post('/plugins/sirsoft-pay_nhnkcp/payment/callback', [
|
||||
'res_cd' => '',
|
||||
'res_cd' => '',
|
||||
'ordr_idxx' => 'ORD-TEST-EMPTY',
|
||||
]);
|
||||
|
||||
@@ -561,12 +563,23 @@ class PaymentCallbackControllerTest extends PluginTestCase
|
||||
$this->assertStringContainsString('error=order_not_found', $response->headers->get('Location'));
|
||||
}
|
||||
|
||||
public function test_auth_callback_redirects_to_fail_when_cli_approval_fails(): void
|
||||
/**
|
||||
* 서버 승인이 실패하면 실패 URL 로 돌아가되 주문 상태는 건드리지 않는다.
|
||||
*
|
||||
* 계약 변경(KVE-2026-2018): `authCallback` 은 PG 서명도 IP 증명도 없는 비인증 브라우저
|
||||
* POST 다. 주문번호는 요청자가 고른 값이라, 승인 실패를 근거로 주문을 취소하면 남의
|
||||
* 주문번호와 아무 암호문이나 실어 보내는 것만으로 그 주문을 취소시킬 수 있다.
|
||||
* 승인이 성공하지 않은 이상 이 엔드포인트는 상태를 바꾸지 않는다.
|
||||
*/
|
||||
public function test_auth_callback_does_not_mutate_the_order_when_cli_approval_fails(): void
|
||||
{
|
||||
$order = $this->createTestOrder(50000);
|
||||
$this->mockPluginSettings();
|
||||
$this->mockApiService($this->makeCliResponse('TNO_FAIL', $order->order_number, 50000, '9999'));
|
||||
|
||||
$statusBefore = $order->order_status;
|
||||
$paymentStatusBefore = $order->payment->payment_status;
|
||||
|
||||
$response = $this->post(
|
||||
'/plugins/sirsoft-pay_nhnkcp/payment/callback',
|
||||
$this->makeCallbackParams($order->order_number, 50000)
|
||||
@@ -579,14 +592,16 @@ class PaymentCallbackControllerTest extends PluginTestCase
|
||||
$payment = $order->payment;
|
||||
$payment->refresh();
|
||||
|
||||
$this->assertEquals(OrderStatusEnum::CANCELLED, $order->order_status);
|
||||
$this->assertEquals(PaymentStatusEnum::FAILED, $payment->payment_status);
|
||||
$this->assertSame('nhnkcp', $payment->payment_meta['failure_source'] ?? null);
|
||||
$this->assertSame('9999', $payment->payment_meta['failure_code'] ?? null);
|
||||
$this->assertSame('approval_failed', $payment->payment_meta['failure_stage'] ?? null);
|
||||
$this->assertEquals($statusBefore, $order->order_status, '비인증 콜백이 주문 상태를 바꿨습니다.');
|
||||
$this->assertEquals($paymentStatusBefore, $payment->payment_status, '비인증 콜백이 결제 상태를 바꿨습니다.');
|
||||
$this->assertNotEquals(OrderStatusEnum::CANCELLED, $order->order_status);
|
||||
$this->assertArrayNotHasKey('failure_stage', $payment->payment_meta ?? []);
|
||||
}
|
||||
|
||||
public function test_auth_callback_records_amount_mismatch_as_non_retryable_kcp_failure(): void
|
||||
/**
|
||||
* 브라우저가 보낸 금액이 주문 금액과 다르면 승인 자체를 하지 않고, 주문도 건드리지 않는다.
|
||||
*/
|
||||
public function test_auth_callback_does_not_mutate_the_order_on_browser_amount_mismatch(): void
|
||||
{
|
||||
$order = $this->createTestOrder(50000);
|
||||
$this->mockPluginSettings();
|
||||
@@ -594,6 +609,9 @@ class PaymentCallbackControllerTest extends PluginTestCase
|
||||
$tno = 'KCP_TNO_AMOUNT_MISMATCH';
|
||||
$this->mockApiService($this->makeCliResponse($tno, $order->order_number, 60000));
|
||||
|
||||
$statusBefore = $order->order_status;
|
||||
$paymentStatusBefore = $order->payment->payment_status;
|
||||
|
||||
$response = $this->post(
|
||||
'/plugins/sirsoft-pay_nhnkcp/payment/callback',
|
||||
$this->makeCallbackParams($order->order_number, 60000, ['tno' => $tno])
|
||||
@@ -606,11 +624,120 @@ class PaymentCallbackControllerTest extends PluginTestCase
|
||||
$payment = $order->payment;
|
||||
$payment->refresh();
|
||||
|
||||
$this->assertEquals(OrderStatusEnum::CANCELLED, $order->order_status);
|
||||
$this->assertEquals(PaymentStatusEnum::FAILED, $payment->payment_status);
|
||||
$this->assertSame('nhnkcp', $payment->payment_meta['failure_source'] ?? null);
|
||||
$this->assertSame('AMOUNT_MISMATCH', $payment->payment_meta['failure_code'] ?? null);
|
||||
$this->assertSame('amount_mismatch', $payment->payment_meta['failure_stage'] ?? null);
|
||||
$this->assertEquals($statusBefore, $order->order_status, '비인증 콜백이 주문 상태를 바꿨습니다.');
|
||||
$this->assertEquals($paymentStatusBefore, $payment->payment_status, '비인증 콜백이 결제 상태를 바꿨습니다.');
|
||||
$this->assertNotEquals(OrderStatusEnum::CANCELLED, $order->order_status);
|
||||
}
|
||||
|
||||
/**
|
||||
* 무인증 위조 콜백으로 타인의 결제대기 주문을 취소할 수 없다 (KVE-2026-2018 회귀).
|
||||
*
|
||||
* 공격자는 로그인하지 않고, 피해자의 주문번호와 아무 암호문만으로 이 엔드포인트를 친다.
|
||||
* 서버 승인은 당연히 실패하는데, 그 실패를 피해 주문의 결제 실패로 오인 처리하면
|
||||
* 남의 주문이 취소된다.
|
||||
*/
|
||||
public function test_forged_unauthenticated_callback_cannot_cancel_another_users_order(): void
|
||||
{
|
||||
$victimOrder = $this->createTestOrder(50000);
|
||||
$this->mockPluginSettings();
|
||||
$this->mockApiService($this->makeCliResponse('', $victimOrder->order_number, 0, '6003'));
|
||||
|
||||
$response = $this->post(
|
||||
'/plugins/sirsoft-pay_nhnkcp/payment/callback',
|
||||
$this->makeCallbackParams($victimOrder->order_number, 0, [
|
||||
'enc_data' => 'FORGED_CIPHERTEXT',
|
||||
'enc_info' => 'FORGED_INFO',
|
||||
])
|
||||
);
|
||||
|
||||
$response->assertRedirect();
|
||||
|
||||
$victimOrder->refresh();
|
||||
$payment = $victimOrder->payment;
|
||||
$payment->refresh();
|
||||
|
||||
$this->assertEquals(
|
||||
OrderStatusEnum::PENDING_ORDER,
|
||||
$victimOrder->order_status,
|
||||
'무인증 위조 콜백이 피해자의 주문을 취소시켰습니다.'
|
||||
);
|
||||
$this->assertNotEquals(PaymentStatusEnum::FAILED, $payment->payment_status);
|
||||
$this->assertArrayNotHasKey('payment_failure_code', $victimOrder->order_meta ?? []);
|
||||
}
|
||||
|
||||
/**
|
||||
* 카드 주문에 use_pay_method=VCNT 를 실어 가상계좌 분기로 우회하는 통로 차단.
|
||||
*
|
||||
* 가상계좌 모바일 분기는 enc_data/enc_info 가 비면 PG 서버를 호출하지 않고 콜백 평문을
|
||||
* 그대로 승인 응답으로 취급한다. 분기 판정이 요청값을 보면 공격자가 카드 주문을 그 경로로
|
||||
* 몰아, 은행명·계좌번호를 비운 것만으로 "발급 실패" 를 만들어 남의 주문을 취소시킬 수 있다.
|
||||
*/
|
||||
public function test_forged_vbank_routed_callback_cannot_cancel_a_card_order(): void
|
||||
{
|
||||
$victimOrder = $this->createTestOrder(50000);
|
||||
$this->mockPluginSettings();
|
||||
|
||||
$response = $this->post(
|
||||
'/plugins/sirsoft-pay_nhnkcp/payment/callback',
|
||||
[
|
||||
'res_cd' => '0000',
|
||||
'ordr_idxx' => $victimOrder->order_number,
|
||||
'tno' => 'FORGED',
|
||||
// 금액을 비워 승인 전 금액 검증을 건너뛴다
|
||||
// enc_data/enc_info 를 비워 CLI 호출 자체를 우회한다
|
||||
// bankname/account 를 비워 "발급 실패" 판정을 유도한다
|
||||
'use_pay_method' => 'VCNT',
|
||||
]
|
||||
);
|
||||
|
||||
$response->assertRedirect();
|
||||
|
||||
$victimOrder->refresh();
|
||||
$payment = $victimOrder->payment;
|
||||
$payment->refresh();
|
||||
|
||||
$this->assertEquals(
|
||||
OrderStatusEnum::PENDING_ORDER,
|
||||
$victimOrder->order_status,
|
||||
'위조 콜백이 use_pay_method=VCNT 우회로 피해자의 카드 주문을 취소시켰습니다.'
|
||||
);
|
||||
$this->assertNotEquals(PaymentStatusEnum::FAILED, $payment->payment_status);
|
||||
$this->assertArrayNotHasKey('payment_failure_code', $victimOrder->order_meta ?? []);
|
||||
}
|
||||
|
||||
/**
|
||||
* 분기 판정이 주문의 결제수단만 본다는 계약 (요청값으로 경로를 고를 수 없다).
|
||||
*
|
||||
* 카드 주문에 VCNT + 위조 발급정보를 실어도 가상계좌 발급으로 기록되지 않아야 한다.
|
||||
* 요청값으로 분기가 갈리면 공격자가 피해자 카드 주문에 임의 계좌번호를 심을 수 있다.
|
||||
*/
|
||||
public function test_request_pay_method_cannot_route_a_card_order_into_the_vbank_branch(): void
|
||||
{
|
||||
$victimOrder = $this->createTestOrder(50000);
|
||||
$this->mockPluginSettings();
|
||||
$this->mockApiService($this->makeCliResponse('', $victimOrder->order_number, 0, '6003'));
|
||||
|
||||
$this->post(
|
||||
'/plugins/sirsoft-pay_nhnkcp/payment/callback',
|
||||
[
|
||||
'res_cd' => '0000',
|
||||
'ordr_idxx' => $victimOrder->order_number,
|
||||
'tno' => 'FORGED',
|
||||
'use_pay_method' => 'VCNT',
|
||||
'bankname' => '공격자은행',
|
||||
'account' => '110-000-999999',
|
||||
'depositor' => '공격자',
|
||||
]
|
||||
);
|
||||
|
||||
$payment = $victimOrder->payment;
|
||||
$payment->refresh();
|
||||
|
||||
$this->assertNull(
|
||||
$payment->vbank_number,
|
||||
'요청의 use_pay_method 로 카드 주문이 가상계좌 분기로 흘러 위조 계좌가 기록됐습니다.'
|
||||
);
|
||||
$this->assertNull($payment->vbank_name);
|
||||
}
|
||||
|
||||
public function test_auth_callback_redirects_to_fail_url_on_missing_params(): void
|
||||
@@ -671,14 +798,14 @@ class PaymentCallbackControllerTest extends PluginTestCase
|
||||
// - result=0000 → KCP 가 통보 성공으로 인정 (재시도 차단)
|
||||
// - 그 외 → KCP 재통보 (최대 10회)
|
||||
|
||||
private function assertKcpNotifyOk(\Illuminate\Testing\TestResponse $response): void
|
||||
private function assertKcpNotifyOk(TestResponse $response): void
|
||||
{
|
||||
$response->assertOk();
|
||||
$this->assertStringContainsString('name="result"', $response->getContent());
|
||||
$this->assertStringContainsString('value="0000"', $response->getContent());
|
||||
}
|
||||
|
||||
private function assertKcpNotifyRetry(\Illuminate\Testing\TestResponse $response): void
|
||||
private function assertKcpNotifyRetry(TestResponse $response): void
|
||||
{
|
||||
$response->assertOk();
|
||||
$this->assertStringContainsString('name="result"', $response->getContent());
|
||||
@@ -688,18 +815,18 @@ class PaymentCallbackControllerTest extends PluginTestCase
|
||||
private function makeVbankNotifyPayload(string $orderNo, int $amount, array $overrides = []): array
|
||||
{
|
||||
return array_merge([
|
||||
'site_cd' => 'T0000',
|
||||
'tno' => 'KCP_VBANK_TNO_' . uniqid(),
|
||||
'order_no' => $orderNo,
|
||||
'tx_cd' => 'TX00',
|
||||
'tx_tm' => now()->format('YmdHis'),
|
||||
'op_cd' => '50',
|
||||
'ipgm_mnyx' => $amount,
|
||||
'ipgm_name' => '홍길동',
|
||||
'remitter' => '홍길동',
|
||||
'bank_code' => 'BK04',
|
||||
'account' => 'T1234567890',
|
||||
'noti_id' => uniqid('NOTI_'),
|
||||
'site_cd' => 'T0000',
|
||||
'tno' => 'KCP_VBANK_TNO_'.uniqid(),
|
||||
'order_no' => $orderNo,
|
||||
'tx_cd' => 'TX00',
|
||||
'tx_tm' => now()->format('YmdHis'),
|
||||
'op_cd' => '50',
|
||||
'ipgm_mnyx' => $amount,
|
||||
'ipgm_name' => '홍길동',
|
||||
'remitter' => '홍길동',
|
||||
'bank_code' => 'BK04',
|
||||
'account' => 'T1234567890',
|
||||
'noti_id' => uniqid('NOTI_'),
|
||||
], $overrides);
|
||||
}
|
||||
|
||||
@@ -707,7 +834,7 @@ class PaymentCallbackControllerTest extends PluginTestCase
|
||||
* KCP 공식 발신 IP 로 vbank-notify POST.
|
||||
* RestrictKcpIp 미들웨어가 항상 IP 검증하므로 화이트리스트 IP 필수.
|
||||
*/
|
||||
private function postVbankNotify(array $payload, string $kcpIp = '203.238.36.58'): \Illuminate\Testing\TestResponse
|
||||
private function postVbankNotify(array $payload, string $kcpIp = '203.238.36.58'): TestResponse
|
||||
{
|
||||
return $this->withServerVariables(['REMOTE_ADDR' => $kcpIp])
|
||||
->post('/plugins/sirsoft-pay_nhnkcp/payment/vbank-notify', $payload);
|
||||
@@ -840,18 +967,18 @@ class PaymentCallbackControllerTest extends PluginTestCase
|
||||
$this->markVbankIssued($order, 'KCP_TNO_REAL', 'T9876543210');
|
||||
|
||||
$response = $this->postVbankNotify([
|
||||
'site_cd' => 'T0000',
|
||||
'tno' => 'KCP_TNO_REAL',
|
||||
'order_no' => $order->order_number,
|
||||
'tx_cd' => 'TX00',
|
||||
'tx_tm' => '20260514120000',
|
||||
'op_cd' => '50',
|
||||
'site_cd' => 'T0000',
|
||||
'tno' => 'KCP_TNO_REAL',
|
||||
'order_no' => $order->order_number,
|
||||
'tx_cd' => 'TX00',
|
||||
'tx_tm' => '20260514120000',
|
||||
'op_cd' => '50',
|
||||
'ipgm_mnyx' => 50000,
|
||||
'ipgm_name' => '홍길동',
|
||||
'remitter' => '실입금자',
|
||||
'remitter' => '실입금자',
|
||||
'bank_code' => '04',
|
||||
'account' => 'T9876543210',
|
||||
'noti_id' => '26051412000018046532',
|
||||
'account' => 'T9876543210',
|
||||
'noti_id' => '26051412000018046532',
|
||||
]);
|
||||
|
||||
$this->assertKcpNotifyOk($response);
|
||||
@@ -1012,21 +1139,21 @@ class PaymentCallbackControllerTest extends PluginTestCase
|
||||
|
||||
$tno = 'KCP_VBANK_V000';
|
||||
$this->mockApiService([
|
||||
'res_cd' => 'V000',
|
||||
'res_msg' => '가상계좌가 발급되었습니다.',
|
||||
'tno' => $tno,
|
||||
'bankname' => 'NH농협',
|
||||
'account' => 'T1109260001455',
|
||||
'res_cd' => 'V000',
|
||||
'res_msg' => '가상계좌가 발급되었습니다.',
|
||||
'tno' => $tno,
|
||||
'bankname' => 'NH농협',
|
||||
'account' => 'T1109260001455',
|
||||
'depositor' => 'NHN KCP',
|
||||
'va_date' => '20260516235959',
|
||||
'bankcode' => 'BK11',
|
||||
'app_time' => '20260513174624',
|
||||
'va_date' => '20260516235959',
|
||||
'bankcode' => 'BK11',
|
||||
'app_time' => '20260513174624',
|
||||
]);
|
||||
|
||||
$response = $this->post(
|
||||
'/plugins/sirsoft-pay_nhnkcp/payment/callback',
|
||||
$this->makeCallbackParams($order->order_number, 30000, [
|
||||
'tno' => $tno,
|
||||
'tno' => $tno,
|
||||
'use_pay_method' => 'VCNT',
|
||||
])
|
||||
);
|
||||
@@ -1119,10 +1246,20 @@ class PaymentCallbackControllerTest extends PluginTestCase
|
||||
$order->refresh();
|
||||
$this->assertNotEquals(OrderStatusEnum::PAYMENT_COMPLETE, $order->order_status);
|
||||
|
||||
// "완료되지 않았다" 만으로는 부족하다 — 이 콜백은 비인증 브라우저 경로이므로,
|
||||
// 발급 실패를 근거로 주문을 취소하면 주문번호만 아는 제3자가 남의 주문을
|
||||
// 취소시킬 수 있다 (KVE-2026-2018 동일 계열). 취소되지 않았음까지 단언한다.
|
||||
$this->assertNotEquals(
|
||||
OrderStatusEnum::CANCELLED,
|
||||
$order->order_status,
|
||||
'승인 증거 없는 가상계좌 콜백이 주문을 취소시켰습니다.'
|
||||
);
|
||||
|
||||
$payment = $order->payment;
|
||||
$payment->refresh();
|
||||
$this->assertNull($payment->vbank_name);
|
||||
$this->assertNull($payment->vbank_number);
|
||||
$this->assertNotEquals(PaymentStatusEnum::FAILED, $payment->payment_status);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -1148,10 +1285,20 @@ class PaymentCallbackControllerTest extends PluginTestCase
|
||||
$order->refresh();
|
||||
$this->assertNotEquals(OrderStatusEnum::PAYMENT_COMPLETE, $order->order_status);
|
||||
|
||||
// "완료되지 않았다" 만으로는 부족하다 — 이 콜백은 비인증 브라우저 경로이므로,
|
||||
// 발급 실패를 근거로 주문을 취소하면 주문번호만 아는 제3자가 남의 주문을
|
||||
// 취소시킬 수 있다 (KVE-2026-2018 동일 계열). 취소되지 않았음까지 단언한다.
|
||||
$this->assertNotEquals(
|
||||
OrderStatusEnum::CANCELLED,
|
||||
$order->order_status,
|
||||
'승인 증거 없는 가상계좌 콜백이 주문을 취소시켰습니다.'
|
||||
);
|
||||
|
||||
$payment = $order->payment;
|
||||
$payment->refresh();
|
||||
$this->assertNull($payment->vbank_name);
|
||||
$this->assertNull($payment->vbank_number);
|
||||
$this->assertNotEquals(PaymentStatusEnum::FAILED, $payment->payment_status);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -1173,10 +1320,10 @@ class PaymentCallbackControllerTest extends PluginTestCase
|
||||
$response = $this->post(
|
||||
'/plugins/sirsoft-pay_nhnkcp/payment/callback',
|
||||
[
|
||||
'res_cd' => '0000',
|
||||
'ordr_idxx' => $order->order_number,
|
||||
'good_mny' => 30000,
|
||||
'tno' => 'KCP_VBANK_MOBILE_FAIL',
|
||||
'res_cd' => '0000',
|
||||
'ordr_idxx' => $order->order_number,
|
||||
'good_mny' => 30000,
|
||||
'tno' => 'KCP_VBANK_MOBILE_FAIL',
|
||||
'use_pay_method' => 'VCNT',
|
||||
// bankname / account / depositor / va_date 모두 누락 → 발급 정보 없음
|
||||
]
|
||||
@@ -1188,9 +1335,19 @@ class PaymentCallbackControllerTest extends PluginTestCase
|
||||
$order->refresh();
|
||||
$this->assertNotEquals(OrderStatusEnum::PAYMENT_COMPLETE, $order->order_status);
|
||||
|
||||
// "완료되지 않았다" 만으로는 부족하다 — 이 콜백은 비인증 브라우저 경로이므로,
|
||||
// 발급 실패를 근거로 주문을 취소하면 주문번호만 아는 제3자가 남의 주문을
|
||||
// 취소시킬 수 있다 (KVE-2026-2018 동일 계열). 취소되지 않았음까지 단언한다.
|
||||
$this->assertNotEquals(
|
||||
OrderStatusEnum::CANCELLED,
|
||||
$order->order_status,
|
||||
'승인 증거 없는 가상계좌 콜백이 주문을 취소시켰습니다.'
|
||||
);
|
||||
|
||||
$payment = $order->payment;
|
||||
$payment->refresh();
|
||||
$this->assertNull($payment->vbank_name);
|
||||
$this->assertNull($payment->vbank_number);
|
||||
$this->assertNotEquals(PaymentStatusEnum::FAILED, $payment->payment_status);
|
||||
}
|
||||
}
|
||||
@@ -470,10 +470,17 @@ class NhnKcpApiServiceTest extends PluginTestCase
|
||||
$reflection->getConstant('LOG_DISABLED_PATH'),
|
||||
'gnuboard5 의 검증된 패턴(/home100/kcp) 과 일치해야 함',
|
||||
);
|
||||
$this->assertFalse(
|
||||
is_dir($reflection->getConstant('LOG_DISABLED_PATH')),
|
||||
'경로가 실제 시스템에 존재하지 않아야 (로그 작성 silent skip 보장)',
|
||||
);
|
||||
// 존재 여부는 **배포 OS(리눅스)** 기준 계약이다. KCP CLI 는 리눅스 바이너리이고
|
||||
// (`test_cli_args_include_disabled_log_path_constant` 도 같은 이유로 Windows 를 제외한다),
|
||||
// Windows 는 선행 `/` 를 현재 드라이브 기준으로 해석해 `C:\home100\kcp` 를 본다.
|
||||
// 그래서 개발자 PC 에 우연히 그 폴더가 있으면 배포 계약과 무관하게 붉은불이 뜬다.
|
||||
// 계약 자체는 그대로 두고, 그 계약이 성립하는 OS 에서만 파일시스템을 확인한다.
|
||||
if (DIRECTORY_SEPARATOR === '/') {
|
||||
$this->assertFalse(
|
||||
is_dir($reflection->getConstant('LOG_DISABLED_PATH')),
|
||||
'경로가 실제 시스템에 존재하지 않아야 (로그 작성 silent skip 보장)',
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
public function test_log_level_is_minimal_to_prevent_pii_leak(): void
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
# audit:allow test-scenario-coverage reason: Phase 2 SSoT — 본 매니페스트는 NHN KCP 콜백 보안 매트릭스의 명세 문서. CLI sanitization 단위 테스트가 핵심 경로를 커버하며, replay/net-cancel 의 cross product 전체 자동 검증은 Phase 3 (침투 PoC) 에서 처리.
|
||||
|
||||
feature: 콜백 보안 방어 (replay attack / CLI command injection / post-approve net cancel)
|
||||
feature: 콜백 보안 방어 (replay attack / CLI command injection / post-approve net cancel / 비인증 브라우저 콜백의 주문 변조)
|
||||
|
||||
description: |
|
||||
NHN KCP 결제 콜백 처리 경로의 3가지 핵심 보안 위협에 대한 방어 매트릭스.
|
||||
@@ -18,8 +18,9 @@ description: |
|
||||
|
||||
axes:
|
||||
context: [paymentCallback_card, paymentCallback_vbank, mobileApproval]
|
||||
threat: [replay, cli_injection, post_approve_failure]
|
||||
callback_state: [first_arrival, second_arrival_same_tno, cli_arg_normal, cli_arg_unsafe, domain_succeeds, domain_fails]
|
||||
threat: [replay, cli_injection, post_approve_failure, forged_browser_callback]
|
||||
callback_state: [first_arrival, second_arrival_same_tno, cli_arg_normal, cli_arg_unsafe, domain_succeeds, domain_fails, approval_not_yet_attempted, approval_failed, approval_succeeded]
|
||||
caller: [pg_server_verified, unauthenticated_browser, ownership_verified_buyer]
|
||||
|
||||
exclusions:
|
||||
- { threat: replay, callback_state: cli_arg_normal, reason: "replay 는 CLI 단계 이전 분기" }
|
||||
@@ -36,6 +37,26 @@ exclusions:
|
||||
- { threat: post_approve_failure, callback_state: cli_arg_normal, reason: "post-approve 실패는 CLI 와 무관" }
|
||||
- { threat: post_approve_failure, callback_state: cli_arg_unsafe, reason: "post-approve 실패는 CLI 와 무관" }
|
||||
- { threat: post_approve_failure, context: paymentCallback_vbank, reason: "vbank 통보는 PG 측 비동기 입금 — post-approve 단계 없음" }
|
||||
- { threat: forged_browser_callback, callback_state: first_arrival, reason: "위조 콜백은 도착 차수가 아니라 승인 성립 여부로 갈린다" }
|
||||
- { threat: forged_browser_callback, callback_state: second_arrival_same_tno, reason: "동일" }
|
||||
- { threat: forged_browser_callback, callback_state: cli_arg_normal, reason: "위조 콜백 축은 CLI 인수 정제 단계가 아니다" }
|
||||
- { threat: forged_browser_callback, callback_state: cli_arg_unsafe, reason: "동일" }
|
||||
- { threat: forged_browser_callback, callback_state: domain_succeeds, reason: "도메인 처리 이전에 승인 성립 여부로 판정한다" }
|
||||
- { threat: forged_browser_callback, callback_state: domain_fails, reason: "동일" }
|
||||
- { threat: replay, callback_state: approval_not_yet_attempted, reason: "승인 성립 축은 위조 콜백 전용 — replay 는 도착 차수 분기" }
|
||||
- { threat: replay, callback_state: approval_failed, reason: "동일" }
|
||||
- { threat: replay, callback_state: approval_succeeded, reason: "동일" }
|
||||
- { threat: cli_injection, callback_state: approval_not_yet_attempted, reason: "CLI 인젝션은 인수 정제 단계 분기" }
|
||||
- { threat: cli_injection, callback_state: approval_failed, reason: "동일" }
|
||||
- { threat: cli_injection, callback_state: approval_succeeded, reason: "동일" }
|
||||
- { threat: post_approve_failure, callback_state: approval_not_yet_attempted, reason: "정의상 승인 이후 분기" }
|
||||
- { threat: post_approve_failure, callback_state: approval_failed, reason: "동일" }
|
||||
- { threat: post_approve_failure, callback_state: approval_succeeded, reason: "post-approve 실패는 domain_fails 로 표현한다" }
|
||||
- { caller: ownership_verified_buyer, threat: replay, reason: "close-report 는 결제창 콜백이 아니라 별도 소유권 검증 엔드포인트" }
|
||||
- { caller: ownership_verified_buyer, threat: cli_injection, reason: "동일 — CLI 를 호출하지 않는다" }
|
||||
- { caller: ownership_verified_buyer, threat: post_approve_failure, reason: "동일 — 승인 단계가 없다" }
|
||||
- { caller: pg_server_verified, threat: forged_browser_callback, reason: "위조 축의 전제가 비인증 브라우저 입력이다" }
|
||||
- { caller: unauthenticated_browser, threat: cli_injection, reason: "CLI 인수는 상점 설정·주문 저장값에서 오고 브라우저 입력이 아니다" }
|
||||
|
||||
effects:
|
||||
# Replay defense — PreventsReplayCallback trait
|
||||
@@ -62,15 +83,41 @@ effects:
|
||||
- cli_exec_uses_escapeshellarg
|
||||
- cli_no_shell_executed_on_unsafe_input
|
||||
|
||||
# 비인증 브라우저 콜백의 주문 변조 차단 (KVE-2026-2018 + 형제)
|
||||
- unauthenticated_callback_cannot_cancel_another_users_order
|
||||
- browser_result_code_alone_never_transitions_order_state
|
||||
- pre_approval_failure_sink_does_not_call_fail_payment
|
||||
- pre_approval_amount_mismatch_does_not_mutate_the_order
|
||||
- post_approval_failure_still_records_failure_with_tno
|
||||
- payment_method_branch_is_decided_by_stored_order_value_only
|
||||
- request_pay_method_cannot_route_a_card_order_into_vbank_branch
|
||||
- forged_vbank_callback_cannot_cancel_a_card_order
|
||||
- forged_vbank_callback_cannot_write_an_account_number_to_the_order
|
||||
- mobile_vbank_issuance_failure_does_not_mutate_the_order
|
||||
- pc_vbank_cli_exception_does_not_mutate_the_order
|
||||
- vbank_save_failure_mutates_only_on_pc_server_confirmed_issuance
|
||||
- cancelled_order_is_restored_only_after_approval_or_issuance_is_confirmed
|
||||
- legitimate_failure_is_recorded_by_ownership_verified_close_report
|
||||
- close_report_rejects_buyer_mismatch
|
||||
- normal_approval_still_completes_the_order
|
||||
|
||||
# Post-approve net cancel
|
||||
- post_approve_failure_triggers_auto_cancel
|
||||
- net_cancel_sends_pg_cancel_api_call
|
||||
- net_cancel_passes_approved_tno
|
||||
- net_cancel_passes_full_amount
|
||||
|
||||
test_files: []
|
||||
test_files:
|
||||
- plugins/_bundled/sirsoft-pay_nhnkcp/tests/Feature/Controllers/PaymentCallbackControllerTest.php
|
||||
|
||||
manual_verification:
|
||||
- description: "위조 콜백 PoC — 남의 주문번호로 결제 실패 유도"
|
||||
steps:
|
||||
- "피해자 계정으로 결제대기 주문 1건 생성 (pending_order / ready)"
|
||||
- "로그아웃 상태에서 authCallback 에 피해 ordr_idxx + res_cd=0000 + 위조 암호문 POST"
|
||||
- "302 리다이렉트만 발생하고 주문 상태·결제 상태가 불변인지 재조회로 확인"
|
||||
- "요청에 use_pay_method=VCNT 를 섞어도 카드 주문이 가상계좌 분기로 흐르지 않는지 확인"
|
||||
- "위조 bankname/account 가 주문에 기록되지 않는지 확인"
|
||||
- description: "Replay PoC — paymentCallback 두 번 전송"
|
||||
steps:
|
||||
- "정상 카드 콜백 1차 전송 → 200 OK, payment_status=paid"
|
||||
|
||||
@@ -128,6 +128,8 @@ API 와 동기화하는 역할만 합니다. 등록은 훅 기반입니다
|
||||
| 가상계좌 입금통보(`vbank-notify`)에 IP 화이트리스트 미부착 | `VbankNotifyIpWhitelist` 미들웨어 유지 | 통보 엔드포인트는 나이스페이먼츠 서버만 호출해야 하며, 화이트리스트가 없으면 제3자가 위조 입금통보를 보내 결제 상태를 조작할 수 있다 |
|
||||
| 부분취소인데 가상계좌 입금 완료 건을 일반 취소 API로 처리 | 환불 계좌 정보가 필요한 가상계좌 건은 별도 어드민 환불 계좌 API 경로로 처리 | 가상계좌는 카드와 달리 PG가 자동으로 환불할 계좌를 모르므로 일반 취소 API를 호출하면 실패하거나 환불이 누락된다 |
|
||||
| 라이브 가맹점 키를 로그·에러 메시지에 노출 | 운영 키는 항상 마스킹하거나 로그 대상에서 제외 | 노출되면 제3자가 결제 요청을 위조할 수 있다 |
|
||||
| 콜백이 넘겨준 `NextAppURL`/`NetCancelURL` 의 도메인을 원문 host 로 대조 (`str_ends_with` 등) | `OutboundUrlValidator::normalizeHost()` 로 정규화한 뒤 대조 (사본 금지 — 코어가 SSoT) | UTS#46 정규화에서 전각 문자가 ASCII 구분자로 바뀐다. `evil.example/.nicepay.co.kr`(U+FF0F)은 접미사 검사를 통과하지만 실제 연결 host 는 `evil.example` 이 되어, 인증 토큰과 MID 가 실린 POST 가 외부로 나간다 |
|
||||
| 그 URL 에 userinfo(`user@host`)가 있어도 통과 | userinfo 존재만으로 거부 | `@` 앞부분이 신뢰 도메인처럼 보이게 위장할 수 있다 |
|
||||
<!-- @intent END -->
|
||||
|
||||
## 7. 테스트 실행
|
||||
|
||||
@@ -6,6 +6,10 @@
|
||||
|
||||
## [1.0.3] - 2026-08-31
|
||||
|
||||
### Security
|
||||
|
||||
- 결제창이 넘겨준 승인 요청 주소에 마침표·빗금처럼 보이는 특수문자를 섞으면, 나이스페이먼츠 도메인 검사를 통과하면서 실제로는 다른 서버로 승인 요청이 나갈 수 있던 문제를 수정했습니다. 그 요청에는 인증 토큰과 상점 아이디가 실려 있어 외부로 유출될 수 있었습니다. 이제 검사와 실제 연결이 주소를 같은 방식으로 해석하며, 로그인 정보가 포함된 주소도 거부합니다. 정상적인 나이스페이먼츠 주소는 그대로 사용됩니다.
|
||||
|
||||
### Added
|
||||
|
||||
- 개발자와 AI 에이전트를 위한 문서를 추가했습니다. 확장 폴더의 `AGENTS.md`(설계 의도·확장점·수정 시 확인할 것)와 `README.md`(도입·운영 안내), `docs/`(상세 문서)로 구성됩니다.
|
||||
|
||||
@@ -10,9 +10,9 @@
|
||||
| 훅 이름 | 유형 | 설명 | 발행 위치 |
|
||||
|---|---|---|---|
|
||||
| `sirsoft-pay_nicepayments.payment.after_authorize` | action | 나이스페이먼츠 서버 승인 완료 후 | `src/Controllers/PaymentCallbackController.php:257` |
|
||||
| `sirsoft-pay_nicepayments.payment.after_cancel` | action | 나이스페이먼츠 결제 취소 완료 후 | `src/Services/NicePaymentsApiService.php:308` |
|
||||
| `sirsoft-pay_nicepayments.payment.after_cancel` | action | 나이스페이먼츠 결제 취소 완료 후 | `src/Services/NicePaymentsApiService.php:312` |
|
||||
| `sirsoft-pay_nicepayments.payment.before_authorize` | action | 나이스페이먼츠 서버 승인 API 호출 전 | `src/Controllers/PaymentCallbackController.php:252` |
|
||||
| `sirsoft-pay_nicepayments.payment.before_cancel` | action | 나이스페이먼츠 결제 취소 API 호출 전 (본인인증 등 확장 지점) | `src/Services/NicePaymentsApiService.php:285` |
|
||||
| `sirsoft-pay_nicepayments.payment.before_cancel` | action | 나이스페이먼츠 결제 취소 API 호출 전 (본인인증 등 확장 지점) | `src/Services/NicePaymentsApiService.php:289` |
|
||||
| `sirsoft-pay_nicepayments.payment.refund_failed` | action | — | `src/Listeners/PaymentRefundListener.php:131` |
|
||||
<!-- @generated:hooks-published END -->
|
||||
|
||||
|
||||
@@ -6,6 +6,7 @@ namespace Plugins\Sirsoft\PayNicepayments\Services;
|
||||
|
||||
use App\Extension\HookManager;
|
||||
use App\Services\PluginSettingsService;
|
||||
use App\Support\OutboundUrlValidator;
|
||||
use Illuminate\Support\Facades\Http;
|
||||
use Illuminate\Support\Facades\Log;
|
||||
use Plugins\Sirsoft\PayNicepayments\Exceptions\NicePayApiException;
|
||||
@@ -52,7 +53,7 @@ class NicePaymentsApiService
|
||||
return '';
|
||||
}
|
||||
|
||||
return str_starts_with($suffix, 'SR') ? $suffix : 'SR' . $suffix;
|
||||
return str_starts_with($suffix, 'SR') ? $suffix : 'SR'.$suffix;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -116,6 +117,7 @@ class NicePaymentsApiService
|
||||
* @param string $buyerAddress 구매자 주소
|
||||
* @param string $registerName 등록자명
|
||||
* @return array NicePay 응답 (UTF-8 변환 + JSON 파싱)
|
||||
*
|
||||
* @throws \Exception API 호출 실패 또는 PG 오류 시
|
||||
*/
|
||||
public function registerEscrowDelivery(
|
||||
@@ -127,7 +129,7 @@ class NicePaymentsApiService
|
||||
): array {
|
||||
$reqType = '03';
|
||||
$ediDate = $this->computeEdiDate();
|
||||
$signData = bin2hex(hash('sha256', $tid . $this->mid . $reqType . $ediDate . $this->merchantKey, true));
|
||||
$signData = bin2hex(hash('sha256', $tid.$this->mid.$reqType.$ediDate.$this->merchantKey, true));
|
||||
|
||||
$response = Http::timeout(15)->asForm()->post(self::DELIVERY_REG_URL, [
|
||||
'MID' => $this->mid,
|
||||
@@ -144,7 +146,7 @@ class NicePaymentsApiService
|
||||
]);
|
||||
|
||||
if ($response->failed()) {
|
||||
throw new NicePayApiException('NicePayments delivery reg API error: HTTP ' . $response->status());
|
||||
throw new NicePayApiException('NicePayments delivery reg API error: HTTP '.$response->status());
|
||||
}
|
||||
|
||||
$result = $response->json() ?? [];
|
||||
@@ -172,7 +174,7 @@ class NicePaymentsApiService
|
||||
*/
|
||||
public function verifyCallbackSignature(string $authToken, string $mid, int $amt, string $signature): bool
|
||||
{
|
||||
$expected = bin2hex(hash('sha256', $authToken . $mid . (string) $amt . $this->merchantKey, true));
|
||||
$expected = bin2hex(hash('sha256', $authToken.$mid.(string) $amt.$this->merchantKey, true));
|
||||
|
||||
return hash_equals($expected, $signature);
|
||||
}
|
||||
@@ -187,7 +189,7 @@ class NicePaymentsApiService
|
||||
*/
|
||||
public function verifyVbankNotifySignature(string $tid, int $amt, string $signature): bool
|
||||
{
|
||||
$expected = bin2hex(hash('sha256', $tid . $this->mid . (string) $amt . $this->merchantKey, true));
|
||||
$expected = bin2hex(hash('sha256', $tid.$this->mid.(string) $amt.$this->merchantKey, true));
|
||||
|
||||
return hash_equals($expected, $signature);
|
||||
}
|
||||
@@ -195,22 +197,23 @@ class NicePaymentsApiService
|
||||
/**
|
||||
* 서버 승인 API 호출 (2단계 인증)
|
||||
*
|
||||
* @param string $nextAppUrl 나이스페이먼츠가 전달한 승인 URL
|
||||
* @param string $txTid 임시 거래번호
|
||||
* @param string $authToken 인증 토큰
|
||||
* @param int $amt 결제 금액
|
||||
* @param string $nextAppUrl 나이스페이먼츠가 전달한 승인 URL
|
||||
* @param string $txTid 임시 거래번호
|
||||
* @param string $authToken 인증 토큰
|
||||
* @param int $amt 결제 금액
|
||||
* @return array PG 응답 데이터
|
||||
*
|
||||
* @throws \Exception API 호출 실패 시
|
||||
*/
|
||||
public function authorizePayment(string $nextAppUrl, string $txTid, string $authToken, int $amt): array
|
||||
{
|
||||
// SSRF 방지: NextAppURL은 반드시 나이스페이먼츠 공식 도메인이어야 함
|
||||
if (! $this->isNicePayUrl($nextAppUrl)) {
|
||||
throw new NicePayApiException('Invalid NextAppURL host: ' . parse_url($nextAppUrl, PHP_URL_HOST));
|
||||
throw new NicePayApiException('Invalid NextAppURL host: '.parse_url($nextAppUrl, PHP_URL_HOST));
|
||||
}
|
||||
|
||||
$ediDate = $this->computeEdiDate();
|
||||
$signData = bin2hex(hash('sha256', $authToken . $this->mid . (string) $amt . $ediDate . $this->merchantKey, true));
|
||||
$signData = bin2hex(hash('sha256', $authToken.$this->mid.(string) $amt.$ediDate.$this->merchantKey, true));
|
||||
|
||||
$response = Http::timeout(15)->asForm()->post($nextAppUrl, [
|
||||
'TID' => $txTid,
|
||||
@@ -223,7 +226,7 @@ class NicePaymentsApiService
|
||||
]);
|
||||
|
||||
if ($response->failed()) {
|
||||
throw new NicePayApiException('NicePayments authorize API error: HTTP ' . $response->status());
|
||||
throw new NicePayApiException('NicePayments authorize API error: HTTP '.$response->status());
|
||||
}
|
||||
|
||||
return $response->json() ?? [];
|
||||
@@ -244,6 +247,7 @@ class NicePaymentsApiService
|
||||
* @param string|null $refundBankCd 환불 은행 코드
|
||||
* @param string|null $refundAcctNm 환불 계좌 예금주명
|
||||
* @return array PG 응답 데이터
|
||||
*
|
||||
* @throws \Exception API 호출 실패 시
|
||||
*/
|
||||
public function cancelPayment(
|
||||
@@ -257,7 +261,7 @@ class NicePaymentsApiService
|
||||
?string $refundAcctNm = null,
|
||||
): array {
|
||||
$ediDate = $this->computeEdiDate();
|
||||
$signData = bin2hex(hash('sha256', $this->mid . (string) $cancelAmt . $ediDate . $this->merchantKey, true));
|
||||
$signData = bin2hex(hash('sha256', $this->mid.(string) $cancelAmt.$ediDate.$this->merchantKey, true));
|
||||
|
||||
// NicePay 취소 API는 EUC-KR 인코딩 요구
|
||||
$cancelMsgEuc = mb_convert_encoding($cancelMsg, 'EUC-KR', 'UTF-8');
|
||||
@@ -287,7 +291,7 @@ class NicePaymentsApiService
|
||||
$response = Http::timeout(15)->asForm()->post(self::CANCEL_URL, $params);
|
||||
|
||||
if ($response->failed()) {
|
||||
throw new NicePayApiException('NicePayments cancel API error: HTTP ' . $response->status());
|
||||
throw new NicePayApiException('NicePayments cancel API error: HTTP '.$response->status());
|
||||
}
|
||||
|
||||
// 취소 API는 EUC-KR 응답을 반환하므로 UTF-8로 변환 후 JSON 파싱
|
||||
@@ -313,15 +317,16 @@ class NicePaymentsApiService
|
||||
/**
|
||||
* 단건 거래 조회 API 호출
|
||||
*
|
||||
* @param string $tid 조회할 거래번호
|
||||
* @param string $tid 조회할 거래번호
|
||||
* @return array PG 응답 데이터
|
||||
*
|
||||
* @throws \Exception API 호출 실패 시
|
||||
*/
|
||||
public function queryTransaction(string $tid): array
|
||||
{
|
||||
$ediDate = $this->computeEdiDate();
|
||||
// SignData: hex(sha256(TID + MID + EdiDate + MerchantKey)) — TID 먼저
|
||||
$signData = bin2hex(hash('sha256', $tid . $this->mid . $ediDate . $this->merchantKey, true));
|
||||
$signData = bin2hex(hash('sha256', $tid.$this->mid.$ediDate.$this->merchantKey, true));
|
||||
|
||||
$response = Http::timeout(15)->asForm()->post(self::QUERY_URL, [
|
||||
'TID' => $tid,
|
||||
@@ -333,7 +338,7 @@ class NicePaymentsApiService
|
||||
]);
|
||||
|
||||
if ($response->failed()) {
|
||||
throw new NicePayApiException('NicePayments query API error: HTTP ' . $response->status());
|
||||
throw new NicePayApiException('NicePayments query API error: HTTP '.$response->status());
|
||||
}
|
||||
|
||||
return $response->json() ?? [];
|
||||
@@ -342,10 +347,10 @@ class NicePaymentsApiService
|
||||
/**
|
||||
* 망취소 요청 (서버 승인 중 예외 발생 시 결제 원천 취소)
|
||||
*
|
||||
* @param string $netCancelUrl 나이스페이먼츠가 전달한 망취소 URL
|
||||
* @param string $txTid 임시 거래번호 (TxTid)
|
||||
* @param string $authToken 인증 토큰
|
||||
* @param int $amt 결제 금액
|
||||
* @param string $netCancelUrl 나이스페이먼츠가 전달한 망취소 URL
|
||||
* @param string $txTid 임시 거래번호 (TxTid)
|
||||
* @param string $authToken 인증 토큰
|
||||
* @param int $amt 결제 금액
|
||||
*/
|
||||
public function sendNetCancel(string $netCancelUrl, string $txTid, string $authToken, int $amt): void
|
||||
{
|
||||
@@ -357,7 +362,7 @@ class NicePaymentsApiService
|
||||
|
||||
try {
|
||||
$ediDate = $this->computeEdiDate();
|
||||
$signData = bin2hex(hash('sha256', $authToken . $this->mid . (string) $amt . $ediDate . $this->merchantKey, true));
|
||||
$signData = bin2hex(hash('sha256', $authToken.$this->mid.(string) $amt.$ediDate.$this->merchantKey, true));
|
||||
|
||||
Http::timeout(10)->asForm()->post($netCancelUrl, [
|
||||
'TID' => $txTid,
|
||||
@@ -399,7 +404,7 @@ class NicePaymentsApiService
|
||||
*/
|
||||
public function generateSignData(string $ediDate, int $amt): string
|
||||
{
|
||||
return bin2hex(hash('sha256', $ediDate . $this->mid . (string) $amt . $this->merchantKey, true));
|
||||
return bin2hex(hash('sha256', $ediDate.$this->mid.(string) $amt.$this->merchantKey, true));
|
||||
}
|
||||
|
||||
private function computeEdiDate(): string
|
||||
@@ -407,13 +412,37 @@ class NicePaymentsApiService
|
||||
return $this->generateEdiDate();
|
||||
}
|
||||
|
||||
/** NextAppURL / NetCancelURL이 나이스페이먼츠 공식 도메인인지 검증 (SSRF 방지) */
|
||||
/**
|
||||
* NextAppURL / NetCancelURL이 나이스페이먼츠 공식 도메인인지 검증 (SSRF 방지)
|
||||
*
|
||||
* 이 URL 은 결제창이 콜백으로 넘겨준 값이라 공격자가 지정할 수 있고, 서버는 여기에
|
||||
* 인증 토큰·MID 를 실어 POST 한다. 접미사 대조를 원문 host 로 수행하면 연결 계층의
|
||||
* 해석과 어긋난다 — `evil.example/.nicepay.co.kr`(U+FF0F)은 접미사 검사를 통과하지만
|
||||
* UTS#46 정규화 후에는 host 가 `evil.example` 이 된다. 코어 검증기의 정규화를 그대로
|
||||
* 재사용해(사본 금지) 판정 기준을 연결 계층과 일치시킨다.
|
||||
*
|
||||
* @param string $url 검증 대상 URL (결제 콜백이 제공)
|
||||
* @return bool 나이스페이먼츠 공식 도메인이면 true
|
||||
*/
|
||||
private function isNicePayUrl(string $url): bool
|
||||
{
|
||||
$parsed = parse_url($url);
|
||||
$scheme = $parsed['scheme'] ?? '';
|
||||
$host = $parsed['host'] ?? '';
|
||||
|
||||
return $scheme === 'https' && str_ends_with($host, '.nicepay.co.kr');
|
||||
if (($parsed['scheme'] ?? '') !== 'https') {
|
||||
return false;
|
||||
}
|
||||
|
||||
// userinfo(`user:pass@host`)는 host 위조의 핵심 벡터 — 존재만으로 거부
|
||||
if (isset($parsed['user']) || isset($parsed['pass'])) {
|
||||
return false;
|
||||
}
|
||||
|
||||
$host = OutboundUrlValidator::normalizeHost((string) ($parsed['host'] ?? ''));
|
||||
|
||||
if ($host === null) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return $host === 'nicepay.co.kr' || str_ends_with($host, '.nicepay.co.kr');
|
||||
}
|
||||
}
|
||||
+86
-2
@@ -4,6 +4,8 @@ namespace Plugins\Sirsoft\PayNicepayments\Tests\Unit\Services;
|
||||
|
||||
use App\Services\PluginSettingsService;
|
||||
use Illuminate\Support\Facades\Http;
|
||||
use PHPUnit\Framework\Attributes\DataProvider;
|
||||
use Plugins\Sirsoft\PayNicepayments\Exceptions\NicePayApiException;
|
||||
use Plugins\Sirsoft\PayNicepayments\Services\NicePaymentsApiService;
|
||||
use Plugins\Sirsoft\PayNicepayments\Tests\PluginTestCase;
|
||||
|
||||
@@ -66,7 +68,7 @@ class NicePaymentsApiServiceTest extends PluginTestCase
|
||||
$authToken = 'AUTH_TOKEN_TEST';
|
||||
$mid = self::TEST_MID;
|
||||
$amt = 50000;
|
||||
$signature = bin2hex(hash('sha256', $authToken . $mid . (string) $amt . self::TEST_MERCHANT_KEY, true));
|
||||
$signature = bin2hex(hash('sha256', $authToken.$mid.(string) $amt.self::TEST_MERCHANT_KEY, true));
|
||||
|
||||
$this->assertTrue($service->verifyCallbackSignature($authToken, $mid, $amt, $signature));
|
||||
}
|
||||
@@ -84,7 +86,7 @@ class NicePaymentsApiServiceTest extends PluginTestCase
|
||||
|
||||
$authToken = 'AUTH_TOKEN_TEST';
|
||||
$amt = 50000;
|
||||
$signature = bin2hex(hash('sha256', $authToken . self::TEST_MID . (string) $amt . self::TEST_MERCHANT_KEY, true));
|
||||
$signature = bin2hex(hash('sha256', $authToken.self::TEST_MID.(string) $amt.self::TEST_MERCHANT_KEY, true));
|
||||
|
||||
// 금액을 변조하여 서명 검증
|
||||
$this->assertFalse($service->verifyCallbackSignature($authToken, self::TEST_MID, 99999, $signature));
|
||||
@@ -250,4 +252,86 @@ class NicePaymentsApiServiceTest extends PluginTestCase
|
||||
|
||||
$service->queryTransaction('TID_TEST');
|
||||
}
|
||||
|
||||
/**
|
||||
* 결제창이 넘겨준 콜백 URL 은 공격자가 지정할 수 있고, 서버는 여기에 인증 토큰과
|
||||
* MID 를 실어 POST 한다. 도메인 대조가 연결 계층의 host 해석과 어긋나면 그 자격증명이
|
||||
* 외부로 나가고 내부망 호출까지 가능해진다.
|
||||
*
|
||||
* @param string $url 차단되어야 하는 NextAppURL
|
||||
* @param string $reason 차단 사유 (실패 메시지용)
|
||||
*/
|
||||
#[DataProvider('forgedCallbackUrlProvider')]
|
||||
public function test_authorize_payment_rejects_urls_that_only_look_like_nicepay(string $url, string $reason): void
|
||||
{
|
||||
$service = $this->makeService();
|
||||
|
||||
Http::fake(['*' => Http::response(['ResultCode' => '3001'], 200)]);
|
||||
|
||||
try {
|
||||
$service->authorizePayment($url, 'TID', 'TOKEN', 50000);
|
||||
$this->fail("차단되어야 하는 NextAppURL 이 통과함 ({$reason}): {$url}");
|
||||
} catch (NicePayApiException) {
|
||||
// 기대 동작
|
||||
}
|
||||
|
||||
Http::assertNothingSent();
|
||||
}
|
||||
|
||||
/**
|
||||
* 정규화 후 나이스페이먼츠 공식 도메인인 URL 은 그대로 통과한다.
|
||||
*
|
||||
* @param string $url 허용되어야 하는 NextAppURL
|
||||
*/
|
||||
#[DataProvider('legitimateCallbackUrlProvider')]
|
||||
public function test_authorize_payment_still_accepts_official_nicepay_urls(string $url): void
|
||||
{
|
||||
$service = $this->makeService();
|
||||
|
||||
Http::fake(['*' => Http::response(['ResultCode' => '3001', 'TID' => 'T'], 200)]);
|
||||
|
||||
$result = $service->authorizePayment($url, 'TID', 'TOKEN', 50000);
|
||||
|
||||
$this->assertSame('3001', $result['ResultCode']);
|
||||
}
|
||||
|
||||
/**
|
||||
* 공식 도메인으로 위장한 콜백 URL 목록.
|
||||
*
|
||||
* @return array<string, array{string, string}>
|
||||
*/
|
||||
public static function forgedCallbackUrlProvider(): array
|
||||
{
|
||||
return [
|
||||
// U+FF0F 는 UTS#46 에서 ASCII `/` 로 매핑된다 — 접미사 대조는 통과하지만
|
||||
// 연결 계층은 `evil.example` 을 host 로 읽는다.
|
||||
'전각 슬래시로 감춘 외부 호스트' => ["https://evil.example\u{FF0F}.nicepay.co.kr/v1/authorize", '정규화 시 host 는 evil.example'],
|
||||
'전각 슬래시로 감춘 루프백' => ["https://127.0.0.1\u{FF0F}.nicepay.co.kr/v1/authorize", '정규화 시 host 는 127.0.0.1'],
|
||||
'전각 슬래시로 감춘 메타데이터' => ["https://169.254.169.254\u{FF0F}.nicepay.co.kr/latest/meta-data/", '정규화 시 host 는 169.254.169.254'],
|
||||
'userinfo 위장' => ['https://pay.nicepay.co.kr@evil.example/v1/authorize', 'userinfo(@) 뒤가 실제 host'],
|
||||
'접미사 확장 도메인' => ['https://pay.nicepay.co.kr.evil.example/v1/authorize', '화이트리스트가 접두사일 뿐'],
|
||||
'http scheme' => ['http://pay.nicepay.co.kr/v1/authorize', 'https 아님'],
|
||||
'완전 무관 도메인' => ['https://evil.example/v1/authorize', '공식 도메인 아님'],
|
||||
'하이픈 접미사' => ['https://pay.nicepay.co.kr-evil.example/v1/authorize', '접미사 확장'],
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* 정상 통과해야 하는 공식 콜백 URL 목록.
|
||||
*
|
||||
* @return array<string, array{string}>
|
||||
*/
|
||||
public static function legitimateCallbackUrlProvider(): array
|
||||
{
|
||||
return [
|
||||
'표준 인증 URL' => ['https://pay.nicepay.co.kr/v1/authorize'],
|
||||
'다른 서브도메인' => ['https://webapi.nicepay.co.kr/webapi/cancel_process.jsp'],
|
||||
'대소문자 혼용' => ['https://PAY.NicePay.CO.KR/v1/authorize'],
|
||||
'후행 점 표기' => ['https://pay.nicepay.co.kr./v1/authorize'],
|
||||
// U+00AD SOFT HYPHEN 은 UTS#46 에서 제거된다. 정규화 후 host 는
|
||||
// `evil.example.nicepay.co.kr` — 나이스페이먼츠가 소유한 서브도메인이므로
|
||||
// 검증기와 연결 계층의 판정이 일치한다(위장 통로가 아니다).
|
||||
'soft hyphen 제거 후 공식 서브도메인' => ["https://evil.example\u{00AD}.nicepay.co.kr/v1/authorize"],
|
||||
];
|
||||
}
|
||||
}
|
||||
+19
-3
@@ -1,6 +1,6 @@
|
||||
# audit:allow test-scenario-coverage reason: Phase 2 SSoT — 본 매니페스트는 나이스페이먼츠 콜백 보안 매트릭스의 명세 문서. AuthToken Cache 기반 dedupe 와 replay/net-cancel 의 cross product 전체 자동 검증은 Phase 3 (침투 PoC) 에서 처리.
|
||||
|
||||
feature: 콜백 보안 방어 (replay attack / authToken dedupe / post-approve net cancel)
|
||||
feature: 콜백 보안 방어 (replay attack / authToken dedupe / post-approve net cancel / 승인 URL 호스트 정규화)
|
||||
|
||||
description: |
|
||||
나이스페이먼츠 결제 콜백 처리 경로의 3가지 핵심 보안 위협에 대한 방어 매트릭스.
|
||||
@@ -18,7 +18,7 @@ description: |
|
||||
|
||||
axes:
|
||||
context: [authorize_card, authorize_vbank, naverpay_callback, kakaopay_callback]
|
||||
threat: [replay_db_long, replay_token_short, post_approve_failure]
|
||||
threat: [replay_db_long, replay_token_short, post_approve_failure, forged_approval_url_host]
|
||||
callback_state: [first_arrival, second_arrival_outside_60s, second_arrival_within_60s, domain_succeeds, domain_fails]
|
||||
|
||||
exclusions:
|
||||
@@ -33,6 +33,13 @@ exclusions:
|
||||
- { threat: post_approve_failure, callback_state: second_arrival_outside_60s, reason: "post-approve 실패는 도메인 결과 분기" }
|
||||
- { threat: post_approve_failure, callback_state: second_arrival_within_60s, reason: "post-approve 실패는 도메인 결과 분기" }
|
||||
- { threat: post_approve_failure, context: authorize_vbank, reason: "vbank 는 비동기 입금 — post-approve 단계 없음" }
|
||||
- { threat: forged_approval_url_host, callback_state: first_arrival, reason: "호스트 판정은 도착 차수와 무관하다" }
|
||||
- { threat: forged_approval_url_host, callback_state: second_arrival_outside_60s, reason: "동일" }
|
||||
- { threat: forged_approval_url_host, callback_state: second_arrival_within_60s, reason: "동일" }
|
||||
- { threat: forged_approval_url_host, callback_state: domain_succeeds, reason: "호스트가 거부되면 도메인 처리에 도달하지 못한다" }
|
||||
- { threat: forged_approval_url_host, callback_state: domain_fails, reason: "동일" }
|
||||
- { threat: forged_approval_url_host, context: naverpay_callback, reason: "간편결제 콜백은 승인 URL 을 결제창에서 받지 않는다" }
|
||||
- { threat: forged_approval_url_host, context: kakaopay_callback, reason: "동일" }
|
||||
|
||||
effects:
|
||||
# DB 영구 replay defense — PreventsReplayCallback trait
|
||||
@@ -51,6 +58,14 @@ effects:
|
||||
- auth_token_blocked_returns_4xx_or_idempotent
|
||||
- auth_token_logged_when_dedupe_hit
|
||||
|
||||
# 승인 URL 호스트 정규화 (KVE-2026-2010 형제 — 검증기 미경유 독립 경로)
|
||||
- approval_url_host_check_reuses_core_normalize_host_not_a_copy
|
||||
- host_that_only_looks_like_nicepay_is_rejected
|
||||
- dot_equivalent_characters_cannot_disguise_the_host
|
||||
- url_carrying_userinfo_is_rejected
|
||||
- official_nicepay_hosts_are_still_accepted
|
||||
- rejected_url_never_receives_the_auth_token_or_merchant_id
|
||||
|
||||
# Post-approve net cancel
|
||||
- post_approve_failure_triggers_send_net_cancel
|
||||
- net_cancel_sends_pg_cancel_api_call
|
||||
@@ -58,7 +73,8 @@ effects:
|
||||
- net_cancel_passes_approved_tid
|
||||
- net_cancel_passes_full_amount
|
||||
|
||||
test_files: []
|
||||
test_files:
|
||||
- plugins/_bundled/sirsoft-pay_nicepayments/tests/Unit/Services/NicePaymentsApiServiceTest.php
|
||||
|
||||
manual_verification:
|
||||
- description: "Replay DB 영구 PoC — authorize_card 재전송"
|
||||
|
||||
@@ -137,6 +137,10 @@
|
||||
| 가상계좌 웹훅의 secret 대조를 생략하거나 항상 통과 | `payment_meta.toss_secret`과 웹훅 본문의 secret을 항상 대조 | 토스는 notify IP 목록·서명을 제공하지 않아 secret 대조가 유일한 위조 방지 수단이다 — 생략하면 제3자가 임의 주문에 대해 위조 입금통보를 보낼 수 있다 |
|
||||
| `core.plugin_settings.before_save` 리스너에 `sync: true` 없이 등록 | 저장을 막아야 하는 검증 훅은 반드시 `sync: true` | 기본값(비동기 큐)이면 `ValidationException`이 워커 안에서 죽고 저장이 그대로 진행되어 검증이 무력화된다 |
|
||||
| 라이브 시크릿 키를 로그·에러 메시지에 노출 | 운영 키는 항상 마스킹하거나 로그 대상에서 제외 | 노출되면 제3자가 서버측 API를 위조 호출할 수 있다 |
|
||||
| `fail()` 에서 `failPayment()` 등 주문 상태를 바꾸는 호출 | 로그 + `resolveFailUrl()` 만 | 이 엔드포인트는 인증도 서명도 없는 GET 이고 `orderId`·`code` 가 전부 쿼리스트링에서 온다. 실패 처리를 수행하면 링크 하나로 남의 결제대기 주문을 취소시킬 수 있다 |
|
||||
| 결제 실패를 `fail()` 이 기록해 줄 것으로 가정 | 구매자 정보를 대조하는 `POST /api/plugins/sirsoft-tosspayments/payment/close-report` 가 기록한다 | 결제 성립은 `success()` 의 서버 `confirmPayment`, 결제완료 후 취소는 secret 대조를 통과한 웹훅이 담당한다. 주문을 실패로 전이시키는 결제창 경로는 close-report 하나뿐이다 |
|
||||
| 결제창 컨텍스트(구매자 정보)를 `window` 전역에만 보관 | `rememberPendingClose()` 로 sessionStorage 에 남긴다 | 결제창은 전체 페이지 이동으로 열리고 돌아와 JS 컨텍스트가 소실된다. 전역에만 두면 실패 화면에서 보고할 근거가 사라져 결제 실패가 어디에도 기록되지 않는다 |
|
||||
| 실패 화면에서 보고가 닿지 못한 주문을 방치 | 이커머스 모듈의 만료 주문 자동 정리가 최종 안전망 | 브라우저를 바로 닫으면 보고가 나가지 않는다. 두 경로가 함께 있어야 선차감 마일리지가 무기한 묶이지 않는다 |
|
||||
<!-- @intent END -->
|
||||
|
||||
## 7. 테스트 실행
|
||||
@@ -144,8 +148,8 @@
|
||||
<!-- @generated:test-commands START — ext:docgen 이 갱신. 이 블록 안은 직접 수정하지 않는다 -->
|
||||
| 종류 | 개수 | 위치 |
|
||||
|---|---|---|
|
||||
| PHPUnit | 12개 | `plugins/_bundled/sirsoft-tosspayments/tests` |
|
||||
| Vitest | 5개 | `vitest.config.ts` |
|
||||
| PHPUnit | 13개 | `plugins/_bundled/sirsoft-tosspayments/tests` |
|
||||
| Vitest | 6개 | `vitest.config.ts` |
|
||||
| Playwright | 0개 | — |
|
||||
| 시나리오 매니페스트 | 3개 | `tests/scenarios` |
|
||||
|
||||
|
||||
@@ -6,8 +6,14 @@
|
||||
|
||||
## [1.0.3] - 2026-08-31
|
||||
|
||||
### Security
|
||||
|
||||
- 제3자가 남의 주문번호만 알면 주소 하나로 그 주문을 취소시킬 수 있던 문제를 수정했습니다. 결제 실패 안내 주소는 로그인도 서명 확인도 거치지 않고 주문번호와 실패 사유를 주소에 담아 받는 경로여서, 그 주소를 열기만 해도 해당 주문이 결제 실패로 처리되었습니다. 이제 이 주소는 주문 상태를 바꾸지 않고 결제 화면으로 되돌려 보내기만 합니다. 결제 성립은 종전처럼 서버 승인 확인으로, 결제완료 후 취소는 서명이 확인된 입금·취소 통보로 처리됩니다.
|
||||
|
||||
### Added
|
||||
|
||||
- 결제창을 닫거나 결제가 거절됐을 때 그 사실을 서버에 알리는 경로를 추가했습니다. 구매자 본인인지 확인한 뒤에만 주문을 실패로 기록하므로, 남의 주문번호를 아는 것만으로는 그 주문을 건드릴 수 없습니다. 다른 결제사 플러그인이 이미 제공하던 것과 같은 방식입니다.
|
||||
- 결제가 거절되어 실패 화면으로 돌아오면 그 사실이 자동으로 서버에 기록됩니다. 종전에는 결제 실패가 어디에도 남지 않았습니다.
|
||||
- 개발자와 AI 에이전트를 위한 문서를 추가했습니다. 확장 폴더의 `AGENTS.md`(설계 의도·확장점·수정 시 확인할 것)와 `README.md`(도입·운영 안내), `docs/`(상세 문서)로 구성됩니다.
|
||||
- 확장 문서에 「레이아웃 편집기 스펙」 항목을 추가했습니다. 이 확장이 레이아웃 편집기에 무엇을 선언했는지와, 화면 요소나 데이터를 추가할 때 편집기 쪽에서 함께 해야 할 일을 담습니다.
|
||||
- 문서의 제품 표기를 「그누보드7」로 통일했습니다.
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"$schema": "https://json-schema.org/draft/2020-12/schema",
|
||||
"identifier": "sirsoft-tosspayments",
|
||||
"version": "1.0.1",
|
||||
"version": "1.0.3",
|
||||
"components": {
|
||||
"basic": [],
|
||||
"composite": [],
|
||||
|
||||
@@ -1 +1 @@
|
||||
(function(){"use strict";function O(e){return new Promise((t,s)=>{if(document.querySelector(`script[src="${e}"]`)){t();return}const n=document.createElement("script");n.src=e,n.async=!0,n.onload=()=>t(),n.onerror=()=>s(new Error(`Failed to load script: ${e}`)),document.head.appendChild(n)})}function $(e,t){if(!e.order_sheet_mode||!t)return{method:"CARD",easyPay:null};const s=(e.enabled_methods??[]).find(n=>n.id===t);return s?{method:s.method,easyPay:s.easy_pay_provider}:{method:"CARD",easyPay:null}}function T(e){if(e==="on")return!0;if(e==="off")return!1}function q(e,t){const s={validHours:e.vbank?.valid_hours??24},n=e.vbank?.cash_receipt_type??"";n&&(s.cashReceipt={type:n});const o=T(e.use_escrow);return o!==void 0&&(s.useEscrow=o),s}function A(e,t,s){if(t.use_escrow==="off")return;const n=s.escrow_products??[];n.length>0&&(e.escrowProducts=n)}async function F(e,t){const s=e.params||{},{pgPaymentData:n}=s;if(!n){console.error("[sirsoft-tosspayments] pgPaymentData is required");return}const o=window.G7Core,r=s.paymentMethod??o?.state?.getLocal?.()?.paymentMethod;try{const a=await o.api.get("/modules/sirsoft-ecommerce/payments/client-config/tosspayments");if(!a.data){console.error("[sirsoft-tosspayments] Failed to fetch client config",a);return}const i=a.data;if(window.TossPayments||await O(i.sdk_url),window.TossPayments||await new Promise(m=>setTimeout(m,100)),!window.TossPayments){console.error("[sirsoft-tosspayments] TossPayments SDK not available");return}const te=window.TossPayments(i.client_key).payment({customerKey:n.customer_key??window.TossPayments.ANONYMOUS}),g=n.currency??"KRW",{method:d,easyPay:b}=$(i,r);if(g!=="KRW"&&(d!=="CARD"||b!==null)){console.warn("[sirsoft-tosspayments] non-KRW currency supports card only",{currency:g,method:d}),o?.state?.setLocal?.({paymentErrorMessage:o?.t?.("sirsoft-tosspayments.errors.non_krw_method")??"This payment method is available for KRW only.",isSubmittingOrder:!1}),o?.modal?.open?.("tosspayments_payment_error_modal");return}const D=window.location.origin,c={method:d,amount:{currency:g,value:n.amount},orderId:n.order_number,orderName:n.order_name,successUrl:D+i.callback_urls.success,failUrl:D+i.callback_urls.fail,customerEmail:n.customer_email??void 0,customerName:n.customer_name??void 0,customerMobilePhone:n.customer_phone??void 0};if(d==="CARD")c.card={flowMode:"DEFAULT",useCardPoint:!1,useAppCardOnly:!1},b&&(c.card.flowMode="DIRECT",c.card.easyPay=b);else if(d==="VIRTUAL_ACCOUNT")c.virtualAccount=q(i,n),A(c,i,n);else if(d==="TRANSFER"){const m=T(i.use_escrow);m!==void 0&&(c.transfer={useEscrow:m}),A(c,i,n)}await te.requestPayment(c)}catch(a){if(console.error("[sirsoft-tosspayments] requestPayment error",a),a?.code==="USER_CANCEL"){console.info("[sirsoft-tosspayments] Payment cancelled by user");try{await o.api.post(`/modules/sirsoft-ecommerce/orders/${n.order_number}/cancel-payment`,{cancel_code:a.code,cancel_message:a.message})}catch(x){console.warn("[sirsoft-tosspayments] Failed to record cancellation",x)}o?.state?.setLocal?.({isSubmittingOrder:!1}),o?.modal?.open?.("tosspayments_payment_cancel_modal");return}const i=a?.message??"Unknown error";o?.state?.setLocal?.({paymentErrorMessage:i,isSubmittingOrder:!1}),o?.modal?.open?.("tosspayments_payment_error_modal")}}const v={requestPayment:F},U="sirsoft-tosspayments",E="__tossAdminPaymentMethodBrandInjectorInstalled",S="__tossAdminPaymentMethodBrandSyncListenerAttached",B=/^\/admin\/ecommerce\/settings\/?$/,L='[data-toss-admin-payment-brand-mark="true"]',K=200,G=120,H=[{id:"toss_tosspay",labels:["토스페이 (토스페이먼츠)","토스페이 간편결제 — 토스페이먼츠를 통해 처리","TossPay (TossPayments)","TossPay easy payment — processed via TossPayments"],shortLabels:[],markLines:["T"],markClassName:"bg-blue-500 text-white"},{id:"toss_kakaopay",labels:["카카오페이 (토스페이먼츠)","카카오페이 간편결제 — 토스페이먼츠를 통해 처리","KakaoPay (TossPayments)","KakaoPay easy payment — processed via TossPayments"],shortLabels:[],markLines:["K"],markClassName:"bg-yellow-400 text-gray-950"},{id:"toss_naverpay",labels:["네이버페이 (토스페이먼츠)","네이버페이 간편결제 — 토스페이먼츠를 통해 처리","NaverPay (TossPayments)","NaverPay easy payment — processed via TossPayments"],shortLabels:[],markLines:["N"],markClassName:"bg-green-500 text-white"},{id:"toss_payco",labels:["페이코 (토스페이먼츠)","페이코 간편결제 — 토스페이먼츠를 통해 처리","PAYCO (TossPayments)","PAYCO easy payment — processed via TossPayments"],shortLabels:[],markLines:["P"],markClassName:"bg-red-500 text-white"},{id:"toss_samsungpay",labels:["삼성페이 (토스페이먼츠)","삼성페이 간편결제 — 토스페이먼츠를 통해 처리","Samsung Pay (TossPayments)","Samsung Pay easy payment — processed via TossPayments"],shortLabels:[],markLines:["S"],markClassName:"bg-blue-600 text-white"}];let M=null,u=null,y=!1;function Y(Line truncated
|
||||
(function(){"use strict";const q="sirsoft-tosspayments",y="g7:sirsoft-tosspayments:pendingClose",I="/api/plugins/sirsoft-tosspayments/payment/close-report";function f(){try{return window.sessionStorage??null}catch{return null}}function G(e){const t=f();if(t)try{t.setItem(y,JSON.stringify(e))}catch{}}function E(){const e=f();if(e)try{e.removeItem(y)}catch{}}function K(){const e=f();if(!e)return null;try{const t=e.getItem(y);if(!t)return null;const s=JSON.parse(t);return s&&typeof s.orderId=="string"&&s.orderId!==""?s:null}catch{return null}}async function B(e,t,s){const n={orderId:e.orderId,amount:Number(e.amount),buyer_email:e.buyer_email??"",buyer_phone:e.buyer_phone??"",code:t.slice(0,60),reason:s.trim().slice(0,160)},o=window.G7Core?.api;if(typeof o?.post=="function"){await o.post(I,n);return}await fetch(I,{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify(n),keepalive:!0})}async function j(){const e=K();if(!e)return;let t;try{t=new URLSearchParams(window.location.search)}catch{return}const s=t.get("orderId")??"";if(s!==""&&s!==e.orderId)return;if(/\/(complete|success)(\/|$|\?)/.test(window.location.pathname)){E();return}const n=t.get("error")??"",o=t.get("message")??"";if(!(n===""&&s==="")){E();try{await B(e,n,o!==""?o:n)}catch(r){console.warn(`[${q}] failed to report payment failure`,r)}}}function H(e){return new Promise((t,s)=>{if(document.querySelector(`script[src="${e}"]`)){t();return}const n=document.createElement("script");n.src=e,n.async=!0,n.onload=()=>t(),n.onerror=()=>s(new Error(`Failed to load script: ${e}`)),document.head.appendChild(n)})}function Y(e,t){if(!e.order_sheet_mode||!t)return{method:"CARD",easyPay:null};const s=(e.enabled_methods??[]).find(n=>n.id===t);return s?{method:s.method,easyPay:s.easy_pay_provider}:{method:"CARD",easyPay:null}}function A(e){if(e==="on")return!0;if(e==="off")return!1}function W(e,t){const s={validHours:e.vbank?.valid_hours??24},n=e.vbank?.cash_receipt_type??"";n&&(s.cashReceipt={type:n});const o=A(e.use_escrow);return o!==void 0&&(s.useEscrow=o),s}function C(e,t,s){if(t.use_escrow==="off")return;const n=s.escrow_products??[];n.length>0&&(e.escrowProducts=n)}async function J(e,t){const s=e.params||{},{pgPaymentData:n}=s;if(!n){console.error("[sirsoft-tosspayments] pgPaymentData is required");return}const o=window.G7Core,r=s.paymentMethod??o?.state?.getLocal?.()?.paymentMethod;try{const a=await o.api.get("/modules/sirsoft-ecommerce/payments/client-config/tosspayments");if(!a.data){console.error("[sirsoft-tosspayments] Failed to fetch client config",a);return}const i=a.data;if(window.TossPayments||await H(i.sdk_url),window.TossPayments||await new Promise(m=>setTimeout(m,100)),!window.TossPayments){console.error("[sirsoft-tosspayments] TossPayments SDK not available");return}const de=window.TossPayments(i.client_key).payment({customerKey:n.customer_key??window.TossPayments.ANONYMOUS}),T=n.currency??"KRW",{method:d,easyPay:S}=Y(i,r);if(T!=="KRW"&&(d!=="CARD"||S!==null)){console.warn("[sirsoft-tosspayments] non-KRW currency supports card only",{currency:T,method:d}),o?.state?.setLocal?.({paymentErrorMessage:o?.t?.("sirsoft-tosspayments.errors.non_krw_method")??"This payment method is available for KRW only.",isSubmittingOrder:!1}),o?.modal?.open?.("tosspayments_payment_error_modal");return}const F=window.location.origin,c={method:d,amount:{currency:T,value:n.amount},orderId:n.order_number,orderName:n.order_name,successUrl:F+i.callback_urls.success,failUrl:F+i.callback_urls.fail,customerEmail:n.customer_email??void 0,customerName:n.customer_name??void 0,customerMobilePhone:n.customer_phone??void 0};if(d==="CARD")c.card={flowMode:"DEFAULT",useCardPoint:!1,useAppCardOnly:!1},S&&(c.card.flowMode="DIRECT",c.card.easyPay=S);else if(d==="VIRTUAL_ACCOUNT")c.virtualAccount=W(i,n),C(c,i,n);else if(d==="TRANSFER"){const m=A(i.use_escrow);m!==void 0&&(c.transfer={useEscrow:m}),C(c,i,n)}G({orderId:n.order_number,amount:n.amount,buyer_email:n.customer_email??"",buyer_phone:n.customer_phone??""}),await de.requestPayment(c)}catch(a){if(console.error("[sirsoft-tosspayments] requestPayment error",a),a?.code==="USER_CANCEL"){console.info("[sirsoft-tosspayments] Payment cancelled by user");try{await o.api.post(`/modules/sirsoft-ecommerce/orders/${n.order_number}/cancel-payment`,{cancel_code:a.code,cancel_message:a.message})}catch(U){console.warn("[sirsoft-tosspayments] Failed to record cancellation",U)}o?.state?.setLocal?.({isSubmittingOrder:!1}),o?.modal?.open?.("tosspayments_payment_cancel_modal");return}const i=a?.message??"Unknown error";o?.state?.setLocal?.({paymentErrorMessage:i,isSubmittingOrder:!1}),o?.modal?.open?.("tosspayments_payment_error_modal")}}const v={requestPayment:J},V="sirsoft-tosspayments",L="__tossAdminPaymentMethodBrandInjectorInstalled",N="__tossAdminPaymentMethodBrandSyncListenerAttached",z=/^\/admin\/ecommerce\/settings\/?$/,R='[data-toss-admin-payment-brand-mark="true"]',Q=200,X=120,Z=[{id:"toss_tosLine truncated
|
||||
@@ -3,7 +3,7 @@
|
||||
> plugins/_bundled/sirsoft-tosspayments · 플러그인
|
||||
|
||||
<!-- @generated:stats START — ext:docgen 이 갱신. 이 블록 안은 직접 수정하지 않는다 -->
|
||||
**훅 수**: 4 · **구독 훅 수**: 9 · **라우트 수**: 4 · **모델 수**: 0 · **테이블 수**: 0 · **마이그레이션 수**: 0 · **레이아웃 수**: 1 · **핸들러 수**: 1
|
||||
**훅 수**: 4 · **구독 훅 수**: 9 · **라우트 수**: 5 · **모델 수**: 0 · **테이블 수**: 0 · **마이그레이션 수**: 0 · **레이아웃 수**: 1 · **핸들러 수**: 1
|
||||
<!-- @generated:stats END -->
|
||||
|
||||
## 문서 목차
|
||||
|
||||
@@ -71,10 +71,92 @@ Location: /shop/checkout?error=PAY_PROCESS_CANCELED&orderId=20260711-000001
|
||||
|
||||
주의사항:
|
||||
|
||||
- 이 엔드포인트는 **주문 상태를 변경하지 않는다**. 결제 취소 이력 기록은 프론트엔드가 별도 API(`/modules/sirsoft-ecommerce/orders/{orderNumber}/cancel-payment`)로 수행한다.
|
||||
- 이 엔드포인트는 **주문 상태를 변경하지 않는다**. 인증도 서명도 없는 GET 이고 `orderId`·`code` 가 전부 쿼리스트링에서 오므로, 실패 처리를 수행하면 링크 하나로 남의 결제대기 주문을 취소시킬 수 있다. 결제 실패 기록은 구매자 정보를 대조하는 `POST /api/plugins/sirsoft-tosspayments/payment/close-report` 가 담당하며, 실패 화면에 도착한 프론트엔드가 그 경로로 보고한다.
|
||||
- 결제창을 띄우기 전 단계에서 사용자가 취소한 경우(SDK `USER_CANCEL`)는 이 콜백을 타지 않고 프론트엔드에서 직접 처리된다.
|
||||
|
||||
|
||||
### POST /api/plugins/sirsoft-tosspayments/payment/close-report
|
||||
<!-- @generated:start:api.plugins.sirsoft-tosspayments.payment.close-report -->
|
||||
- **라우트명**: `api.plugins.sirsoft-tosspayments.payment.close-report`
|
||||
- **컨트롤러**: `Plugins\Sirsoft\Tosspayments\Controllers\PaymentCloseReportController@store`
|
||||
- **인증/권한**: 공개 (인증 불필요)
|
||||
|
||||
**요청 파라미터**
|
||||
|
||||
| 이름 | 위치 | 타입 | 필수 | 허용값 | 용도 |
|
||||
| --- | --- | --- | --- | --- | --- |
|
||||
| orderId | body | string | 예 | max 40 | 결제창을 닫거나 결제가 거절된 대상 주문의 주문번호. 서버가 이 값으로 주문을 조회해 결제 실패/취소 이력을 기록한다. |
|
||||
| amount | body | integer | 예 | min 1 | 결제 금액. 저장된 주문 청구액과 일치하는지 검증한다. |
|
||||
| buyer_email | body | string | 아니오 | max 255 | 구매자 이메일. 주문의 구매자 정보와 대조해 본인 요청인지 확인한다. |
|
||||
| buyer_phone | body | string | 아니오 | max 30 | 구매자 전화번호. 주문의 구매자 정보와 대조해 본인 요청인지 확인한다. |
|
||||
| code | body | string | 아니오 | max 60 | 토스 실패 코드. 값이 있으면 결제 거절로, 없으면 결제창 닫힘으로 기록한다. |
|
||||
| reason | body | string | 아니오 | max 160 | 사람이 읽을 실패 사유. 취소 이력에 남는다. |
|
||||
|
||||
**요청 예시**
|
||||
|
||||
```http
|
||||
POST /api/plugins/sirsoft-tosspayments/payment/close-report HTTP/1.1
|
||||
Host: api.example.com
|
||||
Accept: application/json
|
||||
Content-Type: application/json
|
||||
|
||||
{
|
||||
"orderId": "20260711-000001",
|
||||
"amount": 10000,
|
||||
"buyer_email": "buyer@example.com",
|
||||
"buyer_phone": "01012345678",
|
||||
"code": "REJECT_CARD_COMPANY",
|
||||
"reason": "카드사에서 승인을 거절했습니다."
|
||||
}
|
||||
```
|
||||
|
||||
**응답 필드** (`data` 내부)
|
||||
|
||||
| 필드 | 타입 | 실측 예시값 | 용도/설명 |
|
||||
| --- | --- | --- | --- |
|
||||
| status | string | `recorded` | 처리 결과. 기록했으면 `recorded`, 대상이 아니어서 넘어갔으면 `ignored`. |
|
||||
| reason | string | `order_not_payable` | `status` 가 `ignored` 일 때만 포함. 무시 사유(`order_not_payable` / `payment_already_paid`). |
|
||||
|
||||
**응답 예시**
|
||||
|
||||
```http
|
||||
HTTP/1.1 200
|
||||
```
|
||||
|
||||
```json
|
||||
{
|
||||
"success": true,
|
||||
"message": "성공적으로 처리되었습니다.",
|
||||
"data": {
|
||||
"status": "recorded"
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
**에러 응답**
|
||||
|
||||
| 상태코드 | 의미 | 발생 조건 |
|
||||
| --- | --- | --- |
|
||||
| 403 | Forbidden | 요청의 구매자 정보(`buyer_email` / `buyer_phone`)가 주문의 구매자와 일치하지 않는 경우 |
|
||||
| 404 | Not Found | `orderId` 에 해당하는 주문이 없는 경우 |
|
||||
| 422 | Unprocessable Entity | 요청 파라미터가 검증 규칙을 위반한 경우 (`error.errors` 에 필드별 메시지), 주문 통화가 청구 불가, 금액이 주문 청구액과 불일치 |
|
||||
| 429 | Too Many Requests | 동일 IP·`orderId` 조합에서 분당 20회를 초과해 요청한 경우 |
|
||||
|
||||
<!-- @generated:end -->
|
||||
|
||||
**설명**
|
||||
|
||||
**주문을 실패로 전이시키는 유일한 결제창 경로**입니다. 브라우저 리턴 콜백(`/payment/fail`)은 인증도 서명도 없고 주문번호가 쿼리스트링으로 오므로 주문 상태를 바꾸지 않습니다. 정당한 결제 실패는 구매자 이메일·전화 대조를 통과한 이 요청으로만 기록되며, 이는 다른 결제사 플러그인(KCP·KG이니시스·나이스페이)의 close-report 와 같은 계약입니다.
|
||||
|
||||
프론트엔드는 결제창을 열기 직전에 구매자 정보를 브라우저 세션에 남겨 두었다가, 결제가 거절되어 실패 화면으로 돌아왔을 때 그 정보로 이 엔드포인트를 호출합니다. 결제창은 전체 페이지 이동으로 열리고 돌아오므로 화면의 컨텍스트는 그 사이 소실되기 때문입니다.
|
||||
|
||||
`code` 유무로 기록이 갈립니다 — 값이 있으면 결제 거절(`failure_stage=payment_failed`), 없으면 결제창 닫힘(`failure_stage=window_closed`)으로 남아 운영자가 원인을 구분할 수 있습니다.
|
||||
|
||||
이미 결제가 성립한 주문(`payment_status=paid`)과 결제 가능 상태가 아닌 주문은 성공 응답에 `status: ignored` 로 무시합니다 — 결제 성공 콜백(`success` → `confirmPayment`)과 경쟁할 때 주문/옵션 상태가 어긋나는 것을 차단합니다.
|
||||
|
||||
보고가 끝내 도달하지 못한 주문(브라우저를 바로 닫는 등)은 이커머스 모듈의 만료 주문 자동 정리가 최종 안전망으로 처리합니다.
|
||||
|
||||
|
||||
### GET /plugins/sirsoft-tosspayments/payment/success
|
||||
<!-- @generated:start:web.plugins.sirsoft-tosspayments.payment.success -->
|
||||
- **라우트명**: `web.plugins.sirsoft-tosspayments.payment.success`
|
||||
|
||||
@@ -71,6 +71,7 @@ _등록하는 메뉴가 없습니다._
|
||||
<!-- @generated:routes START — ext:docgen 이 갱신. 이 블록 안은 직접 수정하지 않는다 -->
|
||||
| 종류 | 파일 | URL prefix |
|
||||
|---|---|---|
|
||||
| `api` | `src/routes/api.php` | `/api/plugins/sirsoft-tosspayments/...` |
|
||||
| `web` | `src/routes/web.php` | `/plugins/sirsoft-tosspayments/...` |
|
||||
|
||||
확장 라우트는 **활성 상태인 확장의 것만** 등록됩니다. 라우트 정의를 바꾸면 라우트 캐시 재생성이 필요합니다.
|
||||
|
||||
+157
@@ -0,0 +1,157 @@
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
import {
|
||||
forgetPendingClose,
|
||||
rememberPendingClose,
|
||||
reportPaymentFailureOnReturn,
|
||||
} from '../paymentCloseReport';
|
||||
|
||||
function windowRecord(): Record<string, any> {
|
||||
return window as unknown as Record<string, any>;
|
||||
}
|
||||
|
||||
/**
|
||||
* 화면 주소를 바꿔 결제 리턴 상황을 재현한다.
|
||||
*/
|
||||
function setLocation(pathname: string, search: string): void {
|
||||
Object.defineProperty(window, 'location', {
|
||||
configurable: true,
|
||||
value: { pathname, search, origin: 'https://shop.example' },
|
||||
});
|
||||
}
|
||||
|
||||
const CONTEXT = {
|
||||
orderId: 'ORD-TOSS-1001',
|
||||
amount: 10000,
|
||||
buyer_email: 'buyer@example.com',
|
||||
buyer_phone: '01012345678',
|
||||
};
|
||||
|
||||
describe('토스페이먼츠 결제 실패 보고', () => {
|
||||
beforeEach(() => {
|
||||
window.sessionStorage.clear();
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
delete windowRecord().G7Core;
|
||||
vi.restoreAllMocks();
|
||||
window.sessionStorage.clear();
|
||||
});
|
||||
|
||||
it('실패 화면으로 돌아오면 저장해 둔 구매자 정보로 보고한다', async () => {
|
||||
const apiPost = vi.fn().mockResolvedValue({ success: true });
|
||||
windowRecord().G7Core = { api: { post: apiPost } };
|
||||
|
||||
rememberPendingClose(CONTEXT);
|
||||
setLocation('/shop/checkout', '?error=PAY_PROCESS_CANCELED&message=cancelled&orderId=ORD-TOSS-1001');
|
||||
|
||||
await reportPaymentFailureOnReturn();
|
||||
|
||||
expect(apiPost).toHaveBeenCalledWith(
|
||||
'/api/plugins/sirsoft-tosspayments/payment/close-report',
|
||||
expect.objectContaining({
|
||||
orderId: 'ORD-TOSS-1001',
|
||||
amount: 10000,
|
||||
buyer_email: 'buyer@example.com',
|
||||
buyer_phone: '01012345678',
|
||||
code: 'PAY_PROCESS_CANCELED',
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
it('보고 후에는 저장분을 지워 중복 보고하지 않는다', async () => {
|
||||
const apiPost = vi.fn().mockResolvedValue({ success: true });
|
||||
windowRecord().G7Core = { api: { post: apiPost } };
|
||||
|
||||
rememberPendingClose(CONTEXT);
|
||||
setLocation('/shop/checkout', '?error=PAY_PROCESS_CANCELED&orderId=ORD-TOSS-1001');
|
||||
|
||||
await reportPaymentFailureOnReturn();
|
||||
await reportPaymentFailureOnReturn();
|
||||
|
||||
expect(apiPost).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it('저장해 둔 정보가 없으면 아무것도 보내지 않는다', async () => {
|
||||
const apiPost = vi.fn();
|
||||
windowRecord().G7Core = { api: { post: apiPost } };
|
||||
|
||||
setLocation('/shop/checkout', '?error=PAY_PROCESS_CANCELED&orderId=ORD-TOSS-1001');
|
||||
|
||||
await reportPaymentFailureOnReturn();
|
||||
|
||||
expect(apiPost).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('다른 주문번호로 돌아왔으면 보고하지 않는다', async () => {
|
||||
const apiPost = vi.fn();
|
||||
windowRecord().G7Core = { api: { post: apiPost } };
|
||||
|
||||
rememberPendingClose(CONTEXT);
|
||||
setLocation('/shop/checkout', '?error=PAY_PROCESS_CANCELED&orderId=ORD-TOSS-OTHER');
|
||||
|
||||
await reportPaymentFailureOnReturn();
|
||||
|
||||
expect(apiPost).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('결제 완료 화면으로 돌아오면 보고하지 않고 저장분만 지운다', async () => {
|
||||
const apiPost = vi.fn();
|
||||
windowRecord().G7Core = { api: { post: apiPost } };
|
||||
|
||||
rememberPendingClose(CONTEXT);
|
||||
setLocation('/shop/orders/ORD-TOSS-1001/complete', '');
|
||||
|
||||
await reportPaymentFailureOnReturn();
|
||||
|
||||
expect(apiPost).not.toHaveBeenCalled();
|
||||
expect(window.sessionStorage.getItem('g7:sirsoft-tosspayments:pendingClose')).toBeNull();
|
||||
});
|
||||
|
||||
it('실패 표시가 전혀 없으면 판단하지 않고 저장분을 남겨 둔다', async () => {
|
||||
const apiPost = vi.fn();
|
||||
windowRecord().G7Core = { api: { post: apiPost } };
|
||||
|
||||
rememberPendingClose(CONTEXT);
|
||||
setLocation('/shop/checkout', '');
|
||||
|
||||
await reportPaymentFailureOnReturn();
|
||||
|
||||
expect(apiPost).not.toHaveBeenCalled();
|
||||
expect(window.sessionStorage.getItem('g7:sirsoft-tosspayments:pendingClose')).not.toBeNull();
|
||||
});
|
||||
|
||||
it('G7Core API 가 없으면 fetch 로 보고한다', async () => {
|
||||
const fetchSpy = vi.fn().mockResolvedValue({ ok: true, json: async () => ({}) });
|
||||
windowRecord().fetch = fetchSpy;
|
||||
|
||||
rememberPendingClose(CONTEXT);
|
||||
setLocation('/shop/checkout', '?error=REJECT_CARD_COMPANY&orderId=ORD-TOSS-1001');
|
||||
|
||||
await reportPaymentFailureOnReturn();
|
||||
|
||||
expect(fetchSpy).toHaveBeenCalledWith(
|
||||
'/api/plugins/sirsoft-tosspayments/payment/close-report',
|
||||
expect.objectContaining({ method: 'POST' }),
|
||||
);
|
||||
});
|
||||
|
||||
it('보고가 실패해도 예외를 던지지 않는다', async () => {
|
||||
const apiPost = vi.fn().mockRejectedValue(new Error('network down'));
|
||||
windowRecord().G7Core = { api: { post: apiPost } };
|
||||
vi.spyOn(console, 'warn').mockImplementation(() => undefined);
|
||||
|
||||
rememberPendingClose(CONTEXT);
|
||||
setLocation('/shop/checkout', '?error=PAY_PROCESS_CANCELED&orderId=ORD-TOSS-1001');
|
||||
|
||||
await expect(reportPaymentFailureOnReturn()).resolves.toBeUndefined();
|
||||
});
|
||||
|
||||
it('forgetPendingClose 는 저장분을 지운다', () => {
|
||||
rememberPendingClose(CONTEXT);
|
||||
expect(window.sessionStorage.getItem('g7:sirsoft-tosspayments:pendingClose')).not.toBeNull();
|
||||
|
||||
forgetPendingClose();
|
||||
|
||||
expect(window.sessionStorage.getItem('g7:sirsoft-tosspayments:pendingClose')).toBeNull();
|
||||
});
|
||||
});
|
||||
@@ -15,6 +15,8 @@
|
||||
|
||||
/* eslint-disable @typescript-eslint/no-explicit-any */
|
||||
|
||||
import { rememberPendingClose } from '../paymentCloseReport';
|
||||
|
||||
interface EscrowProduct {
|
||||
id: string;
|
||||
name: string;
|
||||
@@ -295,6 +297,16 @@ export async function requestPaymentHandler(action: any, _context?: any): Promis
|
||||
attachEscrowProducts(requestPayload, config, pgPaymentData);
|
||||
}
|
||||
|
||||
// 결제창은 전체 페이지 이동으로 열리고 돌아오므로, 실패 화면에서 서버에 보고할 때 쓸
|
||||
// 구매자 정보를 미리 남겨 둔다. 브라우저 리턴 콜백은 인증이 없어 주문 상태를 바꾸지 않고,
|
||||
// 소유권을 대조하는 close-report 만이 정당한 결제 실패를 기록할 수 있다.
|
||||
rememberPendingClose({
|
||||
orderId: pgPaymentData.order_number,
|
||||
amount: pgPaymentData.amount,
|
||||
buyer_email: pgPaymentData.customer_email ?? '',
|
||||
buyer_phone: pgPaymentData.customer_phone ?? '',
|
||||
});
|
||||
|
||||
await payment.requestPayment(requestPayload);
|
||||
// → 브라우저가 successUrl 또는 failUrl로 리다이렉트됨
|
||||
|
||||
|
||||
@@ -7,6 +7,7 @@
|
||||
|
||||
import { handlerMap } from './handlers';
|
||||
import { installAdminPaymentMethodBrandInjector } from './adminPaymentMethodBrandInjector';
|
||||
import { reportPaymentFailureOnReturn } from './paymentCloseReport';
|
||||
|
||||
const PLUGIN_IDENTIFIER = 'sirsoft-tosspayments';
|
||||
|
||||
@@ -67,6 +68,11 @@ function initPlugin(): void {
|
||||
// (관리자 화면은 결제 핸들러를 쓰지 않으므로 ActionDispatcher 준비를 기다릴 이유가 없다).
|
||||
installAdminPaymentMethodBrandInjector();
|
||||
|
||||
// 결제 실패로 돌아온 화면이면 서버에 보고한다. 브라우저 리턴 콜백은 인증이 없어 주문
|
||||
// 상태를 바꾸지 않으므로, 소유권을 대조하는 close-report 가 정당한 실패를 기록하는
|
||||
// 유일한 경로다. 저장해 둔 정보가 없으면 아무 일도 하지 않는다.
|
||||
void reportPaymentFailureOnReturn();
|
||||
|
||||
const doInit = () => {
|
||||
const count = registerHandlers();
|
||||
|
||||
|
||||
@@ -0,0 +1,187 @@
|
||||
/**
|
||||
* 토스페이먼츠 결제창 닫힘·결제 실패 보고
|
||||
*
|
||||
* 브라우저 리턴 콜백(`/payment/fail`)은 인증도 서명도 없고 주문번호가 쿼리스트링으로 오므로
|
||||
* 주문 상태를 바꾸지 않는다. 정당한 결제 실패를 기록하는 것은 구매자 정보를 대조하는
|
||||
* close-report 엔드포인트뿐이며, 이 모듈이 그 호출을 담당한다.
|
||||
*
|
||||
* 결제창은 전체 페이지 이동으로 열리고 돌아오므로, 결제 요청 직전에 구매자 정보를
|
||||
* sessionStorage 에 남겨 두었다가 실패 화면으로 돌아왔을 때 꺼내 쓴다. sessionStorage 는
|
||||
* 같은 탭에서 외부 도메인을 다녀와도 유지된다.
|
||||
*/
|
||||
|
||||
const PLUGIN_IDENTIFIER = 'sirsoft-tosspayments';
|
||||
|
||||
const STORAGE_KEY = 'g7:sirsoft-tosspayments:pendingClose';
|
||||
|
||||
const CLOSE_REPORT_PATH = '/api/plugins/sirsoft-tosspayments/payment/close-report';
|
||||
|
||||
export interface PaymentCloseReportContext {
|
||||
orderId: string;
|
||||
amount: number;
|
||||
buyer_email?: string;
|
||||
buyer_phone?: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* sessionStorage 접근은 브라우저 설정(사이트 데이터 차단·시크릿 모드)에 따라 예외를 던진다.
|
||||
* 보고는 편의 장치이므로 실패해도 결제 흐름을 막지 않는다.
|
||||
*/
|
||||
function safeSessionStorage(): Storage | null {
|
||||
try {
|
||||
return window.sessionStorage ?? null;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 결제창을 열기 직전에 구매자 정보를 저장합니다.
|
||||
*
|
||||
* @param context 결제창 닫힘 보고에 필요한 주문·구매자 정보
|
||||
*/
|
||||
export function rememberPendingClose(context: PaymentCloseReportContext): void {
|
||||
const storage = safeSessionStorage();
|
||||
if (!storage) {
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
storage.setItem(STORAGE_KEY, JSON.stringify(context));
|
||||
} catch {
|
||||
// 저장 실패는 무시 — 만료 자동 정리가 최종 안전망이다.
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 저장해 둔 구매자 정보를 지웁니다 (보고 완료 또는 결제 성공 시).
|
||||
*/
|
||||
export function forgetPendingClose(): void {
|
||||
const storage = safeSessionStorage();
|
||||
if (!storage) {
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
storage.removeItem(STORAGE_KEY);
|
||||
} catch {
|
||||
// 무시
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 저장해 둔 구매자 정보를 읽습니다.
|
||||
*
|
||||
* @returns 저장된 정보, 없거나 형식이 깨졌으면 null
|
||||
*/
|
||||
function readPendingClose(): PaymentCloseReportContext | null {
|
||||
const storage = safeSessionStorage();
|
||||
if (!storage) {
|
||||
return null;
|
||||
}
|
||||
|
||||
try {
|
||||
const raw = storage.getItem(STORAGE_KEY);
|
||||
if (!raw) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const parsed = JSON.parse(raw) as PaymentCloseReportContext;
|
||||
|
||||
return parsed && typeof parsed.orderId === 'string' && parsed.orderId !== ''
|
||||
? parsed
|
||||
: null;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* close-report 엔드포인트에 보고합니다.
|
||||
*
|
||||
* @param context 주문·구매자 정보
|
||||
* @param code 결제 실패 코드 (결제창을 닫은 경우 빈 값)
|
||||
* @param reason 사람이 읽을 실패 사유
|
||||
*/
|
||||
async function postCloseReport(
|
||||
context: PaymentCloseReportContext,
|
||||
code: string,
|
||||
reason: string,
|
||||
): Promise<void> {
|
||||
const payload = {
|
||||
orderId: context.orderId,
|
||||
amount: Number(context.amount),
|
||||
buyer_email: context.buyer_email ?? '',
|
||||
buyer_phone: context.buyer_phone ?? '',
|
||||
code: code.slice(0, 60),
|
||||
reason: reason.trim().slice(0, 160),
|
||||
};
|
||||
|
||||
const apiClient = ((window as any).G7Core)?.api;
|
||||
if (typeof apiClient?.post === 'function') {
|
||||
await apiClient.post(CLOSE_REPORT_PATH, payload);
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
await fetch(CLOSE_REPORT_PATH, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json', Accept: 'application/json' },
|
||||
body: JSON.stringify(payload),
|
||||
keepalive: true,
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* 결제 실패 화면으로 돌아왔으면 저장해 둔 정보로 서버에 보고합니다.
|
||||
*
|
||||
* 결제 성공으로 돌아온 경우에는 보고하지 않고 저장분만 지운다 — 성공 확정은 서버의
|
||||
* `confirmPayment` 가 담당하므로 여기서 관여할 것이 없다.
|
||||
*
|
||||
* 플러그인 부팅 시 1회 호출한다.
|
||||
*/
|
||||
export async function reportPaymentFailureOnReturn(): Promise<void> {
|
||||
const pending = readPendingClose();
|
||||
if (!pending) {
|
||||
return;
|
||||
}
|
||||
|
||||
let params: URLSearchParams;
|
||||
try {
|
||||
params = new URLSearchParams(window.location.search);
|
||||
} catch {
|
||||
return;
|
||||
}
|
||||
|
||||
const orderIdInUrl = params.get('orderId') ?? '';
|
||||
|
||||
// 저장분과 화면의 주문번호가 다르면 이번 이동과 무관한 잔여물이다 — 보고하지 않는다.
|
||||
if (orderIdInUrl !== '' && orderIdInUrl !== pending.orderId) {
|
||||
return;
|
||||
}
|
||||
|
||||
// 결제 완료 화면으로 돌아왔으면 보고 대상이 아니다.
|
||||
if (/\/(complete|success)(\/|$|\?)/.test(window.location.pathname)) {
|
||||
forgetPendingClose();
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
const code = params.get('error') ?? '';
|
||||
const message = params.get('message') ?? '';
|
||||
|
||||
// 실패 표시가 전혀 없으면 결제창을 열기만 하고 돌아온 경우일 수 있다 — 판단하지 않는다.
|
||||
if (code === '' && orderIdInUrl === '') {
|
||||
return;
|
||||
}
|
||||
|
||||
// 중복 보고를 막기 위해 요청 전에 먼저 지운다. 서버도 멱등하게 처리하지만
|
||||
// (이미 취소된 주문은 order_not_payable 로 무시) 불필요한 요청 자체를 줄인다.
|
||||
forgetPendingClose();
|
||||
|
||||
try {
|
||||
await postCloseReport(pending, code, message !== '' ? message : code);
|
||||
} catch (error) {
|
||||
console.warn(`[${PLUGIN_IDENTIFIER}] failed to report payment failure`, error);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,204 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Plugins\Sirsoft\Tosspayments\Concerns;
|
||||
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Support\Facades\Log;
|
||||
use InvalidArgumentException;
|
||||
use Modules\Sirsoft\Ecommerce\Enums\PaymentStatusEnum;
|
||||
use Modules\Sirsoft\Ecommerce\Models\Order;
|
||||
use Modules\Sirsoft\Ecommerce\Models\OrderAddress;
|
||||
use Modules\Sirsoft\Ecommerce\Models\OrderPayment;
|
||||
use Modules\Sirsoft\Ecommerce\Services\CurrencyConversionService;
|
||||
use Modules\Sirsoft\Ecommerce\Services\OrderProcessingService;
|
||||
|
||||
/**
|
||||
* 결제창 닫힘·결제 실패를 소유권 검증 후 기록하는 공통 절차.
|
||||
*
|
||||
* 브라우저 리턴 콜백(`/payment/success`·`/payment/fail`)은 인증도 서명도 없고 주문번호가
|
||||
* 쿼리스트링으로 오므로 주문 상태를 바꾸지 않는다. 주문을 실패로 전이시키는 것은 구매자
|
||||
* 정보를 대조한 이 경로뿐이며, 다른 결제사 플러그인(KCP·KG이니시스·나이스페이)과 같은 계약이다.
|
||||
*/
|
||||
trait RecordsPaymentWindowClosure
|
||||
{
|
||||
private const TOSS_PROVIDER = 'tosspayments';
|
||||
|
||||
/**
|
||||
* 주문의 결제 청구액을 결제 통화 기준으로 계산합니다.
|
||||
*
|
||||
* 결제 청구액 SSoT 는 결제 통화(order_currency) 환산액이다. base(total_due_amount)를 직접
|
||||
* 비교하면 base≠결제 통화인 주문에서 PG 청구 통화와 단위가 어긋난다.
|
||||
*
|
||||
* @param Order $order 대상 주문
|
||||
* @return int 결제 통화 기준 청구액
|
||||
*/
|
||||
protected function expectedPaymentPrice(Order $order): int
|
||||
{
|
||||
return app(CurrencyConversionService::class)->resolveOrderPaymentChargeAmount($order);
|
||||
}
|
||||
|
||||
/**
|
||||
* 결제 청구액을 계산하되 통화가 청구 불가하면 null 을 반환합니다.
|
||||
*
|
||||
* @param Order $order 대상 주문
|
||||
* @param string $context 로그 문맥
|
||||
* @param array<string, mixed> $logContext 추가 로그 항목
|
||||
* @return int|null 청구액, 통화가 청구 불가하면 null
|
||||
*/
|
||||
protected function resolveExpectedPaymentPriceOrNull(Order $order, string $context, array $logContext = []): ?int
|
||||
{
|
||||
try {
|
||||
return $this->expectedPaymentPrice($order);
|
||||
} catch (InvalidArgumentException $e) {
|
||||
Log::error('TossPayments: payment currency is not chargeable', array_merge([
|
||||
'context' => $context,
|
||||
'order_id' => $order->id,
|
||||
'order_number' => $order->order_number,
|
||||
'currency' => $order->currency,
|
||||
'error' => $e->getMessage(),
|
||||
], $logContext));
|
||||
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 요청이 주문의 구매자 본인에게서 온 것인지 대조합니다.
|
||||
*
|
||||
* 이 대조가 주문 상태를 바꿀 자격의 근거다. 배송지가 없으면 대조할 기준이 없으므로 통과시킨다
|
||||
* (다른 결제사 플러그인과 동일 계약).
|
||||
*
|
||||
* @param Request $request 검증 대상 요청
|
||||
* @param Order $order 대상 주문
|
||||
* @return bool 구매자 정보가 일치하면 true
|
||||
*/
|
||||
protected function requestMatchesOrderBuyer(Request $request, Order $order): bool
|
||||
{
|
||||
/** @var OrderAddress|null $address */
|
||||
$address = $order->shippingAddress;
|
||||
if (! $address) {
|
||||
return true;
|
||||
}
|
||||
|
||||
$expectedEmail = strtolower(trim((string) $address->orderer_email));
|
||||
if ($expectedEmail !== '') {
|
||||
$receivedEmail = strtolower(trim((string) $request->input('buyer_email', '')));
|
||||
if ($receivedEmail === '' || $receivedEmail !== $expectedEmail) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
$expectedPhone = $this->digitsOnly((string) $address->orderer_phone);
|
||||
if ($expectedPhone !== '') {
|
||||
$receivedPhone = $this->digitsOnly((string) $request->input('buyer_phone', ''));
|
||||
if ($receivedPhone === '' || $receivedPhone !== $expectedPhone) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* 결제창 닫힘/실패를 주문에 반영합니다.
|
||||
*
|
||||
* @param OrderProcessingService $orderService 주문 처리 서비스
|
||||
* @param Order $order 대상 주문
|
||||
* @param string $failureCode 실패 코드
|
||||
* @param string $failureMessage 실패 메시지
|
||||
* @param string|null $cancelMessage 취소 이력에 남길 메시지 (미전달 시 실패 메시지)
|
||||
* @param string $failureStage 실패 단계 (window_closed | payment_failed)
|
||||
* @return Order 반영된 주문
|
||||
*/
|
||||
protected function markPaymentWindowClosed(
|
||||
OrderProcessingService $orderService,
|
||||
Order $order,
|
||||
string $failureCode,
|
||||
string $failureMessage,
|
||||
?string $cancelMessage = null,
|
||||
string $failureStage = 'window_closed',
|
||||
): Order {
|
||||
if (! $order->order_status->isBeforePayment()) {
|
||||
return $order;
|
||||
}
|
||||
|
||||
$failedOrder = $orderService->failPayment($order, $failureCode, $failureMessage);
|
||||
|
||||
$cancelledOrder = $orderService->recordPaymentCancellation(
|
||||
$failedOrder,
|
||||
$failureCode,
|
||||
$cancelMessage ?: $failureMessage,
|
||||
);
|
||||
|
||||
return $this->markTossPaymentFailureRecord(
|
||||
$cancelledOrder,
|
||||
$failureCode,
|
||||
$cancelMessage ?: $failureMessage,
|
||||
$failureStage,
|
||||
PaymentStatusEnum::CANCELLED,
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* 결제 실패 이력을 결제 레코드에 남깁니다.
|
||||
*
|
||||
* @param Order $order 대상 주문
|
||||
* @param string $failureCode 실패 코드
|
||||
* @param string $failureMessage 실패 메시지
|
||||
* @param string $failureStage 실패 단계
|
||||
* @param PaymentStatusEnum $paymentStatus 기록할 결제 상태
|
||||
* @return Order 갱신된 주문
|
||||
*/
|
||||
protected function markTossPaymentFailureRecord(
|
||||
Order $order,
|
||||
string $failureCode,
|
||||
string $failureMessage,
|
||||
string $failureStage,
|
||||
PaymentStatusEnum $paymentStatus = PaymentStatusEnum::FAILED,
|
||||
): Order {
|
||||
/** @var OrderPayment|null $payment */
|
||||
$payment = $order->payment;
|
||||
if (! $payment || ! $payment->exists) {
|
||||
return $order;
|
||||
}
|
||||
|
||||
$now = now()->toIso8601String();
|
||||
$paymentMeta = $payment->payment_meta ?? [];
|
||||
$history = $paymentMeta['failure_history'] ?? [];
|
||||
$history = is_array($history) ? $history : [];
|
||||
$history[] = [
|
||||
'code' => $failureCode,
|
||||
'message' => $failureMessage,
|
||||
'stage' => $failureStage,
|
||||
'failed_at' => $now,
|
||||
];
|
||||
|
||||
$paymentMeta['failure_history'] = array_slice($history, -5);
|
||||
$paymentMeta['failure_source'] = self::TOSS_PROVIDER;
|
||||
$paymentMeta['failure_code'] = $failureCode;
|
||||
$paymentMeta['failure_message'] = $failureMessage;
|
||||
$paymentMeta['failure_stage'] = $failureStage;
|
||||
$paymentMeta['failed_at'] = $now;
|
||||
|
||||
$payment->update([
|
||||
'pg_provider' => self::TOSS_PROVIDER,
|
||||
'payment_status' => $paymentStatus->value,
|
||||
'payment_meta' => $paymentMeta,
|
||||
]);
|
||||
|
||||
return $order->fresh('payment') ?? $order;
|
||||
}
|
||||
|
||||
/**
|
||||
* 문자열에서 숫자만 남깁니다 (전화번호 대조용).
|
||||
*
|
||||
* @param string $value 원본 문자열
|
||||
* @return string 숫자만 남은 문자열
|
||||
*/
|
||||
protected function digitsOnly(string $value): string
|
||||
{
|
||||
return preg_replace('/[^0-9]/', '', $value) ?? '';
|
||||
}
|
||||
}
|
||||
@@ -176,14 +176,11 @@ class PaymentCallbackController
|
||||
'orderId' => $orderId,
|
||||
]);
|
||||
|
||||
if ($orderId) {
|
||||
$order = $this->orderService->findByOrderNumber($orderId);
|
||||
|
||||
if ($order) {
|
||||
$this->orderService->failPayment($order, $code, $message);
|
||||
}
|
||||
}
|
||||
|
||||
// 이 엔드포인트는 인증도 서명도 없는 GET 이고, orderId·code·message 는 전부 쿼리스트링에서
|
||||
// 온다. 즉 "실패했다" 는 주장 자체를 누구나 만들 수 있고 대상 주문도 마음대로 고를 수 있다.
|
||||
// 그 주장만으로 주문을 실패 처리하면 링크 하나로 남의 결제대기 주문을 취소시킬 수 있으므로,
|
||||
// 여기서는 주문 상태를 바꾸지 않고 기록과 안내만 한다.
|
||||
// 실제 결제 성립은 success() 의 서버 confirm 이, 결제완료 후 취소는 서명 검증된 웹훅이 담당한다.
|
||||
return redirect($this->resolveFailUrl([
|
||||
'error' => $code,
|
||||
'message' => $message,
|
||||
|
||||
+130
@@ -0,0 +1,130 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Plugins\Sirsoft\Tosspayments\Controllers;
|
||||
|
||||
use App\Helpers\ResponseHelper;
|
||||
use Illuminate\Http\JsonResponse;
|
||||
use Illuminate\Support\Facades\RateLimiter;
|
||||
use Modules\Sirsoft\Ecommerce\Services\OrderProcessingService;
|
||||
use Plugins\Sirsoft\Tosspayments\Concerns\RecordsPaymentWindowClosure;
|
||||
use Plugins\Sirsoft\Tosspayments\Http\Requests\PaymentCloseReportRequest;
|
||||
|
||||
/**
|
||||
* 토스페이먼츠 결제창 닫힘·결제 실패 보고 컨트롤러
|
||||
*
|
||||
* 브라우저 리턴 콜백(`/payment/fail`)은 인증도 서명도 없고 주문번호가 쿼리스트링으로 오므로
|
||||
* 주문 상태를 바꾸지 않는다. 주문을 실패로 전이시키는 것은 구매자 정보를 대조한 이 경로뿐이며,
|
||||
* KCP·KG이니시스·나이스페이 플러그인의 close-report 와 같은 계약이다.
|
||||
*/
|
||||
class PaymentCloseReportController
|
||||
{
|
||||
use RecordsPaymentWindowClosure;
|
||||
|
||||
private const FAILURE_CODE = 'USER_CANCEL';
|
||||
|
||||
private const FAILURE_MESSAGE = '사용자가 토스페이먼츠 결제창을 닫았습니다.';
|
||||
|
||||
public function __construct(
|
||||
private readonly OrderProcessingService $orderService,
|
||||
) {}
|
||||
|
||||
/**
|
||||
* 결제창 닫힘·결제 실패 보고를 검증하고 결제 실패/취소 이력을 기록합니다.
|
||||
*
|
||||
* @param PaymentCloseReportRequest $request 결제창 닫힘 보고 요청
|
||||
* @return JsonResponse 닫힘 보고 처리 결과
|
||||
*/
|
||||
public function store(PaymentCloseReportRequest $request): JsonResponse
|
||||
{
|
||||
$validated = $request->validated();
|
||||
$orderId = $validated['orderId'];
|
||||
$amount = (int) $validated['amount'];
|
||||
|
||||
$rateLimitKey = $this->rateLimitKey($request->ip() ?? '', $orderId);
|
||||
if (RateLimiter::tooManyAttempts($rateLimitKey, 20)) {
|
||||
return ResponseHelper::error('common.failed', 429, [
|
||||
'message' => ['Too many TossPayments payment close reports. Please try again later.'],
|
||||
]);
|
||||
}
|
||||
RateLimiter::hit($rateLimitKey, 60);
|
||||
|
||||
$order = $this->orderService->findByOrderNumber($orderId);
|
||||
if (! $order) {
|
||||
return ResponseHelper::error('common.failed', 404, [
|
||||
'message' => ['Order not found.'],
|
||||
]);
|
||||
}
|
||||
|
||||
if (! $order->order_status->isBeforePayment()) {
|
||||
return ResponseHelper::success('common.success', [
|
||||
'status' => 'ignored',
|
||||
'reason' => 'order_not_payable',
|
||||
]);
|
||||
}
|
||||
|
||||
// 결제 성공 콜백(success → confirmPayment)과 이 보고가 경쟁할 수 있다. 카드 주문은 승인
|
||||
// 직전까지 order_status=PENDING_ORDER 라 위 가드를 통과하므로, 결제가 이미 성공했으면
|
||||
// 여기서 차단해 옵션이 취소로 덮이는 것을 막는다.
|
||||
if ($order->payment?->isPaid()) {
|
||||
return ResponseHelper::success('common.success', [
|
||||
'status' => 'ignored',
|
||||
'reason' => 'payment_already_paid',
|
||||
]);
|
||||
}
|
||||
|
||||
if (! $this->requestMatchesOrderBuyer($request, $order)) {
|
||||
return ResponseHelper::error('common.failed', 403, [
|
||||
'message' => ['Order buyer verification failed.'],
|
||||
]);
|
||||
}
|
||||
|
||||
$expectedAmount = $this->resolveExpectedPaymentPriceOrNull($order, 'close_report', [
|
||||
'orderId' => $orderId,
|
||||
'received_amount' => $amount,
|
||||
'ip' => $request->ip(),
|
||||
]);
|
||||
if ($expectedAmount === null) {
|
||||
return ResponseHelper::error('common.failed', 422, [
|
||||
'message' => ['Payment currency is not chargeable.'],
|
||||
]);
|
||||
}
|
||||
|
||||
if ($amount !== $expectedAmount) {
|
||||
return ResponseHelper::error('common.failed', 422, [
|
||||
'message' => ['Payment amount does not match the order amount.'],
|
||||
]);
|
||||
}
|
||||
|
||||
// 결제창을 닫은 것인지 결제가 거절된 것인지는 실패 코드 유무로 갈린다. 두 경우 모두
|
||||
// 주문을 실패로 전이시키지만, 운영자가 원인을 구분할 수 있도록 단계를 나눠 기록한다.
|
||||
$failureCode = trim((string) ($validated['code'] ?? ''));
|
||||
$closeReason = trim((string) ($validated['reason'] ?? ''));
|
||||
|
||||
$this->markPaymentWindowClosed(
|
||||
$this->orderService,
|
||||
$order,
|
||||
$failureCode !== '' ? $failureCode : self::FAILURE_CODE,
|
||||
self::FAILURE_MESSAGE,
|
||||
$closeReason !== '' ? $closeReason : self::FAILURE_MESSAGE,
|
||||
$failureCode !== '' ? 'payment_failed' : 'window_closed',
|
||||
);
|
||||
|
||||
return ResponseHelper::success('common.success', [
|
||||
'status' => 'recorded',
|
||||
]);
|
||||
}
|
||||
|
||||
/**
|
||||
* 레이트리밋 키를 생성합니다 (IP + 주문번호 조합).
|
||||
*
|
||||
* @param string $ip 요청 IP
|
||||
* @param string $orderId 주문번호
|
||||
* @return string 레이트리밋 키
|
||||
*/
|
||||
private function rateLimitKey(string $ip, string $orderId): string
|
||||
{
|
||||
return 'sirsoft-tosspayments:payment-close-report:'.sha1($ip.'|'.$orderId);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Plugins\Sirsoft\Tosspayments\Http\Requests;
|
||||
|
||||
use Illuminate\Foundation\Http\FormRequest;
|
||||
|
||||
class PaymentCloseReportRequest extends FormRequest
|
||||
{
|
||||
/**
|
||||
* 결제창 닫힘 보고 요청을 허용합니다.
|
||||
*
|
||||
* 인증은 요구하지 않는다 — 결제창 컨텍스트에서 호출되기 때문이다. 대신 컨트롤러가
|
||||
* 구매자 정보·금액 대조로 자격을 검증한다.
|
||||
*
|
||||
* @return bool 요청 허용 여부
|
||||
*/
|
||||
public function authorize(): bool
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* 결제창 닫힘 보고 요청 검증 규칙을 반환합니다.
|
||||
*
|
||||
* @return array<string, array<int, string>> 필드별 검증 규칙
|
||||
*/
|
||||
public function rules(): array
|
||||
{
|
||||
return [
|
||||
'orderId' => ['required', 'string', 'max:40'],
|
||||
'amount' => ['required', 'integer', 'min:1'],
|
||||
'buyer_email' => ['nullable', 'string', 'max:255'],
|
||||
'buyer_phone' => ['nullable', 'string', 'max:30'],
|
||||
'reason' => ['nullable', 'string', 'max:160'],
|
||||
'code' => ['nullable', 'string', 'max:60'],
|
||||
];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
<?php
|
||||
|
||||
use Illuminate\Support\Facades\Route;
|
||||
use Plugins\Sirsoft\Tosspayments\Controllers\PaymentCloseReportController;
|
||||
|
||||
/*
|
||||
|--------------------------------------------------------------------------
|
||||
| TossPayments Plugin API Routes
|
||||
|--------------------------------------------------------------------------
|
||||
|
|
||||
| 프리픽스: /api/plugins/sirsoft-tosspayments (PluginRouteServiceProvider 자동 적용)
|
||||
| 미들웨어: api (PluginRouteServiceProvider 자동 적용)
|
||||
|
|
||||
*/
|
||||
|
||||
// 결제창 닫힘·결제 실패 보고 — 구매자 정보 대조 후 결제 실패/취소 이력 기록.
|
||||
// 브라우저 리턴 콜백(/payment/fail)은 인증·서명이 없어 주문 상태를 바꾸지 않으므로,
|
||||
// 주문을 실패로 전이시키는 유일한 결제창 경로다 (다른 결제사 플러그인과 동일 계약).
|
||||
Route::post('/payment/close-report', [PaymentCloseReportController::class, 'store'])
|
||||
->name('payment.close-report');
|
||||
+37
-6
@@ -345,9 +345,18 @@ class PaymentCallbackControllerTest extends PluginTestCase
|
||||
/**
|
||||
* 결제 실패 시 주문이 존재하면 failPayment 처리되는지 확인
|
||||
*/
|
||||
public function test_fail_calls_fail_payment_when_order_exists(): void
|
||||
/**
|
||||
* 실패 콜백은 주문 상태를 바꾸지 않는다.
|
||||
*
|
||||
* 계약 변경(KVE-2026-2018 형제): 이 엔드포인트는 인증도 서명도 없는 GET 이고
|
||||
* `orderId`·`code` 가 전부 쿼리스트링에서 온다. 실패 처리를 수행하면 링크 하나로
|
||||
* 남의 결제대기 주문을 취소시킬 수 있다. 결제 성립은 `success()` 의 서버 confirm 이,
|
||||
* 결제완료 후 취소는 서명 검증된 웹훅이 담당한다.
|
||||
*/
|
||||
public function test_fail_does_not_mutate_the_order(): void
|
||||
{
|
||||
$order = $this->createTestOrder(30000);
|
||||
$statusBefore = $order->order_status;
|
||||
|
||||
$response = $this->get('/plugins/sirsoft-tosspayments/payment/fail?'.http_build_query([
|
||||
'code' => 'PAY_PROCESS_CANCELED',
|
||||
@@ -357,13 +366,35 @@ class PaymentCallbackControllerTest extends PluginTestCase
|
||||
|
||||
$response->assertRedirect();
|
||||
|
||||
// 주문 상태가 CANCELLED로 변경되었는지 확인
|
||||
$order->refresh();
|
||||
$this->assertEquals(OrderStatusEnum::CANCELLED, $order->order_status);
|
||||
$this->assertEquals($statusBefore, $order->order_status, '비인증 실패 콜백이 주문 상태를 바꿨습니다.');
|
||||
$this->assertNotEquals(OrderStatusEnum::CANCELLED, $order->order_status);
|
||||
$this->assertArrayNotHasKey('payment_failure_code', $order->order_meta ?? []);
|
||||
}
|
||||
|
||||
// 주문 메타에 실패 정보가 저장되었는지 확인
|
||||
$meta = $order->order_meta;
|
||||
$this->assertEquals('PAY_PROCESS_CANCELED', $meta['payment_failure_code']);
|
||||
/**
|
||||
* 제3자가 링크 하나로 타인의 결제대기 주문을 취소할 수 없다 (KVE-2026-2018 형제 회귀).
|
||||
*/
|
||||
public function test_unauthenticated_fail_link_cannot_cancel_another_users_order(): void
|
||||
{
|
||||
$victimOrder = $this->createTestOrder(30000);
|
||||
|
||||
// 공격자는 로그인하지 않고 피해자의 주문번호만 실어 이 URL 을 연다.
|
||||
$response = $this->get('/plugins/sirsoft-tosspayments/payment/fail?'.http_build_query([
|
||||
'code' => 'PAY_PROCESS_CANCELED',
|
||||
'message' => 'forged',
|
||||
'orderId' => $victimOrder->order_number,
|
||||
]));
|
||||
|
||||
$response->assertRedirect();
|
||||
|
||||
$victimOrder->refresh();
|
||||
$this->assertEquals(
|
||||
OrderStatusEnum::PENDING_ORDER,
|
||||
$victimOrder->order_status,
|
||||
'무인증 GET 하나로 피해자의 주문이 취소되었습니다.'
|
||||
);
|
||||
$this->assertNotEquals(PaymentStatusEnum::FAILED, $victimOrder->payment->refresh()->payment_status);
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
+276
@@ -0,0 +1,276 @@
|
||||
<?php
|
||||
|
||||
namespace Plugins\Sirsoft\Tosspayments\Tests\Feature\Controllers;
|
||||
|
||||
use Modules\Sirsoft\Ecommerce\Database\Factories\OrderFactory;
|
||||
use Modules\Sirsoft\Ecommerce\Database\Factories\OrderPaymentFactory;
|
||||
use Modules\Sirsoft\Ecommerce\Enums\OrderStatusEnum;
|
||||
use Modules\Sirsoft\Ecommerce\Enums\PaymentMethodEnum;
|
||||
use Modules\Sirsoft\Ecommerce\Enums\PaymentStatusEnum;
|
||||
use Modules\Sirsoft\Ecommerce\Models\Order;
|
||||
use Modules\Sirsoft\Ecommerce\Models\OrderAddress;
|
||||
use Plugins\Sirsoft\Tosspayments\Tests\PluginTestCase;
|
||||
|
||||
/**
|
||||
* 토스페이먼츠 결제창 닫힘·결제 실패 보고 테스트
|
||||
*
|
||||
* 브라우저 리턴 콜백(`/payment/fail`)이 주문 상태를 바꾸지 않게 되면서, 정당한 결제 실패를
|
||||
* 기록하는 책임은 전적으로 이 엔드포인트에 있다. 그 자격은 구매자 정보 대조가 정한다.
|
||||
*/
|
||||
class PaymentCloseReportControllerTest extends PluginTestCase
|
||||
{
|
||||
private const URL = '/api/plugins/sirsoft-tosspayments/payment/close-report';
|
||||
|
||||
private const BUYER_EMAIL = 'toss-buyer@example.com';
|
||||
|
||||
private const BUYER_PHONE = '01012345678';
|
||||
|
||||
/**
|
||||
* 원화 통화 스냅샷 (자릿수 명시).
|
||||
*
|
||||
* 팩토리 기본값은 상점 통화 설정에서 읽으므로 선행 스위트가 남긴 설정 상태에 좌우된다.
|
||||
* 특히 `decimal_places` 가 비면 KRW(0자리)가 2자리로 해석돼 청구액이 100배가 되고,
|
||||
* 이 파일의 금액 대조가 실제와 다른 것을 측정하게 된다.
|
||||
*
|
||||
* @return array<string, mixed> 통화 스냅샷
|
||||
*/
|
||||
private static function krwSnapshot(): array
|
||||
{
|
||||
return [
|
||||
'base_currency' => 'KRW',
|
||||
'order_currency' => 'KRW',
|
||||
'exchange_rate' => 1.0,
|
||||
'exchange_rates' => [
|
||||
'KRW' => [
|
||||
'rate' => 1.0,
|
||||
'decimal_places' => 0,
|
||||
'rounding_unit' => '1',
|
||||
'rounding_method' => 'round',
|
||||
],
|
||||
],
|
||||
'snapshot_at' => '2026-01-01T00:00:00+00:00',
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* 결제 대기 주문과 배송지(구매자 정보)를 생성합니다.
|
||||
*
|
||||
* @param string $orderNumber 주문번호
|
||||
* @param int $amount 주문 금액
|
||||
* @param bool $withAddress 구매자 정보를 담은 배송지 생성 여부
|
||||
* @return Order 생성된 주문
|
||||
*/
|
||||
private function makeOrder(string $orderNumber, int $amount = 10000, bool $withAddress = true): Order
|
||||
{
|
||||
$order = OrderFactory::new()->create([
|
||||
'order_number' => $orderNumber,
|
||||
'order_status' => OrderStatusEnum::PENDING_ORDER,
|
||||
'currency' => 'KRW',
|
||||
'currency_snapshot' => self::krwSnapshot(),
|
||||
'subtotal_amount' => $amount,
|
||||
'total_amount' => $amount,
|
||||
'total_due_amount' => $amount,
|
||||
'total_paid_amount' => 0,
|
||||
]);
|
||||
|
||||
OrderPaymentFactory::new()->create([
|
||||
'order_id' => $order->id,
|
||||
'payment_status' => PaymentStatusEnum::READY,
|
||||
'payment_method' => PaymentMethodEnum::CARD,
|
||||
'pg_provider' => 'tosspayments',
|
||||
'paid_amount_local' => 0,
|
||||
]);
|
||||
|
||||
if ($withAddress) {
|
||||
OrderAddress::create([
|
||||
'order_id' => $order->id,
|
||||
'address_type' => 'shipping',
|
||||
'orderer_name' => '홍길동',
|
||||
'orderer_phone' => self::BUYER_PHONE,
|
||||
'orderer_email' => self::BUYER_EMAIL,
|
||||
'recipient_name' => '홍길동',
|
||||
'recipient_phone' => self::BUYER_PHONE,
|
||||
'zipcode' => '06234',
|
||||
'address' => '서울시 강남구',
|
||||
'address_detail' => '101호',
|
||||
]);
|
||||
}
|
||||
|
||||
return $order->fresh('payment');
|
||||
}
|
||||
|
||||
/**
|
||||
* 구매자 정보가 일치하면 결제창 닫힘이 주문 취소로 기록된다.
|
||||
*/
|
||||
public function test_close_report_marks_pending_order_cancelled(): void
|
||||
{
|
||||
$order = $this->makeOrder('ORD-TOSS-CLOSE-001');
|
||||
|
||||
$response = $this->postJson(self::URL, [
|
||||
'orderId' => 'ORD-TOSS-CLOSE-001',
|
||||
'amount' => 10000,
|
||||
'buyer_email' => self::BUYER_EMAIL,
|
||||
'buyer_phone' => self::BUYER_PHONE,
|
||||
'reason' => 'user closed the payment window',
|
||||
]);
|
||||
|
||||
$response->assertOk();
|
||||
$this->assertSame('recorded', $response->json('data.status'));
|
||||
|
||||
$order->refresh();
|
||||
$this->assertEquals(OrderStatusEnum::CANCELLED, $order->order_status);
|
||||
$this->assertSame('USER_CANCEL', $order->order_meta['payment_failure_code'] ?? null);
|
||||
|
||||
$payment = $order->payment;
|
||||
$payment->refresh();
|
||||
$this->assertEquals(PaymentStatusEnum::CANCELLED, $payment->payment_status);
|
||||
$this->assertSame('tosspayments', $payment->payment_meta['failure_source'] ?? null);
|
||||
$this->assertSame('window_closed', $payment->payment_meta['failure_stage'] ?? null);
|
||||
}
|
||||
|
||||
/**
|
||||
* 결제 거절(실패 코드 동반)은 원인을 구분할 수 있게 기록된다.
|
||||
*/
|
||||
public function test_close_report_records_declined_payment_with_its_code(): void
|
||||
{
|
||||
$order = $this->makeOrder('ORD-TOSS-CLOSE-002');
|
||||
|
||||
$response = $this->postJson(self::URL, [
|
||||
'orderId' => 'ORD-TOSS-CLOSE-002',
|
||||
'amount' => 10000,
|
||||
'buyer_email' => self::BUYER_EMAIL,
|
||||
'buyer_phone' => self::BUYER_PHONE,
|
||||
'code' => 'REJECT_CARD_COMPANY',
|
||||
'reason' => '카드사에서 승인을 거절했습니다.',
|
||||
]);
|
||||
|
||||
$response->assertOk();
|
||||
|
||||
$order->refresh();
|
||||
$this->assertEquals(OrderStatusEnum::CANCELLED, $order->order_status);
|
||||
$this->assertSame('REJECT_CARD_COMPANY', $order->order_meta['payment_failure_code'] ?? null);
|
||||
|
||||
$payment = $order->payment;
|
||||
$payment->refresh();
|
||||
$this->assertSame('payment_failed', $payment->payment_meta['failure_stage'] ?? null);
|
||||
}
|
||||
|
||||
/**
|
||||
* 구매자 정보가 다르면 주문을 건드리지 않는다 — 이 대조가 유일한 자격 근거다.
|
||||
*/
|
||||
public function test_close_report_rejects_buyer_mismatch(): void
|
||||
{
|
||||
$order = $this->makeOrder('ORD-TOSS-CLOSE-003');
|
||||
|
||||
$response = $this->postJson(self::URL, [
|
||||
'orderId' => 'ORD-TOSS-CLOSE-003',
|
||||
'amount' => 10000,
|
||||
'buyer_email' => 'attacker@evil.example',
|
||||
'buyer_phone' => '01099999999',
|
||||
]);
|
||||
|
||||
$response->assertStatus(403);
|
||||
|
||||
$order->refresh();
|
||||
$this->assertEquals(OrderStatusEnum::PENDING_ORDER, $order->order_status);
|
||||
$this->assertArrayNotHasKey('payment_failure_code', $order->order_meta ?? []);
|
||||
}
|
||||
|
||||
/**
|
||||
* 구매자 정보를 아예 보내지 않아도 통과시키지 않는다.
|
||||
*/
|
||||
public function test_close_report_rejects_missing_buyer_information(): void
|
||||
{
|
||||
$order = $this->makeOrder('ORD-TOSS-CLOSE-004');
|
||||
|
||||
$response = $this->postJson(self::URL, [
|
||||
'orderId' => 'ORD-TOSS-CLOSE-004',
|
||||
'amount' => 10000,
|
||||
]);
|
||||
|
||||
$response->assertStatus(403);
|
||||
|
||||
$order->refresh();
|
||||
$this->assertEquals(OrderStatusEnum::PENDING_ORDER, $order->order_status);
|
||||
}
|
||||
|
||||
/**
|
||||
* 금액이 주문 청구액과 다르면 거부한다.
|
||||
*/
|
||||
public function test_close_report_rejects_amount_mismatch(): void
|
||||
{
|
||||
$order = $this->makeOrder('ORD-TOSS-CLOSE-005');
|
||||
|
||||
$response = $this->postJson(self::URL, [
|
||||
'orderId' => 'ORD-TOSS-CLOSE-005',
|
||||
'amount' => 999,
|
||||
'buyer_email' => self::BUYER_EMAIL,
|
||||
'buyer_phone' => self::BUYER_PHONE,
|
||||
]);
|
||||
|
||||
$response->assertStatus(422);
|
||||
|
||||
$order->refresh();
|
||||
$this->assertEquals(OrderStatusEnum::PENDING_ORDER, $order->order_status);
|
||||
}
|
||||
|
||||
/**
|
||||
* 존재하지 않는 주문번호는 404 로 응답한다.
|
||||
*/
|
||||
public function test_close_report_returns_not_found_for_unknown_order(): void
|
||||
{
|
||||
$response = $this->postJson(self::URL, [
|
||||
'orderId' => 'ORD-TOSS-DOES-NOT-EXIST',
|
||||
'amount' => 10000,
|
||||
'buyer_email' => self::BUYER_EMAIL,
|
||||
]);
|
||||
|
||||
$response->assertStatus(404);
|
||||
}
|
||||
|
||||
/**
|
||||
* 이미 결제가 성공한 주문은 무시한다 — 성공 콜백과의 경쟁에서 주문을 덮지 않는다.
|
||||
*/
|
||||
public function test_close_report_ignores_order_whose_payment_already_paid(): void
|
||||
{
|
||||
$order = $this->makeOrder('ORD-TOSS-CLOSE-006');
|
||||
$order->payment->update([
|
||||
'payment_status' => PaymentStatusEnum::PAID->value,
|
||||
'paid_at' => now(),
|
||||
]);
|
||||
|
||||
$response = $this->postJson(self::URL, [
|
||||
'orderId' => 'ORD-TOSS-CLOSE-006',
|
||||
'amount' => 10000,
|
||||
'buyer_email' => self::BUYER_EMAIL,
|
||||
'buyer_phone' => self::BUYER_PHONE,
|
||||
]);
|
||||
|
||||
$response->assertOk();
|
||||
$this->assertSame('ignored', $response->json('data.status'));
|
||||
$this->assertSame('payment_already_paid', $response->json('data.reason'));
|
||||
|
||||
$order->refresh();
|
||||
$this->assertNotEquals(OrderStatusEnum::CANCELLED, $order->order_status);
|
||||
}
|
||||
|
||||
/**
|
||||
* 이미 결제 가능 상태가 아닌 주문은 무시한다.
|
||||
*/
|
||||
public function test_close_report_ignores_order_that_is_no_longer_payable(): void
|
||||
{
|
||||
$order = $this->makeOrder('ORD-TOSS-CLOSE-007');
|
||||
$order->update(['order_status' => OrderStatusEnum::PAYMENT_COMPLETE->value]);
|
||||
|
||||
$response = $this->postJson(self::URL, [
|
||||
'orderId' => 'ORD-TOSS-CLOSE-007',
|
||||
'amount' => 10000,
|
||||
'buyer_email' => self::BUYER_EMAIL,
|
||||
'buyer_phone' => self::BUYER_PHONE,
|
||||
]);
|
||||
|
||||
$response->assertOk();
|
||||
$this->assertSame('ignored', $response->json('data.status'));
|
||||
$this->assertSame('order_not_payable', $response->json('data.reason'));
|
||||
}
|
||||
}
|
||||
@@ -240,6 +240,16 @@ abstract class PluginTestCase extends TestCase
|
||||
->middleware('web')
|
||||
->group($webRoutesFile);
|
||||
}
|
||||
|
||||
$apiRoutesFile = dirname(__DIR__).'/src/routes/api.php';
|
||||
|
||||
if (file_exists($apiRoutesFile)) {
|
||||
// 프로덕션 PluginRouteServiceProvider 와 동일한 프리픽스·이름 규약을 따른다.
|
||||
Route::prefix('api/plugins/sirsoft-tosspayments')
|
||||
->name('api.plugins.sirsoft-tosspayments.')
|
||||
->middleware('api')
|
||||
->group($apiRoutesFile);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -0,0 +1,100 @@
|
||||
# audit:allow test-scenario-coverage reason: 형제 결제 플러그인(nhnkcp·kginicis·nicepayments)의 security-callback-defense 와 같은 형태의 명세 SSoT. 조합 커버는 test_files 의 통과 테스트가 담당하고, 본 매니페스트는 "무엇을 반드시 담아야 하는가" 를 고정한다.
|
||||
|
||||
feature: 콜백 보안 방어 (비인증 브라우저 콜백의 주문 변조 / 소유권 검증 실패 기록)
|
||||
|
||||
description: |
|
||||
토스페이먼츠 결제 콜백 처리 경로의 주문 상태 전이 계약.
|
||||
|
||||
근본 결함: 실패 리다이렉트(`fail`)는 로그인도 서명 확인도 거치지 않는 GET 이면서
|
||||
주소에 담겨 온 `orderId` 로 주문을 찾아 결제 실패 처리했다. 주문번호만 아는 제3자가
|
||||
그 주소를 열기만 해도 남의 결제대기 주문이 취소됐다 — 보고된 NHN KCP 건보다 조건이
|
||||
가볍다(위조 암호문조차 필요 없다).
|
||||
|
||||
불변조건: **비인증 브라우저-리턴 콜백은 주문/결제 상태를 전이하지 않는다.**
|
||||
상태 전이가 허용되는 경로는 셋뿐이다 —
|
||||
(a) 서버 승인(`confirmPayment`)이 성립한 이후,
|
||||
(b) 소유권을 검증한 close-report,
|
||||
(c) 서명이 검증된 웹훅.
|
||||
|
||||
형제 대비: kcp·kginicis·nicepay 는 close-report 를 이미 갖고 있었으나 토스에는 없어,
|
||||
`fail` 에서 mutation 을 떼면 정당한 결제 실패가 어디에도 기록되지 않는 공백이 생겼다.
|
||||
그래서 형제와 동형인 소유권 검증 close-report 를 함께 신설했다(구매자 연락처 + 금액 대조).
|
||||
|
||||
축 설계: 판정에 실제로 영향을 주는 것은 "누가 불렀는가"와 "서버 승인이 성립했는가"다.
|
||||
리다이렉트 주소 커스터마이즈·쿼리 병합은 표시 계층이므로 축이 아니다.
|
||||
|
||||
axes:
|
||||
endpoint: [success_redirect, fail_redirect, close_report, webhook]
|
||||
caller: [pg_server_confirmed, unauthenticated_browser, ownership_verified_buyer, signed_webhook]
|
||||
order_owner: [self, another_user]
|
||||
order_state: [payable_pending, already_paid, no_longer_payable, not_found]
|
||||
|
||||
exclusions:
|
||||
- { endpoint: success_redirect, caller: unauthenticated_browser, reason: "성공 경로는 서버 confirmPayment 결과로만 완료되므로 호출자 축이 판정에 관여하지 않는다" }
|
||||
- { endpoint: success_redirect, caller: ownership_verified_buyer, reason: "동일 — 성공 확정은 소유권이 아니라 서버 승인이 정한다" }
|
||||
- { endpoint: success_redirect, caller: signed_webhook, reason: "성공 리다이렉트와 웹훅은 별개 엔드포인트" }
|
||||
- { endpoint: fail_redirect, caller: pg_server_confirmed, reason: "실패 리다이렉트는 서버 승인을 거치지 않는다 — 그것이 이 결함의 전제다" }
|
||||
- { endpoint: fail_redirect, caller: ownership_verified_buyer, reason: "실패 리다이렉트에는 구매자 확인 수단이 없다 — 확인은 close-report 가 한다" }
|
||||
- { endpoint: fail_redirect, caller: signed_webhook, reason: "브라우저 리턴 경로에는 서명이 없다" }
|
||||
- { endpoint: close_report, caller: pg_server_confirmed, reason: "close-report 는 결제창을 닫은 구매자가 부르는 경로" }
|
||||
- { endpoint: close_report, caller: signed_webhook, reason: "동일" }
|
||||
- { endpoint: webhook, caller: unauthenticated_browser, reason: "서명 없는 요청은 웹훅으로 수용되지 않는다" }
|
||||
- { endpoint: webhook, caller: ownership_verified_buyer, reason: "웹훅은 PG 서버가 부른다" }
|
||||
- { endpoint: webhook, caller: pg_server_confirmed, reason: "웹훅의 신뢰 근거는 승인 결과가 아니라 서명이다" }
|
||||
- { endpoint: close_report, order_owner: another_user, order_state: not_found, reason: "주문이 없으면 소유권 판정 이전에 404 로 끝난다" }
|
||||
- { endpoint: fail_redirect, order_state: not_found, order_owner: another_user, reason: "동일 — 주문이 없으면 소유권 축이 성립하지 않는다" }
|
||||
- { endpoint: success_redirect, order_owner: another_user, reason: "성공 경로의 주문은 서버 승인 응답이 지목한다 — 주소로 고를 수 없다" }
|
||||
|
||||
effects:
|
||||
# 비인증 브라우저 콜백의 주문 변조 차단
|
||||
- fail_redirect_does_not_mutate_the_order
|
||||
- unauthenticated_fail_link_cannot_cancel_another_users_order
|
||||
- fail_redirect_still_carries_error_params_to_the_checkout_screen
|
||||
- fail_redirect_handles_missing_order_id_without_error
|
||||
- fail_redirect_honors_custom_fail_url_and_existing_query_params
|
||||
|
||||
# 성공 경로 회귀 방지 (서버 승인만이 완료를 만든다)
|
||||
- success_completes_the_order_only_after_server_confirm
|
||||
- success_redirects_to_checkout_on_confirm_api_failure
|
||||
- success_redirects_to_checkout_on_amount_mismatch
|
||||
- success_redirects_to_checkout_on_order_not_found
|
||||
- success_redirect_follows_shop_route_path_setting
|
||||
|
||||
# 소유권 검증 실패 기록 (형제 플러그인과 동형으로 신설)
|
||||
- close_report_marks_pending_order_cancelled
|
||||
- close_report_records_declined_payment_with_its_code
|
||||
- close_report_rejects_buyer_mismatch
|
||||
- close_report_rejects_missing_buyer_information
|
||||
- close_report_rejects_amount_mismatch
|
||||
- close_report_returns_not_found_for_unknown_order
|
||||
- close_report_ignores_order_whose_payment_already_paid
|
||||
- close_report_ignores_order_that_is_no_longer_payable
|
||||
- close_report_restores_mileage_and_option_state_through_fail_payment
|
||||
|
||||
test_files:
|
||||
- plugins/_bundled/sirsoft-tosspayments/tests/Feature/Controllers/PaymentCallbackControllerTest.php
|
||||
- plugins/_bundled/sirsoft-tosspayments/tests/Feature/Controllers/PaymentCloseReportControllerTest.php
|
||||
|
||||
manual_verification:
|
||||
- description: "위조 실패 링크 PoC — 주소 하나로 남의 주문 취소"
|
||||
steps:
|
||||
- "피해자 계정으로 결제대기 주문 1건 생성 (pending_order / ready)"
|
||||
- "로그아웃 상태에서 `/api/plugins/sirsoft-tosspayments/payment/fail?orderId={피해주문번호}&code=...` GET"
|
||||
- "302 리다이렉트만 발생하고 주문 상태·결제 상태가 불변인지 재조회로 확인"
|
||||
- "피해자 재로그인 후 주문 상세에서 여전히 결제대기인지 확인"
|
||||
- description: "정상 실패 기록 — 소유권 검증 close-report"
|
||||
steps:
|
||||
- "구매자 본인 정보(주문 연락처)와 금액을 담아 close-report 호출 → 주문 취소 기록"
|
||||
- "같은 요청에서 연락처만 다른 사람 것으로 바꿔 호출 → 거부되고 주문 불변"
|
||||
- "취소 기록 시 선차감 마일리지 복원·옵션 취소 동기가 함께 일어나는지 확인"
|
||||
|
||||
notes: |
|
||||
`fail` 은 사용자에게 보여 줄 화면을 정하는 표시 경로다. 상태 기록은 close-report 가 맡는다.
|
||||
둘을 한 엔드포인트에 겹치면, 화면을 여는 행위가 곧 상태 변경이 되어 인증 없는 주소가
|
||||
그대로 조작 통로가 된다.
|
||||
|
||||
관련 코드:
|
||||
- src/Controllers/PaymentCallbackController.php (success / fail)
|
||||
- src/Controllers/PaymentCloseReportController.php (소유권 검증 실패 기록)
|
||||
- src/Controllers/WebhookController.php (서명 검증 웹훅)
|
||||
- 형제 참조: plugins/_bundled/sirsoft-pay_nhnkcp · sirsoft-pay_kginicis 의 close-report
|
||||
+34
@@ -189,6 +189,40 @@ class KcpCallbackResolverTest extends PluginTestCase
|
||||
Http::assertNothingSent();
|
||||
}
|
||||
|
||||
/**
|
||||
* 브라우저 실패 코드만으로는 대상 인증을 고를 수 없다.
|
||||
*
|
||||
* 결제 콜백은 주문번호가 사실상 공개값이라 공격자가 피해 대상을 지목할 수 있었지만
|
||||
* (KVE-2026-2018), 이 콜백은 거래를 `reg_cert_key`(KCP 발급 비밀) 또는 challenge UUID
|
||||
* 로만 찾는다. 둘 다 추측할 수 없으므로 res_cd 를 위조해도 남의 인증 로그에 닿지 못한다.
|
||||
* 이 성질이 깨지면 여기도 결제 콜백과 같은 통로가 된다.
|
||||
*/
|
||||
public function test_forged_failure_callback_cannot_select_another_users_verification(): void
|
||||
{
|
||||
$log = $this->createChallenge(User::factory()->create()->id);
|
||||
Http::fake();
|
||||
|
||||
// 공격자는 비밀값을 모르므로 임의 키·임의 challenge id 로 시도할 수밖에 없다.
|
||||
foreach ([
|
||||
['res_cd' => '9999', 'reg_cert_key' => 'GUESSED-KEY'],
|
||||
['res_cd' => 'CS12', 'param_opt_1' => (string) Str::uuid()],
|
||||
['res_cd' => '9999'],
|
||||
] as $forged) {
|
||||
$outcome = $this->resolver->resolve($forged);
|
||||
|
||||
$this->assertFalse($outcome->success);
|
||||
$this->assertSame('NOT_FOUND', $outcome->failureCode);
|
||||
}
|
||||
|
||||
// 피해자의 인증 로그는 그대로 남아 있어야 한다.
|
||||
$this->assertSame(
|
||||
IdentityVerificationStatus::Sent->value,
|
||||
$this->logRepository->findById($log->id)->status->value,
|
||||
'위조 콜백이 타인의 인증 로그 상태를 바꿨습니다.'
|
||||
);
|
||||
Http::assertNothingSent();
|
||||
}
|
||||
|
||||
/**
|
||||
* @scenario outcome=provider_error,lookup=by_reg_cert_key,missing_field=none
|
||||
*
|
||||
|
||||
Reference in new issue
Block a user