fix(core,board,ecommerce,payments,basic): KVE-2026 보안 게이트 6묶음 + 자격증명 전송로 정합
KISA 제보 취약점(KVE-2026-1914/1919/2019/2029/2041/2042/2043/2044)과 그 수정 과정에서 드러난 자격증명 전송로 결함을 함께 해소한다. globalHeaders 는 데이터소스와 apiCall 핸들러에만 적용되는데, 코어 ApiClient 를 직접 부르는 경로들이 그 사실을 모른 채 게이트된 엔드포인트를 호출하고 있었다. 서버는 정당한 사용자를 거부하고 화면은 이미 버튼을 내준 뒤라, 예외도 로그도 없이 그 자리만 비는 형태로만 드러났다. 전송로 10축을 전수 열거해 6건을 고치고, 같은 실수가 반복되지 않도록 규정과 coverage 에 등재했다. 아웃바운드 프록시가 사이트 자기 자신으로 가는 내부 요청까지 가로채 저장이 수십 초씩 걸리던 문제도 함께 고쳤다. 실패가 폴백으로 삼켜져 화면에는 지연으로만 나타났다.
This commit is contained in:
1 parent
8f072895ff
commit
9cf9c3ff8c
104 files changed
+4522
-412
No files matched your search
@@ -149,8 +149,8 @@ OS 판별 후 `executeCliWindows()`/`executeCliLinux()` 로 분기 → CLI 인
|
||||
<!-- @generated:test-commands START — ext:docgen 이 갱신. 이 블록 안은 직접 수정하지 않는다 -->
|
||||
| 종류 | 개수 | 위치 |
|
||||
|---|---|---|
|
||||
| PHPUnit | 28개 | `plugins/_bundled/sirsoft-pay_nhnkcp/tests` |
|
||||
| Vitest | 8개 | `vitest.config.ts` |
|
||||
| PHPUnit | 29개 | `plugins/_bundled/sirsoft-pay_nhnkcp/tests` |
|
||||
| Vitest | 9개 | `vitest.config.ts` |
|
||||
| Playwright | 0개 | — |
|
||||
| 시나리오 매니페스트 | 1개 | `tests/scenarios` |
|
||||
|
||||
|
||||
@@ -6,8 +6,13 @@
|
||||
|
||||
## [1.0.4] - 2026-09-04
|
||||
|
||||
### Fixed
|
||||
|
||||
- 비회원으로 결제하신 손님이 주문완료 화면과 비회원 주문 상세 화면에서 영수증 버튼과 결제수단 표시를 볼 수 없던 문제를 고쳤습니다. 서버는 비회원 주문을 확인해 줄 준비가 되어 있었는데 화면이 확인값을 함께 보내지 않아 조회 자체가 되지 않았고, 오류 메시지도 남지 않아 원인을 알기 어려웠습니다.
|
||||
|
||||
### Security
|
||||
|
||||
- 모바일 가상계좌 결제에서 제3자가 입금 계좌를 자기 계좌로 바꿔치기할 수 있던 문제를 수정했습니다. 모바일은 결제사가 계좌 정보를 브라우저를 거쳐 그대로 전달하는 방식이라, 주문번호만 아는 사람이 위조한 계좌 정보를 보내면 그 주문의 입금 계좌가 바뀌어 구매자가 엉뚱한 곳으로 입금할 수 있었습니다. 이제 결제창을 열 때 본인 확인을 거쳐 발급한 일회용 확인값을 결제사를 통해 되돌려 받아 대조하며, 확인값이 없거나 맞지 않는 요청은 주문을 전혀 건드리지 않고 결제 화면으로 되돌립니다. 확인값은 한 번 쓰면 소멸하므로 같은 값을 다시 보내도 통하지 않습니다. PC 결제는 종전처럼 결제사 서버 확인을 거칩니다. 업데이트를 적용하는 순간 이미 결제창이 열려 있던 모바일 가상계좌 결제 건은 확인값이 없어 실패로 처리되므로, 결제가 몰리지 않는 시간에 적용하시고 적용 직후 결제 실패 건이 있으면 확인해 주세요. (KISA 측에서 제보해주셨습니다 — KVE-2026-2019)
|
||||
- 결제창 프로그램을 불러오는 주소가 NHN KCP 의 주소인지 불러오기 직전에 확인합니다. 확인되지 않는 주소면 결제를 진행하지 않고 안내를 표시합니다.
|
||||
- 제3자가 남의 주문번호만 알면 결제창을 거치지 않고도 그 주문을 취소시킬 수 있던 문제를 수정했습니다. 결제 결과 콜백은 로그인도 서명 확인도 거치지 않는 경로여서, 위조한 결제 정보를 보내 승인을 일부러 실패시키면 그 주문이 결제 실패로 처리되었습니다. 이제 실제 결제 승인이 이루어진 뒤의 실패만 주문에 반영하며, 승인 전 단계의 실패는 결제 화면으로 되돌려 보내기만 합니다. 구매자가 결제창을 닫아 생기는 정상적인 결제 실패는 종전처럼 기록됩니다. (KISA 측에서 제보해주셨습니다 — KVE-2026-2018)
|
||||
- 같은 결제 결과 콜백에서 가상계좌 경로를 통해서도 남의 주문을 건드릴 수 있던 문제를 수정했습니다. 결제수단을 가상계좌라고 주장하는 값을 요청에 섞으면, 카드로 주문한 건도 결제사 확인을 거치지 않는 경로로 흘러 그 주문이 취소되거나 위조된 입금 계좌가 그 주문에 기록될 수 있었습니다. 이제 결제수단은 요청에 실려 온 값이 아니라 주문에 저장된 값으로만 판단하며, 가상계좌 발급이 확인되지 않은 경우에는 주문을 그대로 두고 결제 화면으로 되돌려 보냅니다.
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
(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 I="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(I,JSON.stringify(e))}catch{}}function re(){const e=M();if(e)try{e.removeItem(I)}catch{}}function qe(){const e=M();if(!e)return null;try{const t=e.getItem(I);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"}const ze=["testpay.kcp.co.kr","pay.kcp.co.kr"];function Je(e,t){const n=window?.G7Core?.t;if(typeof n!="function")return t;const o=`sirsoft-pay_nhnkcp.${e}`,r=n(o);return typeof r=="string"&&r!==o?r:t}function Ve(e){let t=null;try{t=new URL(e)}catch{t=null}if(t===null||t.protocol!=="https:"||!ze.includes(t.hostname.toLowerCase()))throw new Error(Je("payment.error.sdk_url_untrusted","결제 모듈 주소가 올바르지 않아 결제를 진행할 수 없습니다."))}function Qe(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 Xe(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 Ze={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 et(e,t){const n=e.toLowerCase();return!t||!Object.prototype.hasOwnProperty.call(se,n)?{}:{param_opt_1:n,nhnkcp_easy_pay_method:n}}function tt(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 nt(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||!tt(e)||(a(),t())},i=document.body??document.documentElement;return i&&typeof MutationObserver<"u"&&(r=new MutationObseLine 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 je(e){return e.trim().slice(0,160)}function Be(e){if(e)return e.replace(/\/payment\/close-report$/,"/payment/retry")}async function oe(e,t,n=!1){const r=window.G7Core?.api;if(typeof r?.post=="function"){await r.post(e,t);return}const o=await fetch(De(e),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t),keepalive:n});if(!o.ok){let a=`NHN KCP payment request failed (${o.status})`;try{const s=await o.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 He(e){const t=Be(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 T="g7:sirsoft-pay_nhnkcp:pendingClose";function M(){try{return window.sessionStorage??null}catch{return null}}function Fe(e){const t=M();if(t)try{t.setItem(T,JSON.stringify(e))}catch{}}function ae(){const e=M();if(e)try{e.removeItem(T)}catch{}}function Ge(){const e=M();if(!e)return null;try{const t=e.getItem(T);if(!t)return null;const n=JSON.parse(t);return n&&typeof n.oid=="string"&&n.oid!==""?n:null}catch{return null}}async function Ue(){const e=Ge();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)){ae();return}const r=t.get("error")??"",o=t.get("message")??"";r===""&&n===""||(ae(),await se(e,o!==""?o:r))}async function se(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:je(t)||"kcp-window-closed"};try{await oe(e.closeReportUrl,n,!0)}catch(r){console.warn("[sirsoft-pay_nhnkcp] failed to report payment window close",r)}}const qe="nhnkcp_applepay";function R(e){return e===qe}function x(){if(typeof navigator>"u")return!1;const e=navigator,t=(e.userAgent||"").toLowerCase(),n=((e.userAgentData?.platform??e.platform)||"").toLowerCase(),r=e.maxTouchPoints??0;return/iphone|ipad|ipod/.test(t)||/iphone|ipad|ipod|ios/.test(n)?!0:/macintosh|mac os x/.test(t)&&r>1}function L(){return((typeof document<"u"?document.documentElement.lang:"")||"").toLowerCase().startsWith("ko")?"애플페이는 IOS 기기에 모바일결제만 가능합니다.":"Apple Pay is available only for mobile payments on iOS devices."}function O(e){return(e??"KRW").trim().toUpperCase()||"KRW"}function Ye(e){return O(e)==="KRW"}const We=["testpay.kcp.co.kr","pay.kcp.co.kr"];function ze(e,t){const n=window?.G7Core?.t;if(typeof n!="function")return t;const r=`sirsoft-pay_nhnkcp.${e}`,o=n(r);return typeof o=="string"&&o!==r?o:t}function Je(e){let t=null;try{t=new URL(e)}catch{t=null}if(t===null||t.protocol!=="https:"||!We.includes(t.hostname.toLowerCase()))throw new Error(ze("payment.error.sdk_url_untrusted","결제 모듈 주소가 올바르지 않아 결제를 진행할 수 없습니다."))}function Ve(e){const t=O(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 r=Math.max(0,Math.round(Number(e.tax_amount??0))),o=Math.max(0,Math.round(Number(e.vat_amount??0))),a=Math.max(0,t-n),s=a>0&&r>0&&o>0?Math.min(a,Math.round(a*(o/r))):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 Xe={card:"100000000000",bank_transfer:"010000000000",virtual_account:"001000000000",mobile:"000010000000",bank:"010000000000",vbank:"001000000000",phone:"000010000000"},ie={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 Ze(e,t){const n=e.toLowerCase();return!t||!Object.prototype.hasOwnProperty.call(ie,n)?{}:{param_opt_1:n,nhnkcp_easy_pay_method:n}}function et(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 tt(e,t){let n=!1,r,o;const a=()=>{n=!0,o&&(o.disconnect(),o=void 0),r!==void 0&&(window.clearInterval(r),r=void 0)},s=()=>{n||!et(e)||(a(),t())},i=document.body??document.documentElement;return i&&typeof MutationObserver<"u"&&(o=new MutationObseLine 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>`),ee.close(),y=window.setTimeout(()=>{N(new Error("KCP SDK load timeout"))},15e3),f.__kcpReady=()=>{y!==void 0&&(clearTimeout(y),y=void 0)}})}const it={nhnkcp_payco:"PAYCO",nhnkcp_naverpay:"네이버페이",nhnkcp_naverpay_point:"네이버페이 포인트",nhnkcp_kakaopay:"카카오페이",nhnkcp_applepay:"Apple Pay"},ct="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 dt(e){const t=ie();if(!t)return;const n=it[e];t.querySelectorAll("button").forEach(o=>{o.textContent?.trim()===n?(o.style.boxShadow=ct,o.style.outline="none"):(o.style.boxShadow="",o.style.outline="")})}function lt(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?dt(t):ce()}function ut(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 pt(e){const t=String(e.params?.text??"");if(t!==""){if(navigator.clipboard&&typeof navigator.clipboard.writeText=="function"){await navigator.clipboard.writeText(t);return}ut(t)}}const de={requestPayment:rt,setPaymentMethod:lt,copyToClipboard:pt},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 mt(e){return typeof e=="string"?e:e instanceof URL?e.toString():typeof Request<"u"&&e instanceof Request?e.url:String(e)}function ft(e,t){return t?.method?t.method.toUpperCase():typeof Request<"u"&&e instanceof Request?e.method.toUpperCase():"GET"}function yt(e,t){if(t!=="POST")return!1;const n=e.split("?")[0].split("#")[0];return n===le||n.endsWith(le)}function ht(e){try{return JSON.parse(e).payment_method}catch{return}}function _t(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 gt(){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=mt(r),i=ft(r,a);if(!yt(s,i))return n(r,a);let c;if(a?.body&&typeof a.body=="string"&&(c=ht(a.body)),T(c)&&!x()){const d=R();return ue.warn(d),_t(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",wt=/^\/shop\/orders\/([^/]+)\/complete$/;function fe(){return localStorage.getItem("auth_token")}async function bt(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 kt(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 Ct(e){if(document.getElementById(me))return;const t=await bt(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);kt(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
|
||||
</body></html>`),te.close(),y=window.setTimeout(()=>{A(new Error("KCP SDK load timeout"))},15e3),f.__kcpReady=()=>{y!==void 0&&(clearTimeout(y),y=void 0)}})}const st={nhnkcp_payco:"PAYCO",nhnkcp_naverpay:"네이버페이",nhnkcp_naverpay_point:"네이버페이 포인트",nhnkcp_kakaopay:"카카오페이",nhnkcp_applepay:"Apple Pay"},it="0 0 0 2px #ffffff, 0 0 0 5px rgba(0,0,0,0.55)";function ce(){return document.querySelector(".nhnkcp-easy-pay-btns")??null}function de(){const e=ce();e&&e.querySelectorAll("button").forEach(t=>{t.style.boxShadow="",t.style.outline=""})}function ct(e){const t=ce();if(!t)return;const n=st[e];t.querySelectorAll("button").forEach(r=>{r.textContent?.trim()===n?(r.style.boxShadow=it,r.style.outline="none"):(r.style.boxShadow="",r.style.outline="")})}function dt(e){const t=e.params?.paymentMethod;if(!t)return;const n=window.G7Core;if(R(t)&&!x()){const o=L();n?.state?.setLocal?.({paymentErrorMessage:o,isSubmittingOrder:!1}),n?.modal?.open?.("nhnkcp_payment_error_modal"),de();return}const r=typeof t=="string"&&t.startsWith("nhnkcp_");n?.state?.setLocal?.({paymentMethod:t}),r?ct(t):de()}function lt(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 ut(e){const t=String(e.params?.text??"");if(t!==""){if(navigator.clipboard&&typeof navigator.clipboard.writeText=="function"){await navigator.clipboard.writeText(t);return}lt(t)}}const le={requestPayment:rt,setPaymentMethod:dt,copyToClipboard:ut},ue="/api/modules/sirsoft-ecommerce/user/orders",K="sirsoft-pay_nhnkcp",pe={info:(...e)=>console.info(`[${K}]`,...e),warn:(...e)=>console.warn(`[${K}]`,...e),error:(...e)=>console.error(`[${K}]`,...e)};function pt(e){return typeof e=="string"?e:e instanceof URL?e.toString():typeof Request<"u"&&e instanceof Request?e.url:String(e)}function mt(e,t){return t?.method?t.method.toUpperCase():typeof Request<"u"&&e instanceof Request?e.method.toUpperCase():"GET"}function ft(e,t){if(t!=="POST")return!1;const n=e.split("?")[0].split("#")[0];return n===ue||n.endsWith(ue)}function yt(e){try{return JSON.parse(e).payment_method}catch{return}}function ht(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 _t(){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(o,a){const s=pt(o),i=mt(o,a);if(!ft(s,i))return n(o,a);let c;if(a?.body&&typeof a.body=="string"&&(c=yt(a.body)),R(c)&&!x()){const d=L();return pe.warn(d),ht(d)}return n(o,a)},pe.info("order request interceptor installed (Apple Pay device guard)")}function gt(){return localStorage.getItem("auth_token")}function wt(){try{const t=sessionStorage.getItem("g7_guest_order_token");if(t)return t}catch{}const e=window.G7Core?.state?.get?.("_global")?.guestOrderToken;return typeof e=="string"&&e!==""?e:null}function v(){const e=gt(),t=wt();if(!e&&!t)return null;const n={Accept:"application/json"};return e?n.Authorization=`Bearer ${e}`:t&&(n["X-Guest-Order-Token"]=t),n}const D="sirsoft-pay_nhnkcp",me="__kcpOcReceiptInjectorInstalled",fe="kcp-oc-receipt-btn",bt=/^\/shop\/orders\/([^/]+)\/complete$/;async function kt(e){const t=v();if(!t)return null;try{const n=await fetch(`/api/modules/sirsoft-ecommerce/user/orders/${e}`,{headers:t,credentials:"same-origin"});return n.ok?(await n.json())?.data?.payment??null:null}catch{return null}}async function j(e){const t=v();if(!t)return null;try{const n=await fetch(`/api/plugins/${D}/user/orders/${e}/receipt`,{headers:t,credentials:"same-origin"});return n.ok?await n.json():null}catch{return null}}function ye(e,t,n){const r=document.createElement("button");return r.type="button",r.className=t,r.textContent=e,r.addEventListener("click",()=>n(r)),r}function Ct(e){if(!e)return!1;const t=Array.from(document.querySelectorAll("div"));for(const n of t){const r=Array.from(n.children).filter(s=>s instanceof HTMLElement&&s.tagName==="SPAN");if(r.length<2)continue;const o=r[0].textContent?.trim();if(o!=="결제 방법"&&o!=="결제수단"&&o!=="결제 방식")continue;const a=r[r.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 xt(e){if(document.getElementById(fe))return;const t=await kt(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 r=await j(e);Ct(r?.payment_method_display_label);const o=n.parentEleLine truncated
|
||||
@@ -179,13 +179,14 @@ PC 표준결제창에서 사용자가 결제를 완료하지 않고 창을 닫
|
||||
| good_mny | numeric | 아니오 | 결제 금액 (min 1) |
|
||||
| use_pay_method | string | 아니오 | 사용된 결제수단 |
|
||||
| nhnkcp_easy_pay_method | string | 아니오 | 간편결제 수단 식별값 (max 50) |
|
||||
| param_opt_2 | string | 아니오 | 모바일 가상계좌 세션 확인값 (max 50). 승인키 발급 시점에 실어 보낸 일회성 값을 KCP 가 그대로 되돌려준다 — 모바일 가상계좌 분기는 이 값이 주문에 저장된 값과 일치할 때만 계좌를 저장한다 |
|
||||
| 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`.
|
||||
고정 `error` 값: `amount_mismatch` · `callback_locked` · `cli_exception` · `confirm_failed` · `currency_not_supported` · `invalid_payment_currency` · `order_not_found` · `order_not_retryable` · `vbank_save_failed` · `vbank_session_mismatch`.
|
||||
|
||||
이 밖에 KCP 가 돌려준 결과코드(`res_cd`)가 그대로 실리는 분기가 있다. 화면이 `error` 로 분기할 때는 위 고정값만 신뢰하고, 그 밖의 값은 미확정 실패로 다룬다.
|
||||
|
||||
@@ -196,3 +197,5 @@ KCP 표준결제창이 인증을 마치고 브라우저를 통해 가맹점으
|
||||
이 문서 상단 **"주문 상태를 바꾸는 경로는 하나뿐이다"** 가 이 엔드포인트의 핵심 계약이다 — 승인 전에 판정되는 실패(금액 불일치·인증 결과코드 비정상)에서는 주문 상태를 바꾸지 않는다. 승인이 이미 일어난 뒤(`tno` 존재)의 실패만 주문에 반영하고, 그 경우 KCP 측에 잔존한 승인을 자동 취소한다.
|
||||
|
||||
이 엔드포인트를 수정할 때는 실패 분기마다 **"이 판정의 근거가 브라우저가 보낸 값인가"** 를 먼저 확인한다. 근거가 브라우저 입력뿐이면 주문 상태를 바꾸지 않는다.
|
||||
|
||||
모바일 가상계좌 분기는 서버-서버 승인이 없어 계좌 정보의 유일한 출처가 브라우저 평문이다. 그래서 평문을 읽기 **전에** `param_opt_2` 가 주문에 저장된 세션 확인값과 일치하는지 대조하고, 일치하지 않으면 `vbank_session_mismatch` 로 되돌린다. 확인값은 저장 시 소멸하므로 같은 값으로 다시 올 수 없다. 발급 지점은 [vbank.md](vbank.md) 참조.
|
||||
@@ -33,6 +33,23 @@
|
||||
|
||||
---
|
||||
|
||||
## 모바일 가상계좌 세션 확인값
|
||||
|
||||
모바일(SmartPhone Pay) 가상계좌는 PC 와 달리 **서버-서버 승인이 없다**. KCP 가 계좌번호를 브라우저 평문 POST 로만 전달하므로, 콜백만으로는 그 값이 KCP 에서 온 것인지 확인할 수 없다.
|
||||
|
||||
그래서 승인키 발급(`POST /api/plugins/sirsoft-pay_nhnkcp/mobile/approval-key`, 구매자 인증 필요)이 가상계좌 요청일 때 일회성 확인값을 만들어 주문에 저장하고, 결제창 필드 `param_opt_2` 로 실어 보낸다. KCP 는 이 값을 콜백에 그대로 되돌려주므로 콜백은 저장된 값과 대조한 뒤에만 계좌를 저장한다.
|
||||
|
||||
| 항목 | 값 |
|
||||
| --- | --- |
|
||||
| 결제창 필드 | `param_opt_2` (가상계좌 요청에만 부여) |
|
||||
| 콜백 수신 필드 | `param_opt_2` (string, max 50) |
|
||||
| 불일치·부재 시 | 주문 상태 **무변경** + 실패 리다이렉트 `error=vbank_session_mismatch` |
|
||||
| 재사용 | 불가 — 계좌 저장 시 확인값이 소멸한다 |
|
||||
|
||||
`param_opt_1` 은 간편결제 수단 식별자가 이미 점유하고 있으므로 `param_opt_2` 를 쓴다. PC 분기(`enc_data` 존재)는 서버 승인으로 검증되므로 이 대조 대상이 아니다.
|
||||
|
||||
---
|
||||
|
||||
## 결제 실패 리다이렉트 규약 (브라우저 콜백)
|
||||
|
||||
결제창에서 돌아오는 브라우저 콜백은 JSON 응답이 아니라 상점 실패 페이지로 **리다이렉트**하며, 실패 사유를 쿼리스트링으로 전달합니다.
|
||||
|
||||
@@ -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:278` |
|
||||
| `sirsoft-pay_nhnkcp.payment.after_confirm` | action | KCP 결제 승인 확인 완료 후 | `src/Controllers/PaymentCallbackController.php:280` |
|
||||
| `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:273` |
|
||||
| `sirsoft-pay_nhnkcp.payment.before_confirm` | action | KCP 결제 승인 확인 전 | `src/Controllers/PaymentCallbackController.php:275` |
|
||||
<!-- @generated:hooks-published END -->
|
||||
|
||||
<!-- @intent START -->
|
||||
|
||||
@@ -83,3 +83,22 @@ KCP 가 제공하는 `payplus_web.jsp` SDK 는 이 목록에 없습니다 — `r
|
||||
그리고, 이 플러그인은 간편결제 버튼·복사 버튼 같은 최소한의 UI만 코어 컴포넌트로
|
||||
구성하기 때문입니다.
|
||||
<!-- @intent END -->
|
||||
|
||||
## 비회원 주문의 자격 증명
|
||||
|
||||
<!-- @intent START -->
|
||||
영수증·결제수단 표시는 주문 정보를 서버에서 다시 조회해 만든다. 이 요청은 레이아웃의
|
||||
`globalHeaders` 배선을 타지 않는 직접 호출(`fetch`)이므로, 자격 증명을 호출부가 직접 실어야 한다.
|
||||
|
||||
- 회원: `Authorization: Bearer …`
|
||||
- 비회원: `X-Guest-Order-Token: …` (코어 storageHandlers 가 sessionStorage 에 저장, 전역 상태 폴백)
|
||||
|
||||
두 경로 모두 `resources/js/guestOrderToken.ts` 의 `buildOrderRequestHeaders()` 한 곳을 거친다.
|
||||
비회원 분기를 비우면 서버는 그 주문을 찾을 수 없다고 응답하고, 화면에는 영수증 버튼이 아예
|
||||
나타나지 않는다 — 예외도 콘솔 오류도 남지 않아 운영자가 원인을 알 수 없다. 서버(`UserReceiptController`)는
|
||||
비회원을 이미 지원하므로, 이 배선이 빠지면 서버 기능이 도달 불가 상태로만 남는다.
|
||||
|
||||
주문 상세 화면의 경로 판정(`ORDER_SHOW_RE`)도 회원(`/mypage/orders/{N}`)과
|
||||
비회원(`/shop/guest/orders/{N}`) 두 주소를 함께 매칭해야 한다. 한쪽을 빼면 그 화면에서는
|
||||
조회가 시작조차 되지 않는다.
|
||||
<!-- @intent END -->
|
||||
@@ -0,0 +1,94 @@
|
||||
/**
|
||||
* 비회원 주문 조회 토큰 배선 검증 (NHN KCP)
|
||||
*
|
||||
* 서버는 `X-Guest-Order-Token` 으로 비회원 주문 소유자를 확인한다. 화면이 그 값을
|
||||
* 보내지 않으면 서버는 주문을 찾지 못하고, 비회원 손님에게는 영수증 버튼이 아예
|
||||
* 나타나지 않는다 — 예외도 콘솔 오류도 남지 않아 원인을 알 수 없는 결함이라 구조로 잠근다.
|
||||
*
|
||||
* @scenario actor=guest, surface=receipt_injector
|
||||
*
|
||||
* @effects guest_order_token_header_built,guest_order_detail_route_matched
|
||||
*/
|
||||
|
||||
import { describe, it, expect, beforeEach, afterEach } from 'vitest';
|
||||
import { readFileSync } from 'node:fs';
|
||||
import { resolve } from 'node:path';
|
||||
|
||||
import { buildOrderRequestHeaders, getGuestOrderToken } from '../guestOrderToken';
|
||||
|
||||
const JS = resolve(__dirname, '..');
|
||||
|
||||
beforeEach(() => {
|
||||
localStorage.clear();
|
||||
sessionStorage.clear();
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
delete (window as any).G7Core;
|
||||
});
|
||||
|
||||
describe('buildOrderRequestHeaders', () => {
|
||||
it('회원 토큰이 있으면 Authorization 을 쓴다', () => {
|
||||
localStorage.setItem('auth_token', 'member-token');
|
||||
|
||||
expect(buildOrderRequestHeaders()).toEqual({
|
||||
Accept: 'application/json',
|
||||
Authorization: 'Bearer member-token',
|
||||
});
|
||||
});
|
||||
|
||||
it('회원 토큰이 없고 비회원 토큰이 있으면 X-Guest-Order-Token 을 쓴다', () => {
|
||||
sessionStorage.setItem('g7_guest_order_token', 'guest-token');
|
||||
|
||||
expect(buildOrderRequestHeaders()).toEqual({
|
||||
Accept: 'application/json',
|
||||
'X-Guest-Order-Token': 'guest-token',
|
||||
});
|
||||
});
|
||||
|
||||
it('둘 다 없으면 null 을 돌려준다 (호출 자체를 막는다)', () => {
|
||||
expect(buildOrderRequestHeaders()).toBeNull();
|
||||
});
|
||||
|
||||
it('sessionStorage 가 비어도 전역 상태 폴백을 본다', () => {
|
||||
(window as any).G7Core = {
|
||||
state: { get: (k: string) => (k === '_global' ? { guestOrderToken: 'global-token' } : undefined) },
|
||||
};
|
||||
|
||||
expect(getGuestOrderToken()).toBe('global-token');
|
||||
});
|
||||
});
|
||||
|
||||
describe('영수증 화면 배선', () => {
|
||||
it.each(['orderCompleteReceiptInjector.ts', 'mypageOrderShowInjector.ts'])(
|
||||
'%s 가 비회원 토큰 헤더를 경유한다',
|
||||
(file) => {
|
||||
const source = readFileSync(resolve(JS, file), 'utf-8');
|
||||
|
||||
expect(
|
||||
source.includes('buildOrderRequestHeaders'),
|
||||
`${file} 가 비회원 토큰을 싣지 않습니다 — 비회원 손님에게 영수증 버튼이 나타나지 않습니다.`
|
||||
).toBe(true);
|
||||
|
||||
expect(
|
||||
/localStorage\.getItem\('auth_token'\)/.test(source),
|
||||
`${file} 에 회원 전용 토큰 조회가 남아 있습니다 — 비회원 분기가 다시 막힙니다.`
|
||||
).toBe(false);
|
||||
}
|
||||
);
|
||||
|
||||
it('주문 상세 경로 판정이 비회원 주소도 매칭한다', () => {
|
||||
const source = readFileSync(resolve(JS, 'mypageOrderShowInjector.ts'), 'utf-8');
|
||||
const match = source.match(/const ORDER_SHOW_RE = (\/.+\/);/);
|
||||
|
||||
expect(match, '주문 상세 경로 정규식을 찾지 못했습니다.').not.toBeNull();
|
||||
|
||||
const re = new RegExp(match![1].slice(1, -1));
|
||||
|
||||
expect(re.test('/mypage/orders/12'), '회원 주문 상세 경로가 매칭되지 않습니다.').toBe(true);
|
||||
expect(
|
||||
re.test('/shop/guest/orders/20260904-0001'),
|
||||
'비회원 주문 상세 경로가 매칭되지 않습니다 — 그 화면에서는 영수증이 조회조차 되지 않습니다.'
|
||||
).toBe(true);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,62 @@
|
||||
/**
|
||||
* 비회원 주문 조회 토큰 확보 (플러그인 공용)
|
||||
*
|
||||
* 비회원 주문의 영수증·결제수단 정보는 서버가 `X-Guest-Order-Token` 으로 소유자를
|
||||
* 확인한다. 이 토큰을 싣지 않으면 서버는 그 주문을 찾을 수 없다고 응답하므로,
|
||||
* 비회원 손님에게는 영수증 버튼이 아예 나타나지 않는다 — 예외도 콘솔 오류도 남지
|
||||
* 않아 운영자가 원인을 알 수 없다.
|
||||
*
|
||||
* 코어 storageHandlers 가 sessionStorage 에 저장하며, 그 접근이 막힌 환경
|
||||
* (프라이빗 창·iframe)을 위해 전역 상태 폴백을 함께 본다.
|
||||
*/
|
||||
|
||||
/**
|
||||
* 회원 인증 토큰을 돌려줍니다.
|
||||
*
|
||||
* @return 토큰 또는 null
|
||||
*/
|
||||
export function getAuthToken(): string | null {
|
||||
return localStorage.getItem('auth_token');
|
||||
}
|
||||
|
||||
/**
|
||||
* 비회원 주문 조회 토큰을 돌려줍니다.
|
||||
*
|
||||
* @return 토큰 또는 null
|
||||
*/
|
||||
export function getGuestOrderToken(): string | null {
|
||||
try {
|
||||
const sessionToken = sessionStorage.getItem('g7_guest_order_token');
|
||||
if (sessionToken) return sessionToken;
|
||||
} catch {
|
||||
// sessionStorage 접근 불가 환경 — 전역 상태 폴백으로 진행
|
||||
}
|
||||
|
||||
const globalToken = (window as any).G7Core?.state?.get?.('_global')?.guestOrderToken;
|
||||
|
||||
return typeof globalToken === 'string' && globalToken !== '' ? globalToken : null;
|
||||
}
|
||||
|
||||
/**
|
||||
* 주문 조회 요청 헤더를 만듭니다. 회원 토큰을 우선하고, 없으면 비회원 토큰을 씁니다.
|
||||
*
|
||||
* @return 헤더 객체. 둘 다 없으면 null (호출 자체를 하지 않아야 함)
|
||||
*/
|
||||
export function buildOrderRequestHeaders(): Record<string, string> | null {
|
||||
const authToken = getAuthToken();
|
||||
const guestToken = getGuestOrderToken();
|
||||
|
||||
if (!authToken && !guestToken) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const headers: Record<string, string> = { Accept: 'application/json' };
|
||||
|
||||
if (authToken) {
|
||||
headers.Authorization = `Bearer ${authToken}`;
|
||||
} else if (guestToken) {
|
||||
headers['X-Guest-Order-Token'] = guestToken;
|
||||
}
|
||||
|
||||
return headers;
|
||||
}
|
||||
@@ -1,10 +1,14 @@
|
||||
import { buildOrderRequestHeaders } from './guestOrderToken';
|
||||
|
||||
const PLUGIN_ID = 'sirsoft-pay_nhnkcp';
|
||||
const FLAG = '__kcpMpShowInjectorInstalled';
|
||||
const VBANK_ID = 'kcp-mp-vbank-row';
|
||||
const ROW_ID = 'kcp-mp-receipt-row';
|
||||
const MOCK_DEPOSIT_ID = 'kcp-mp-mock-deposit';
|
||||
|
||||
const ORDER_SHOW_RE = /^\/mypage\/orders\/([^/]+)$/;
|
||||
// 회원 마이페이지(/mypage/orders/{N}) 와 비회원 주문 상세(/shop/guest/orders/{N}) 를 함께 매칭한다.
|
||||
// 비회원 경로를 빼면 그 화면에서는 영수증 정보가 조회조차 되지 않는다 (서버는 지원한다).
|
||||
const ORDER_SHOW_RE = /^(?:\/mypage\/orders\/([^/]+)|\/shop\/guest\/orders\/([^/]+))$/;
|
||||
|
||||
interface Payment {
|
||||
pg_provider?: string;
|
||||
@@ -38,9 +42,6 @@ function getOrderFromState(orderNumber: string): OrderData | null {
|
||||
}
|
||||
}
|
||||
|
||||
function getToken(): string | null {
|
||||
return localStorage.getItem('auth_token');
|
||||
}
|
||||
|
||||
interface ReceiptInfo {
|
||||
receipt_url?: string;
|
||||
@@ -49,11 +50,12 @@ interface ReceiptInfo {
|
||||
}
|
||||
|
||||
async function fetchReceiptUrls(orderNumber: string): Promise<ReceiptInfo | null> {
|
||||
const token = getToken();
|
||||
if (!token) return null;
|
||||
const headers = buildOrderRequestHeaders();
|
||||
if (!headers) return null;
|
||||
try {
|
||||
const res = await fetch(`/api/plugins/${PLUGIN_ID}/user/orders/${orderNumber}/receipt`, {
|
||||
headers: { Authorization: `Bearer ${token}`, Accept: 'application/json' },
|
||||
headers,
|
||||
credentials: 'same-origin',
|
||||
});
|
||||
if (!res.ok) return null;
|
||||
return (await res.json()) as ReceiptInfo;
|
||||
@@ -72,11 +74,12 @@ interface MockDepositInfo {
|
||||
}
|
||||
|
||||
async function fetchMockDepositInfo(orderNumber: string): Promise<MockDepositInfo | null> {
|
||||
const token = getToken();
|
||||
if (!token) return null;
|
||||
const headers = buildOrderRequestHeaders();
|
||||
if (!headers) return null;
|
||||
try {
|
||||
const res = await fetch(`/api/plugins/${PLUGIN_ID}/user/orders/${orderNumber}/vbank-mock-deposit-info`, {
|
||||
headers: { Authorization: `Bearer ${token}`, Accept: 'application/json' },
|
||||
headers,
|
||||
credentials: 'same-origin',
|
||||
});
|
||||
if (!res.ok) return null;
|
||||
return (await res.json()) as MockDepositInfo;
|
||||
@@ -381,7 +384,9 @@ function startPolling(orderNumber: string): void {
|
||||
|
||||
function onRouteChange(): void {
|
||||
const match = location.pathname.match(ORDER_SHOW_RE);
|
||||
if (match) startPolling(match[1]);
|
||||
// 회원 그룹(match[1]) 또는 비회원 그룹(match[2]) 중 한쪽이 채워진다.
|
||||
const segment = match?.[1] ?? match?.[2];
|
||||
if (segment) startPolling(segment);
|
||||
}
|
||||
|
||||
export function installMypageOrderShowInjector(): void {
|
||||
|
||||
@@ -1,3 +1,5 @@
|
||||
import { buildOrderRequestHeaders } from './guestOrderToken';
|
||||
|
||||
const PLUGIN_ID = 'sirsoft-pay_nhnkcp';
|
||||
const FLAG = '__kcpOcReceiptInjectorInstalled';
|
||||
const BTN_ID = 'kcp-oc-receipt-btn';
|
||||
@@ -11,17 +13,16 @@ type Payment = {
|
||||
[key: string]: unknown;
|
||||
};
|
||||
|
||||
function getToken(): string | null {
|
||||
return localStorage.getItem('auth_token');
|
||||
}
|
||||
|
||||
async function fetchPayment(orderNumber: string): Promise<Payment | null> {
|
||||
const token = getToken();
|
||||
if (!token) return null;
|
||||
// 회원 토큰 또는 비회원 주문 조회 토큰 중 하나는 있어야 한다. 비회원 분기를 비우면
|
||||
// 비회원 손님에게는 영수증 버튼이 아예 나타나지 않는다 (서버는 지원한다).
|
||||
const headers = buildOrderRequestHeaders();
|
||||
if (!headers) return null;
|
||||
|
||||
try {
|
||||
const res = await fetch(`/api/modules/sirsoft-ecommerce/user/orders/${orderNumber}`, {
|
||||
headers: { Authorization: `Bearer ${token}`, Accept: 'application/json' },
|
||||
headers,
|
||||
credentials: 'same-origin',
|
||||
});
|
||||
if (!res.ok) return null;
|
||||
const data = (await res.json()) as { data?: { payment?: Payment } };
|
||||
@@ -38,12 +39,13 @@ interface ReceiptInfo {
|
||||
}
|
||||
|
||||
async function fetchReceiptUrl(orderNumber: string): Promise<ReceiptInfo | null> {
|
||||
const token = getToken();
|
||||
if (!token) return null;
|
||||
const headers = buildOrderRequestHeaders();
|
||||
if (!headers) return null;
|
||||
|
||||
try {
|
||||
const res = await fetch(`/api/plugins/${PLUGIN_ID}/user/orders/${orderNumber}/receipt`, {
|
||||
headers: { Authorization: `Bearer ${token}`, Accept: 'application/json' },
|
||||
headers,
|
||||
credentials: 'same-origin',
|
||||
});
|
||||
if (!res.ok) return null;
|
||||
return (await res.json()) as ReceiptInfo;
|
||||
|
||||
@@ -0,0 +1,101 @@
|
||||
<?php
|
||||
|
||||
namespace Plugins\Sirsoft\PayNhnkcp\Concerns;
|
||||
|
||||
use Illuminate\Support\Facades\Log;
|
||||
use Modules\Sirsoft\Ecommerce\Models\Order;
|
||||
|
||||
/**
|
||||
* 모바일 가상계좌 콜백을 인증된 결제 세션에 묶는 일회성 state.
|
||||
*
|
||||
* KCP 모바일(SmartPhone Pay)은 가상계좌 계좌번호를 서버-서버 승인이 아니라 브라우저
|
||||
* 평문 POST 로만 전달한다. 그래서 콜백만으로는 그 값이 KCP 에서 온 것인지 확인할 수
|
||||
* 없고, 주문번호만 아는 제3자가 위조 계좌를 영속시킬 수 있었다 (KVE-2026-2019).
|
||||
*
|
||||
* 방어는 KCP 가 passthrough 파라미터를 그대로 되돌려주는 성질을 이용한다 —
|
||||
* 소유자 인증을 거친 승인키 발급 시점에 nonce 를 만들어 주문에 저장하고 `param_opt_2`
|
||||
* 로 실어 보낸 뒤, 콜백에서 되돌아온 값과 대조한다. `param_opt_1` 은 간편결제 수단
|
||||
* 식별자가 이미 점유하고 있으므로 `param_opt_2` 를 쓴다.
|
||||
*
|
||||
* 발급 지점은 `auth:sanctum` 이라 nonce 는 주문 소유자의 세션에 완전히 묶인다.
|
||||
* 공격자는 피해자의 nonce 를 알 수 없다.
|
||||
*/
|
||||
trait BindsMobileVbankSession
|
||||
{
|
||||
/**
|
||||
* payment_meta 안의 state 키
|
||||
*/
|
||||
private const MOBILE_VBANK_STATE_KEY = 'mobile_vbank_state';
|
||||
|
||||
/**
|
||||
* 모바일 가상계좌 세션 nonce 를 발급해 주문에 저장합니다.
|
||||
*
|
||||
* 저장에 실패하면 null 을 반환한다 — 호출부는 nonce 없이 결제창을 열지 않는다
|
||||
* (검증 불가능한 콜백을 만들지 않기 위해서다).
|
||||
*
|
||||
* @param Order $order 대상 주문
|
||||
* @return string|null 발급된 nonce, 저장 실패 시 null
|
||||
*/
|
||||
protected function issueMobileVbankState(Order $order): ?string
|
||||
{
|
||||
$payment = $order->payment;
|
||||
if (! $payment || ! $payment->exists) {
|
||||
return null;
|
||||
}
|
||||
|
||||
$nonce = bin2hex(random_bytes(16));
|
||||
|
||||
try {
|
||||
$meta = $payment->payment_meta ?? [];
|
||||
$meta = is_array($meta) ? $meta : [];
|
||||
$meta[self::MOBILE_VBANK_STATE_KEY] = [
|
||||
'nonce' => $nonce,
|
||||
'issued_at' => now()->toIso8601String(),
|
||||
];
|
||||
|
||||
$payment->payment_meta = $meta;
|
||||
$payment->save();
|
||||
} catch (\Exception $e) {
|
||||
Log::error('KCP: failed to persist mobile vbank session state', [
|
||||
'order_number' => $order->order_number,
|
||||
'error' => $e->getMessage(),
|
||||
]);
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
return $nonce;
|
||||
}
|
||||
|
||||
/**
|
||||
* 콜백으로 되돌아온 `param_opt_2` 가 저장된 nonce 와 일치하는지 확인합니다.
|
||||
*
|
||||
* 저장된 state 가 없거나 값이 다르면 false 다. 일치 여부는 timing-safe 비교로
|
||||
* 판정한다.
|
||||
*
|
||||
* @param Order $order 대상 주문
|
||||
* @param string|null $echoedState 콜백이 되돌려준 param_opt_2
|
||||
* @return bool 일치 여부
|
||||
*/
|
||||
protected function mobileVbankStateMatches(Order $order, ?string $echoedState): bool
|
||||
{
|
||||
if (! is_string($echoedState) || $echoedState === '') {
|
||||
return false;
|
||||
}
|
||||
|
||||
$payment = $order->payment;
|
||||
if (! $payment || ! $payment->exists) {
|
||||
return false;
|
||||
}
|
||||
|
||||
$meta = $payment->payment_meta ?? [];
|
||||
$meta = is_array($meta) ? $meta : [];
|
||||
$stored = $meta[self::MOBILE_VBANK_STATE_KEY]['nonce'] ?? null;
|
||||
|
||||
if (! is_string($stored) || $stored === '') {
|
||||
return false;
|
||||
}
|
||||
|
||||
return hash_equals($stored, $echoedState);
|
||||
}
|
||||
}
|
||||
@@ -10,6 +10,7 @@ use Illuminate\Http\JsonResponse;
|
||||
use Illuminate\Http\Request;
|
||||
use Modules\Sirsoft\Ecommerce\Models\Order;
|
||||
use Modules\Sirsoft\Ecommerce\Services\OrderProcessingService;
|
||||
use Plugins\Sirsoft\PayNhnkcp\Concerns\BindsMobileVbankSession;
|
||||
use Plugins\Sirsoft\PayNhnkcp\Concerns\RecordsPaymentWindowClosure;
|
||||
use Plugins\Sirsoft\PayNhnkcp\Exceptions\NhnKcpApiException;
|
||||
use Plugins\Sirsoft\PayNhnkcp\Services\KcpSoapService;
|
||||
@@ -22,6 +23,7 @@ use Plugins\Sirsoft\PayNhnkcp\Services\KcpSoapService;
|
||||
*/
|
||||
class MobileApprovalController
|
||||
{
|
||||
use BindsMobileVbankSession;
|
||||
use RecordsPaymentWindowClosure;
|
||||
|
||||
/** 결제수단 → KCP 모바일 pay_method 코드 */
|
||||
@@ -197,6 +199,21 @@ class MobileApprovalController
|
||||
$settings = plugin_settings(self::PLUGIN_IDENTIFIER) ?? [];
|
||||
$fields['vcnt_expire_term'] = (string) ((int) ($settings['vbank_expire_days'] ?? 3));
|
||||
$fields['disp_tax_yn'] = 'N';
|
||||
|
||||
// 모바일 가상계좌 콜백은 계좌번호를 브라우저 평문으로만 전달한다.
|
||||
// 이 지점은 소유자 인증(auth:sanctum)을 통과했으므로 여기서 만든 일회성
|
||||
// nonce 를 passthrough 파라미터로 실어 보내고, 콜백에서 되돌아온 값과
|
||||
// 대조해 그 콜백이 이 결제 세션에서 비롯됐음을 확인한다 (KVE-2026-2019).
|
||||
// param_opt_1 은 간편결제 수단 식별자가 점유하므로 param_opt_2 를 쓴다.
|
||||
$mobileVbankState = $this->issueMobileVbankState($order);
|
||||
if ($mobileVbankState === null) {
|
||||
return response()->json([
|
||||
'success' => false,
|
||||
'error' => 'Failed to prepare the virtual account payment session.',
|
||||
], 500);
|
||||
}
|
||||
|
||||
$fields['param_opt_2'] = $mobileVbankState;
|
||||
}
|
||||
|
||||
if ($isEasyPay) {
|
||||
|
||||
@@ -17,6 +17,7 @@ use Modules\Sirsoft\Ecommerce\Exceptions\PaymentAmountMismatchException;
|
||||
use Modules\Sirsoft\Ecommerce\Helpers\DeviceDetector;
|
||||
use Modules\Sirsoft\Ecommerce\Models\Order;
|
||||
use Modules\Sirsoft\Ecommerce\Services\OrderProcessingService;
|
||||
use Plugins\Sirsoft\PayNhnkcp\Concerns\BindsMobileVbankSession;
|
||||
use Plugins\Sirsoft\PayNhnkcp\Concerns\IssuesReceiptCookie;
|
||||
use Plugins\Sirsoft\PayNhnkcp\Concerns\PreventsReplayCallback;
|
||||
use Plugins\Sirsoft\PayNhnkcp\Concerns\RecordsPaymentWindowClosure;
|
||||
@@ -38,6 +39,7 @@ use Plugins\Sirsoft\PayNhnkcp\Support\ShopRedirectUrl;
|
||||
*/
|
||||
class PaymentCallbackController
|
||||
{
|
||||
use BindsMobileVbankSession;
|
||||
use IssuesReceiptCookie;
|
||||
use PreventsReplayCallback;
|
||||
use RecordsPaymentWindowClosure;
|
||||
@@ -607,6 +609,24 @@ class PaymentCallbackController
|
||||
$isMobile = $encData === '' || $encInfo === '';
|
||||
|
||||
if ($isMobile) {
|
||||
// 모바일 분기는 PG 서버 호출이 없어 계좌 정보의 유일한 출처가 브라우저 평문이다.
|
||||
// 그래서 이 콜백이 소유자 인증을 거친 결제 세션에서 비롯됐는지를 먼저 확인한다 —
|
||||
// 승인키 발급 시점에 실어 보낸 일회성 nonce 가 param_opt_2 로 되돌아와야 한다
|
||||
// (KVE-2026-2019). 불일치/부재면 상태를 전혀 바꾸지 않고 실패 URL 로 돌린다
|
||||
// ("브라우저 입력만으로 상태 변경 금지" — KVE-2026-2018/2046 과 같은 기준).
|
||||
if (! $this->mobileVbankStateMatches($order, $validated['param_opt_2'] ?? null)) {
|
||||
Log::warning('KCP: mobile vbank callback rejected — session state mismatch', [
|
||||
'ordr_idxx' => $ordrIdxx,
|
||||
'has_echoed_state' => ($validated['param_opt_2'] ?? '') !== '',
|
||||
]);
|
||||
|
||||
return redirect($this->resolveFailUrl([
|
||||
'error' => 'vbank_session_mismatch',
|
||||
'message' => __('sirsoft-pay_nhnkcp::messages.errors.payment_failed'),
|
||||
'orderId' => $ordrIdxx,
|
||||
]));
|
||||
}
|
||||
|
||||
// 모바일: 콜백 POST 의 평문 필드를 그대로 응답으로 취급
|
||||
// KCP 변종 키 모두 대응 (bankname|bank_name, depositor|account_holder, va_date|vnbank_expire_date)
|
||||
$pgResponse = [
|
||||
|
||||
@@ -48,6 +48,8 @@ class AuthCallbackRequest extends FormRequest
|
||||
'good_mny' => ['nullable', 'numeric', 'min:1'],
|
||||
'use_pay_method' => ['nullable', 'string'],
|
||||
'param_opt_1' => ['nullable', 'string', 'max:50'],
|
||||
// 모바일 가상계좌 세션 nonce (승인키 발급 시점에 실어 보낸 값을 KCP 가 되돌려준다)
|
||||
'param_opt_2' => ['nullable', 'string', 'max:50'],
|
||||
'nhnkcp_easy_pay_method' => ['nullable', 'string', 'max:50'],
|
||||
// 모바일 SmartPhone Pay 가상계좌 콜백 (enc_data 없이 평문 전달)
|
||||
// KCP가 보내는 변종 키 모두 허용 — handleVbankIssued 에서 우선순위로 처리
|
||||
|
||||
+400
@@ -0,0 +1,400 @@
|
||||
<?php
|
||||
|
||||
namespace Plugins\Sirsoft\PayNhnkcp\Tests\Feature\Controllers;
|
||||
|
||||
use App\Models\User;
|
||||
use App\Services\PluginSettingsService;
|
||||
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 Plugins\Sirsoft\PayNhnkcp\Services\KcpSoapService;
|
||||
use Plugins\Sirsoft\PayNhnkcp\Tests\PluginTestCase;
|
||||
|
||||
/**
|
||||
* 모바일 가상계좌 콜백 세션 바인딩 회귀 테스트 (KVE-2026-2019).
|
||||
*
|
||||
* 회귀 배경: KCP 모바일(SmartPhone Pay) 가상계좌 콜백은 enc_data/enc_info 없이
|
||||
* 계좌 정보를 평문 POST 로만 전달한다. 그런데 컨트롤러는 그 평문을 PG 서버 검증 없이
|
||||
* 그대로 영속시켰다. 그래서 주문번호만 아는 익명 요청 1회로 피해자 주문의 입금 계좌를
|
||||
* 공격자 계좌로 바꿀 수 있었다.
|
||||
*
|
||||
* 방어: 소유자 인증을 거친 승인키 발급 시점에 일회성 nonce 를 만들어 주문에 저장하고
|
||||
* KCP passthrough 파라미터(param_opt_2)로 실어 보낸 뒤, 콜백에서 되돌아온 값과
|
||||
* 대조한다. 불일치/부재면 상태를 전혀 바꾸지 않는다.
|
||||
*
|
||||
* @group nhnkcp
|
||||
* @group security
|
||||
*/
|
||||
class MobileVbankCallbackBindingTest extends PluginTestCase
|
||||
{
|
||||
private const TEST_SITE_CD = 'T0000';
|
||||
|
||||
private const TEST_SITE_KEY = 'TEST_SITE_KEY_0000';
|
||||
|
||||
private const CALLBACK_URL = '/plugins/sirsoft-pay_nhnkcp/payment/callback';
|
||||
|
||||
private const APPROVAL_KEY_ENDPOINT = '/api/plugins/sirsoft-pay_nhnkcp/mobile/approval-key';
|
||||
|
||||
private const TEST_PAY_URL = 'https://testpay.kcp.co.kr/php/mobile/mc_pay_form.php';
|
||||
|
||||
protected function setUp(): void
|
||||
{
|
||||
parent::setUp();
|
||||
$this->mockPluginSettings();
|
||||
}
|
||||
|
||||
/**
|
||||
* 플러그인 설정을 테스트 모드로 고정합니다.
|
||||
*/
|
||||
private function mockPluginSettings(): void
|
||||
{
|
||||
$mock = $this->createMock(PluginSettingsService::class);
|
||||
$mock->method('get')->willReturn([
|
||||
'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',
|
||||
]);
|
||||
$this->app->instance(PluginSettingsService::class, $mock);
|
||||
}
|
||||
|
||||
/**
|
||||
* KcpSoapService 를 승인키 발급 성공으로 고정합니다.
|
||||
*/
|
||||
private function mockSoapService(): void
|
||||
{
|
||||
$mock = $this->createMock(KcpSoapService::class);
|
||||
$mock->method('getApprovalKey')->willReturn([
|
||||
'approval_key' => 'TEST_APPROVAL_KEY',
|
||||
'pay_url' => self::TEST_PAY_URL,
|
||||
]);
|
||||
$mock->method('getSiteCd')->willReturn(self::TEST_SITE_CD);
|
||||
$mock->method('getEscrowSiteCd')->willReturn(self::TEST_SITE_CD);
|
||||
$this->app->instance(KcpSoapService::class, $mock);
|
||||
}
|
||||
|
||||
/**
|
||||
* KRW 통화 스냅샷을 반환합니다.
|
||||
*
|
||||
* @return array<string, mixed>
|
||||
*/
|
||||
private static function krwCurrencySnapshot(): array
|
||||
{
|
||||
return [
|
||||
'base_currency' => 'KRW',
|
||||
'order_currency' => 'KRW',
|
||||
'base_unit' => 1,
|
||||
'exchange_rates' => [
|
||||
'KRW' => [
|
||||
'rate' => 1,
|
||||
'rounding_unit' => '1',
|
||||
'rounding_method' => 'round',
|
||||
'decimal_places' => 0,
|
||||
'base_unit' => 1,
|
||||
],
|
||||
],
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* 가상계좌 결제대기 주문을 만듭니다.
|
||||
*
|
||||
* @param array<string, mixed> $paymentMeta payment_meta 초기값
|
||||
*/
|
||||
private function createVbankOrder(array $paymentMeta = [], int $totalAmount = 50000): Order
|
||||
{
|
||||
$user = User::factory()->create();
|
||||
|
||||
$order = OrderFactory::new()->create([
|
||||
'user_id' => $user->id,
|
||||
'order_number' => 'ORD-VB-'.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' => $totalAmount,
|
||||
'total_vat_amount' => (int) round($totalAmount * 10 / 110),
|
||||
'total_tax_free_amount' => 0,
|
||||
'currency' => 'KRW',
|
||||
'currency_snapshot' => self::krwCurrencySnapshot(),
|
||||
]);
|
||||
|
||||
OrderPaymentFactory::new()->create([
|
||||
'order_id' => $order->id,
|
||||
'payment_status' => PaymentStatusEnum::READY,
|
||||
'payment_method' => PaymentMethodEnum::VBANK,
|
||||
'pg_provider' => 'nhnkcp',
|
||||
'paid_amount_local' => 0,
|
||||
'paid_at' => null,
|
||||
'transaction_id' => null,
|
||||
'vbank_name' => null,
|
||||
'vbank_number' => null,
|
||||
'vbank_holder' => null,
|
||||
'payment_meta' => $paymentMeta,
|
||||
]);
|
||||
|
||||
return $order->fresh('payment');
|
||||
}
|
||||
|
||||
/**
|
||||
* 저장된 세션 nonce 를 가진 주문을 만듭니다.
|
||||
*
|
||||
* @return array{0: Order, 1: string}
|
||||
*/
|
||||
private function createVbankOrderWithState(): array
|
||||
{
|
||||
$nonce = bin2hex(random_bytes(16));
|
||||
$order = $this->createVbankOrder([
|
||||
'mobile_vbank_state' => [
|
||||
'nonce' => $nonce,
|
||||
'issued_at' => now()->toIso8601String(),
|
||||
],
|
||||
]);
|
||||
|
||||
return [$order, $nonce];
|
||||
}
|
||||
|
||||
/**
|
||||
* 모바일 가상계좌 콜백 페이로드를 만듭니다 (enc_data/enc_info 없음).
|
||||
*
|
||||
* @param array<string, mixed> $overrides 덮어쓸 값
|
||||
* @return array<string, mixed>
|
||||
*/
|
||||
private function mobileVbankPayload(Order $order, array $overrides = []): array
|
||||
{
|
||||
return array_merge([
|
||||
'res_cd' => '0000',
|
||||
'res_msg' => '정상처리',
|
||||
'tno' => 'KCP_TNO_'.uniqid(),
|
||||
'ordr_idxx' => $order->order_number,
|
||||
'good_mny' => (int) $order->total_due_amount,
|
||||
'use_pay_method' => 'VCNT',
|
||||
'bankname' => '공격자은행',
|
||||
'account' => '9999999999',
|
||||
'depositor' => '공격자',
|
||||
'va_date' => now()->addDays(3)->format('YmdHis'),
|
||||
], $overrides);
|
||||
}
|
||||
|
||||
// =========================================================================
|
||||
// 차단 매트릭스
|
||||
// =========================================================================
|
||||
|
||||
/**
|
||||
* 세션 nonce 가 저장되지 않은 주문에 온 모바일 콜백은 계좌를 쓰지 못한다.
|
||||
*/
|
||||
public function test_mobile_vbank_callback_without_stored_state_cannot_persist_account(): void
|
||||
{
|
||||
$order = $this->createVbankOrder();
|
||||
|
||||
$this->post(self::CALLBACK_URL, $this->mobileVbankPayload($order));
|
||||
|
||||
$payment = $order->fresh()->payment;
|
||||
$this->assertNull($payment->vbank_number, '검증되지 않은 콜백이 계좌를 저장했습니다');
|
||||
$this->assertNull($payment->vbank_name);
|
||||
$this->assertSame(PaymentStatusEnum::READY->value, $payment->payment_status->value);
|
||||
}
|
||||
|
||||
/**
|
||||
* 저장된 nonce 와 다른 param_opt_2 는 차단된다.
|
||||
*/
|
||||
public function test_mobile_vbank_callback_with_mismatched_state_is_rejected(): void
|
||||
{
|
||||
[$order] = $this->createVbankOrderWithState();
|
||||
|
||||
$this->post(self::CALLBACK_URL, $this->mobileVbankPayload($order, [
|
||||
'param_opt_2' => bin2hex(random_bytes(16)),
|
||||
]));
|
||||
|
||||
$payment = $order->fresh()->payment;
|
||||
$this->assertNull($payment->vbank_number, '불일치 nonce 로 계좌가 저장되었습니다');
|
||||
$this->assertNull($payment->vbank_name);
|
||||
}
|
||||
|
||||
/**
|
||||
* 이미 발급된 계좌는 위조 콜백으로 덮어써지지 않는다.
|
||||
*/
|
||||
public function test_forged_callback_cannot_overwrite_an_issued_account(): void
|
||||
{
|
||||
$order = $this->createVbankOrder();
|
||||
$order->payment->update([
|
||||
'vbank_name' => '정상은행',
|
||||
'vbank_number' => 'T1234567890',
|
||||
'vbank_holder' => 'NHN KCP',
|
||||
'vbank_issued_at' => now(),
|
||||
]);
|
||||
|
||||
$this->post(self::CALLBACK_URL, $this->mobileVbankPayload($order));
|
||||
|
||||
$payment = $order->fresh()->payment;
|
||||
$this->assertSame('T1234567890', $payment->vbank_number, '위조 콜백이 발급된 계좌를 변조했습니다');
|
||||
$this->assertSame('정상은행', $payment->vbank_name);
|
||||
}
|
||||
|
||||
/**
|
||||
* nonce 는 1회성이다 — 정상 발급 후 같은 nonce 로 다시 오면 차단된다.
|
||||
*/
|
||||
public function test_state_is_single_use_and_replay_is_rejected(): void
|
||||
{
|
||||
[$order, $nonce] = $this->createVbankOrderWithState();
|
||||
|
||||
$this->post(self::CALLBACK_URL, $this->mobileVbankPayload($order, [
|
||||
'param_opt_2' => $nonce,
|
||||
'bankname' => '정상은행',
|
||||
'account' => 'T1111111111',
|
||||
'depositor' => 'NHN KCP',
|
||||
]));
|
||||
|
||||
$this->assertSame('T1111111111', $order->fresh()->payment->vbank_number);
|
||||
|
||||
// 같은 nonce 로 재사용 시도 (계좌 변조)
|
||||
$this->post(self::CALLBACK_URL, $this->mobileVbankPayload($order, [
|
||||
'param_opt_2' => $nonce,
|
||||
'bankname' => '공격자은행',
|
||||
'account' => 'T9999999999',
|
||||
]));
|
||||
|
||||
$this->assertSame(
|
||||
'T1111111111',
|
||||
$order->fresh()->payment->vbank_number,
|
||||
'nonce 재사용으로 계좌가 변조되었습니다'
|
||||
);
|
||||
}
|
||||
|
||||
// =========================================================================
|
||||
// 발급 지점 (승인키 요청) — 정상 흐름 불변
|
||||
// =========================================================================
|
||||
|
||||
/**
|
||||
* 가상계좌 모바일 승인키 요청은 nonce 를 만들어 주문에 저장하고 param_opt_2 로 실어 보낸다.
|
||||
*
|
||||
* 이 경로는 종전 테스트가 카드 결제만 다뤄 비어 있었다. 발급이 조용히 실패하면
|
||||
* 콜백은 언제나 차단되어 **가상계좌 결제 자체가 불능**이 되는데, 그 실패는 차단
|
||||
* 테스트만으로는 드러나지 않는다.
|
||||
*/
|
||||
public function test_mobile_vbank_approval_key_issues_and_persists_the_session_state(): void
|
||||
{
|
||||
$order = $this->createVbankOrder();
|
||||
$this->mockSoapService();
|
||||
|
||||
$response = $this->actingAs($order->user)->postJson(self::APPROVAL_KEY_ENDPOINT, [
|
||||
'order_number' => $order->order_number,
|
||||
'amount' => (int) $order->total_due_amount,
|
||||
'good_name' => '테스트 상품',
|
||||
'pay_method' => 'vbank',
|
||||
'ret_url' => 'https://example.com/callback',
|
||||
]);
|
||||
|
||||
$response->assertOk()->assertJsonPath('success', true);
|
||||
|
||||
$echoed = $response->json('data.fields.param_opt_2');
|
||||
$this->assertIsString($echoed);
|
||||
$this->assertNotSame('', $echoed, 'param_opt_2 가 결제창 필드에 실리지 않았다');
|
||||
|
||||
$stored = $order->fresh()->payment->payment_meta['mobile_vbank_state']['nonce'] ?? null;
|
||||
$this->assertSame($echoed, $stored, '결제창에 실은 값과 저장된 값이 다르다');
|
||||
}
|
||||
|
||||
/**
|
||||
* 카드 결제에는 nonce 를 만들지 않는다 (범위 최소화 — 불필요한 부작용 방지).
|
||||
*/
|
||||
public function test_card_approval_key_does_not_issue_a_vbank_state(): void
|
||||
{
|
||||
$order = $this->createVbankOrder();
|
||||
$this->mockSoapService();
|
||||
|
||||
$response = $this->actingAs($order->user)->postJson(self::APPROVAL_KEY_ENDPOINT, [
|
||||
'order_number' => $order->order_number,
|
||||
'amount' => (int) $order->total_due_amount,
|
||||
'good_name' => '테스트 상품',
|
||||
'pay_method' => 'card',
|
||||
'ret_url' => 'https://example.com/callback',
|
||||
]);
|
||||
|
||||
$response->assertOk();
|
||||
$this->assertNull($response->json('data.fields.param_opt_2'));
|
||||
$this->assertArrayNotHasKey(
|
||||
'mobile_vbank_state',
|
||||
$order->fresh()->payment->payment_meta ?? []
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* 발급 → 콜백 왕복이 실제로 성립한다 (발급 지점과 검증 지점의 계약 일치).
|
||||
*
|
||||
* 두 지점이 서로 다른 키·형식을 쓰면 차단 테스트는 전부 통과하면서 정상 결제만
|
||||
* 막힌다. 과거 KVE 재수정 사례가 "검증 지점과 실행 지점의 해석 불일치" 였으므로
|
||||
* 두 절반을 한 테스트로 묶어 고정한다.
|
||||
*/
|
||||
public function test_issued_state_round_trips_through_the_callback(): void
|
||||
{
|
||||
$order = $this->createVbankOrder();
|
||||
$this->mockSoapService();
|
||||
|
||||
$issued = $this->actingAs($order->user)
|
||||
->postJson(self::APPROVAL_KEY_ENDPOINT, [
|
||||
'order_number' => $order->order_number,
|
||||
'amount' => (int) $order->total_due_amount,
|
||||
'good_name' => '테스트 상품',
|
||||
'pay_method' => 'vbank',
|
||||
'ret_url' => 'https://example.com/callback',
|
||||
])
|
||||
->json('data.fields.param_opt_2');
|
||||
|
||||
$this->post(self::CALLBACK_URL, $this->mobileVbankPayload($order, [
|
||||
'param_opt_2' => $issued,
|
||||
'bankname' => '정상은행',
|
||||
'account' => 'T3333333333',
|
||||
'depositor' => 'NHN KCP',
|
||||
]));
|
||||
|
||||
$this->assertSame(
|
||||
'T3333333333',
|
||||
$order->fresh()->payment->vbank_number,
|
||||
'발급된 nonce 가 콜백에서 인정되지 않았다 — 정상 가상계좌 결제가 불능이다'
|
||||
);
|
||||
}
|
||||
|
||||
// =========================================================================
|
||||
// 통과 매트릭스 (정상 흐름 불변)
|
||||
// =========================================================================
|
||||
|
||||
/**
|
||||
* 일치하는 nonce 를 실은 콜백은 종전대로 계좌를 저장한다.
|
||||
*/
|
||||
public function test_mobile_vbank_callback_with_matching_state_persists_account(): void
|
||||
{
|
||||
[$order, $nonce] = $this->createVbankOrderWithState();
|
||||
|
||||
$this->post(self::CALLBACK_URL, $this->mobileVbankPayload($order, [
|
||||
'param_opt_2' => $nonce,
|
||||
'bankname' => '정상은행',
|
||||
'account' => 'T2222222222',
|
||||
'depositor' => 'NHN KCP',
|
||||
]));
|
||||
|
||||
$payment = $order->fresh()->payment;
|
||||
$this->assertSame('T2222222222', $payment->vbank_number);
|
||||
$this->assertSame('정상은행', $payment->vbank_name);
|
||||
$this->assertSame('NHN KCP', $payment->vbank_holder);
|
||||
$this->assertSame('mobile', $payment->payment_device);
|
||||
}
|
||||
}
|
||||
@@ -139,7 +139,7 @@ API 와 동기화하는 역할만 합니다. 등록은 훅 기반입니다
|
||||
| 종류 | 개수 | 위치 |
|
||||
|---|---|---|
|
||||
| PHPUnit | 23개 | `plugins/_bundled/sirsoft-pay_nicepayments/tests` |
|
||||
| Vitest | 7개 | `vitest.config.ts` |
|
||||
| Vitest | 8개 | `vitest.config.ts` |
|
||||
| Playwright | 0개 | — |
|
||||
| 시나리오 매니페스트 | 1개 | `tests/scenarios` |
|
||||
|
||||
|
||||
@@ -6,6 +6,11 @@
|
||||
|
||||
## [1.0.3] - 2026-09-04
|
||||
|
||||
### Fixed
|
||||
|
||||
- 비회원으로 결제하신 손님이 주문완료 화면과 비회원 주문 상세 화면에서 영수증 버튼과 결제수단 표시를 볼 수 없던 문제를 고쳤습니다. 서버는 비회원 주문을 확인해 줄 준비가 되어 있었는데 화면이 확인값을 함께 보내지 않아 조회 자체가 되지 않았고, 오류 메시지도 남지 않아 원인을 알기 어려웠습니다.
|
||||
- 비회원으로 결제할 때 결제사로 과세·비과세 금액 구분이 전달되지 않던 문제를 고쳤습니다. 주문 정보를 불러오지 못해 세금 항목이 빠진 채 결제가 진행되었고, 면세 상품을 함께 파는 상점에서 금액 구성이 실제와 달라질 수 있었습니다.
|
||||
|
||||
### Security
|
||||
|
||||
- 결제창 프로그램을 불러오는 주소가 나이스페이먼츠의 주소인지 불러오기 직전에 확인합니다. 확인되지 않는 주소면 결제를 진행하지 않고 안내를 표시합니다. 또한 결제창 프로그램이 실제로 준비되었는지를 기준으로 다음 단계를 진행하도록 바꿔, 프로그램이 아직 준비되지 않았는데 결제창이 열리지 않고 멈추던 상황을 없앴습니다.
|
||||
|
||||
@@ -1 +1 @@
|
||||
(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 de(e){return e.trim().slice(0,160)}async function ue(e,t="nicepay-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:de(t)||"nicepay-window-closed"};try{const a=window.G7Core?.api;if(typeof a?.post=="function"){await a.post(e.closeReportUrl,n);return}await fetch(le(e.closeReportUrl),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(n),keepalive:!0})}catch(a){console.warn("[sirsoft-pay_nicepayments] failed to report payment window close",a)}}const pe=["web.nicepay.co.kr"];function me(e,t){const n=window?.G7Core?.t;if(typeof n!="function")return t;const a=`sirsoft-pay_nicepayments.${e}`,r=n(a);return typeof r=="string"&&r!==a?r:t}function ye(e){let t=null;try{t=new URL(e)}catch{t=null}if(t===null||t.protocol!=="https:"||!pe.includes(t.hostname.toLowerCase()))throw new Error(me("payment.error.sdk_url_untrusted","결제 모듈 주소가 올바르지 않아 결제를 진행할 수 없습니다."))}async function fe(e){if(ye(e),typeof window.goPay=="function")return;document.querySelectorAll(`script[src="${CSS.escape(e)}"]`).forEach(n=>n.remove());const t=window?.G7Core?.asset?.loadScript;if(typeof t=="function"){await t(e,{},{label:"nicepayments SDK"});return}await new Promise((n,a)=>{const r=document.createElement("script");r.src=e,r.onload=()=>n(),r.onerror=()=>a(new Error(`Failed to load script: ${e}`)),document.head.appendChild(r)})}function he(e,t){const n=document.createElement("form");n.id="nicepayForm",n.method="post",n.action=e,n.acceptCharset="utf-8";for(const[a,r]of Object.entries(t)){const o=document.createElement("input");o.type="hidden",o.name=a,o.value=r,n.appendChild(o)}return document.body.appendChild(n),n}const we="/plugins/sirsoft-pay_nicepayments/payment/callback",be="https://web.nicepay.co.kr/v3/v3Payment.jsp";function ge(){if(typeof navigator>"u")return!1;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 _e(e,t){const{pgPaymentData:n,paymentMethod:a}=e.params??{},r=window.__templateApp?.globalState?._local,o=a??n?.payment_method??r?.paymentMethod??"card";if(!n){console.error("[sirsoft-pay_nicepayments] pgPaymentData is required");return}const i=window.G7Core;try{const s=await i.api.get("/modules/sirsoft-ecommerce/payments/client-config/nicepayments");if(!s.data){console.error("[sirsoft-pay_nicepayments] Failed to fetch client config",s);return}const l=s.data,d=ge();if(!d&&(await fe(l.sdk_url),typeof window.goPay!="function")){i?.toast?.error?.("나이스페이먼츠 SDK를 불러올 수 없습니다. 잠시 후 다시 시도해주세요."),i?.state?.setLocal?.({isSubmittingOrder:!1,paymentMethod:o});return}const _=window.location.origin+l.sign_data_url,u=typeof localStorage<"u"?localStorage.getItem("auth_token"):null,te={"Content-Type":"application/json","X-Requested-With":"XMLHttpRequest",Accept:"application/json"};u&&(te.Authorization=`Bearer ${u}`);const ne=await fetch(_,{method:"POST",credentials:"include",headers:te,body:JSON.stringify({amt:n.amount,moid:n.order_number,buyer_email:n.customer_email??"",buyer_phone:n.customer_phone??""})});if(!ne.ok)throw new Error("SignData 생성에 실패했습니다.");const I=await ne.json(),ae=window.location.origin+we,M=typeof o=="string"&&o.startsWith("nicepay_"),oe=M?"CARD":{card:"CARD",vbank:"VBANK",bank:"BANK",phone:"CELLPHONE"}[o??"card"]??"CARD",c={PayMethod:oe,GoodsName:n.order_name,Amt:String(n.amount),MID:I.mid,Moid:n.order_number,BuyerName:n.customer_name??"",BuyerEmail:n.customer_email??"",BuyerTel:n.customer_phone??"",ReturnURL:ae,EdiDate:I.ediDate,SignData:I.signData,CharSet:"utf-8",GoodsCl:"1",DirectShowOpt:"",DirectEasyPay:"",NicepayReserved:"",EasyPayMethod:"",MallReserved:"",MallReserved1:""};oe==="CELLPHONE"&&(c.GoodsCl=n.goods_cl??"1");const bt=l.useEscrow&&!M;if(c.TransType=bt?"1":"0",M)switch(c.DirectShowOpt="CARD",c.MallReserved=`nicepay_easy_pay_method=${encodeURIComponent(o)}`,c.MallReserved1=o,o){case"nicepay_naverpay":c.DirectEasyPay="E020",c.EasyPayMethod="E020=CARD";break;case"nicepay_kakaopay":c.NicepayReserved="DirectKakao=Y";break;case"nicepay_samsungpay":c.DirectEasyPay="E021";break;case"nicepay_applepay":c.DirectEasyPay="E025";break;case"nicepay_payco":c.NicepayReserved="DirectPayco=Y";break;case"nicepay_skpay":c.NicepayReserved="DirectPay11=Y";break;case"nicepay_ssgpay":c.DirectEasyPay="E007";break;case"nicepay_lpay":c.DirectEasyPay="E018";break}try{const m=(await i.api.get(`/modules/sirsoft-ecommerc
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 ue(e){return e.trim().slice(0,160)}async function pe(e,t="nicepay-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:ue(t)||"nicepay-window-closed"};try{const a=window.G7Core?.api;if(typeof a?.post=="function"){await a.post(e.closeReportUrl,n);return}await fetch(de(e.closeReportUrl),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(n),keepalive:!0})}catch(a){console.warn("[sirsoft-pay_nicepayments] failed to report payment window close",a)}}const me=["web.nicepay.co.kr"];function ye(e,t){const n=window?.G7Core?.t;if(typeof n!="function")return t;const a=`sirsoft-pay_nicepayments.${e}`,r=n(a);return typeof r=="string"&&r!==a?r:t}function fe(e){let t=null;try{t=new URL(e)}catch{t=null}if(t===null||t.protocol!=="https:"||!me.includes(t.hostname.toLowerCase()))throw new Error(ye("payment.error.sdk_url_untrusted","결제 모듈 주소가 올바르지 않아 결제를 진행할 수 없습니다."))}async function he(e){if(fe(e),typeof window.goPay=="function")return;document.querySelectorAll(`script[src="${CSS.escape(e)}"]`).forEach(n=>n.remove());const t=window?.G7Core?.asset?.loadScript;if(typeof t=="function"){await t(e,{},{label:"nicepayments SDK"});return}await new Promise((n,a)=>{const r=document.createElement("script");r.src=e,r.onload=()=>n(),r.onerror=()=>a(new Error(`Failed to load script: ${e}`)),document.head.appendChild(r)})}function ge(e,t){const n=document.createElement("form");n.id="nicepayForm",n.method="post",n.action=e,n.acceptCharset="utf-8";for(const[a,r]of Object.entries(t)){const o=document.createElement("input");o.type="hidden",o.name=a,o.value=r,n.appendChild(o)}return document.body.appendChild(n),n}const we="/plugins/sirsoft-pay_nicepayments/payment/callback",be="https://web.nicepay.co.kr/v3/v3Payment.jsp";function _e(){if(typeof navigator>"u")return!1;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 Pe(e,t){const{pgPaymentData:n,paymentMethod:a}=e.params??{},r=window.__templateApp?.globalState?._local,o=a??n?.payment_method??r?.paymentMethod??"card";if(!n){console.error("[sirsoft-pay_nicepayments] pgPaymentData is required");return}const i=window.G7Core;try{const s=await i.api.get("/modules/sirsoft-ecommerce/payments/client-config/nicepayments");if(!s.data){console.error("[sirsoft-pay_nicepayments] Failed to fetch client config",s);return}const l=s.data,d=_e();if(!d&&(await he(l.sdk_url),typeof window.goPay!="function")){i?.toast?.error?.("나이스페이먼츠 SDK를 불러올 수 없습니다. 잠시 후 다시 시도해주세요."),i?.state?.setLocal?.({isSubmittingOrder:!1,paymentMethod:o});return}const _=window.location.origin+l.sign_data_url,u=typeof localStorage<"u"?localStorage.getItem("auth_token"):null,te={"Content-Type":"application/json","X-Requested-With":"XMLHttpRequest",Accept:"application/json"};u&&(te.Authorization=`Bearer ${u}`);const ne=await fetch(_,{method:"POST",credentials:"include",headers:te,body:JSON.stringify({amt:n.amount,moid:n.order_number,buyer_email:n.customer_email??"",buyer_phone:n.customer_phone??""})});if(!ne.ok)throw new Error("SignData 생성에 실패했습니다.");const M=await ne.json(),ae=window.location.origin+we,D=typeof o=="string"&&o.startsWith("nicepay_"),oe=D?"CARD":{card:"CARD",vbank:"VBANK",bank:"BANK",phone:"CELLPHONE"}[o??"card"]??"CARD",c={PayMethod:oe,GoodsName:n.order_name,Amt:String(n.amount),MID:M.mid,Moid:n.order_number,BuyerName:n.customer_name??"",BuyerEmail:n.customer_email??"",BuyerTel:n.customer_phone??"",ReturnURL:ae,EdiDate:M.ediDate,SignData:M.signData,CharSet:"utf-8",GoodsCl:"1",DirectShowOpt:"",DirectEasyPay:"",NicepayReserved:"",EasyPayMethod:"",MallReserved:"",MallReserved1:""};oe==="CELLPHONE"&&(c.GoodsCl=n.goods_cl??"1");const _t=l.useEscrow&&!D;if(c.TransType=_t?"1":"0",D)switch(c.DirectShowOpt="CARD",c.MallReserved=`nicepay_easy_pay_method=${encodeURIComponent(o)}`,c.MallReserved1=o,o){case"nicepay_naverpay":c.DirectEasyPay="E020",c.EasyPayMethod="E020=CARD";break;case"nicepay_kakaopay":c.NicepayReserved="DirectKakao=Y";break;case"nicepay_samsungpay":c.DirectEasyPay="E021";break;case"nicepay_applepay":c.DirectEasyPay="E025";break;case"nicepay_payco":c.NicepayReserved="DirectPayco=Y";break;case"nicepay_skpay":c.NicepayReserved="DirectPay11=Y";break;case"nicepay_ssgpay":c.DirectEasyPay="E007";break;case"nicepay_lpay":c.DirectEasyPay="E018";break}try{const m=i?.state?.get?.("_global")?.guestOrderTokenLine truncated
|
||||
@@ -77,3 +77,22 @@
|
||||
`dist/` 산출물과는 다른 층입니다. CSS 산출물이 없는 것은 결제창 자체는 PG 가 그리고, 이
|
||||
플러그인은 간편결제 버튼 같은 최소한의 UI만 코어 컴포넌트로 구성하기 때문입니다.
|
||||
<!-- @intent END -->
|
||||
|
||||
## 비회원 주문의 자격 증명
|
||||
|
||||
<!-- @intent START -->
|
||||
영수증·결제수단 표시는 주문 정보를 서버에서 다시 조회해 만든다. 이 요청은 레이아웃의
|
||||
`globalHeaders` 배선을 타지 않는 직접 호출(`fetch`)이므로, 자격 증명을 호출부가 직접 실어야 한다.
|
||||
|
||||
- 회원: `Authorization: Bearer …`
|
||||
- 비회원: `X-Guest-Order-Token: …` (코어 storageHandlers 가 sessionStorage 에 저장, 전역 상태 폴백)
|
||||
|
||||
두 경로 모두 `resources/js/guestOrderToken.ts` 의 `buildOrderRequestHeaders()` 한 곳을 거친다.
|
||||
비회원 분기를 비우면 서버는 그 주문을 찾을 수 없다고 응답하고, 화면에는 영수증 버튼이 아예
|
||||
나타나지 않는다 — 예외도 콘솔 오류도 남지 않아 운영자가 원인을 알 수 없다. 서버(`UserReceiptController`)는
|
||||
비회원을 이미 지원하므로, 이 배선이 빠지면 서버 기능이 도달 불가 상태로만 남는다.
|
||||
|
||||
주문 상세 화면의 경로 판정(`ORDER_SHOW_RE`)도 회원(`/mypage/orders/{N}`)과
|
||||
비회원(`/shop/guest/orders/{N}`) 두 주소를 함께 매칭해야 한다. 한쪽을 빼면 그 화면에서는
|
||||
조회가 시작조차 되지 않는다.
|
||||
<!-- @intent END -->
|
||||
+94
@@ -0,0 +1,94 @@
|
||||
/**
|
||||
* 비회원 주문 조회 토큰 배선 검증 (나이스페이먼츠)
|
||||
*
|
||||
* 서버는 `X-Guest-Order-Token` 으로 비회원 주문 소유자를 확인한다. 화면이 그 값을
|
||||
* 보내지 않으면 서버는 주문을 찾지 못하고, 비회원 손님에게는 영수증 버튼이 아예
|
||||
* 나타나지 않는다 — 예외도 콘솔 오류도 남지 않아 원인을 알 수 없는 결함이라 구조로 잠근다.
|
||||
*
|
||||
* @scenario actor=guest, surface=receipt_injector
|
||||
*
|
||||
* @effects guest_order_token_header_built,guest_order_detail_route_matched
|
||||
*/
|
||||
|
||||
import { describe, it, expect, beforeEach, afterEach } from 'vitest';
|
||||
import { readFileSync } from 'node:fs';
|
||||
import { resolve } from 'node:path';
|
||||
|
||||
import { buildOrderRequestHeaders, getGuestOrderToken } from '../guestOrderToken';
|
||||
|
||||
const JS = resolve(__dirname, '..');
|
||||
|
||||
beforeEach(() => {
|
||||
localStorage.clear();
|
||||
sessionStorage.clear();
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
delete (window as any).G7Core;
|
||||
});
|
||||
|
||||
describe('buildOrderRequestHeaders', () => {
|
||||
it('회원 토큰이 있으면 Authorization 을 쓴다', () => {
|
||||
localStorage.setItem('auth_token', 'member-token');
|
||||
|
||||
expect(buildOrderRequestHeaders()).toEqual({
|
||||
Accept: 'application/json',
|
||||
Authorization: 'Bearer member-token',
|
||||
});
|
||||
});
|
||||
|
||||
it('회원 토큰이 없고 비회원 토큰이 있으면 X-Guest-Order-Token 을 쓴다', () => {
|
||||
sessionStorage.setItem('g7_guest_order_token', 'guest-token');
|
||||
|
||||
expect(buildOrderRequestHeaders()).toEqual({
|
||||
Accept: 'application/json',
|
||||
'X-Guest-Order-Token': 'guest-token',
|
||||
});
|
||||
});
|
||||
|
||||
it('둘 다 없으면 null 을 돌려준다 (호출 자체를 막는다)', () => {
|
||||
expect(buildOrderRequestHeaders()).toBeNull();
|
||||
});
|
||||
|
||||
it('sessionStorage 가 비어도 전역 상태 폴백을 본다', () => {
|
||||
(window as any).G7Core = {
|
||||
state: { get: (k: string) => (k === '_global' ? { guestOrderToken: 'global-token' } : undefined) },
|
||||
};
|
||||
|
||||
expect(getGuestOrderToken()).toBe('global-token');
|
||||
});
|
||||
});
|
||||
|
||||
describe('영수증 화면 배선', () => {
|
||||
it.each(['orderCompleteReceiptInjector.ts', 'mypageOrderShowInjector.ts'])(
|
||||
'%s 가 비회원 토큰 헤더를 경유한다',
|
||||
(file) => {
|
||||
const source = readFileSync(resolve(JS, file), 'utf-8');
|
||||
|
||||
expect(
|
||||
source.includes('buildOrderRequestHeaders'),
|
||||
`${file} 가 비회원 토큰을 싣지 않습니다 — 비회원 손님에게 영수증 버튼이 나타나지 않습니다.`
|
||||
).toBe(true);
|
||||
|
||||
expect(
|
||||
/localStorage\.getItem\('auth_token'\)/.test(source),
|
||||
`${file} 에 회원 전용 토큰 조회가 남아 있습니다 — 비회원 분기가 다시 막힙니다.`
|
||||
).toBe(false);
|
||||
}
|
||||
);
|
||||
|
||||
it('주문 상세 경로 판정이 비회원 주소도 매칭한다', () => {
|
||||
const source = readFileSync(resolve(JS, 'mypageOrderShowInjector.ts'), 'utf-8');
|
||||
const match = source.match(/const ORDER_SHOW_RE = (\/.+\/);/);
|
||||
|
||||
expect(match, '주문 상세 경로 정규식을 찾지 못했습니다.').not.toBeNull();
|
||||
|
||||
const re = new RegExp(match![1].slice(1, -1));
|
||||
|
||||
expect(re.test('/mypage/orders/12'), '회원 주문 상세 경로가 매칭되지 않습니다.').toBe(true);
|
||||
expect(
|
||||
re.test('/shop/guest/orders/20260904-0001'),
|
||||
'비회원 주문 상세 경로가 매칭되지 않습니다 — 그 화면에서는 영수증이 조회조차 되지 않습니다.'
|
||||
).toBe(true);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,62 @@
|
||||
/**
|
||||
* 비회원 주문 조회 토큰 확보 (플러그인 공용)
|
||||
*
|
||||
* 비회원 주문의 영수증·결제수단 정보는 서버가 `X-Guest-Order-Token` 으로 소유자를
|
||||
* 확인한다. 이 토큰을 싣지 않으면 서버는 그 주문을 찾을 수 없다고 응답하므로,
|
||||
* 비회원 손님에게는 영수증 버튼이 아예 나타나지 않는다 — 예외도 콘솔 오류도 남지
|
||||
* 않아 운영자가 원인을 알 수 없다.
|
||||
*
|
||||
* 코어 storageHandlers 가 sessionStorage 에 저장하며, 그 접근이 막힌 환경
|
||||
* (프라이빗 창·iframe)을 위해 전역 상태 폴백을 함께 본다.
|
||||
*/
|
||||
|
||||
/**
|
||||
* 회원 인증 토큰을 돌려줍니다.
|
||||
*
|
||||
* @return 토큰 또는 null
|
||||
*/
|
||||
export function getAuthToken(): string | null {
|
||||
return localStorage.getItem('auth_token');
|
||||
}
|
||||
|
||||
/**
|
||||
* 비회원 주문 조회 토큰을 돌려줍니다.
|
||||
*
|
||||
* @return 토큰 또는 null
|
||||
*/
|
||||
export function getGuestOrderToken(): string | null {
|
||||
try {
|
||||
const sessionToken = sessionStorage.getItem('g7_guest_order_token');
|
||||
if (sessionToken) return sessionToken;
|
||||
} catch {
|
||||
// sessionStorage 접근 불가 환경 — 전역 상태 폴백으로 진행
|
||||
}
|
||||
|
||||
const globalToken = (window as any).G7Core?.state?.get?.('_global')?.guestOrderToken;
|
||||
|
||||
return typeof globalToken === 'string' && globalToken !== '' ? globalToken : null;
|
||||
}
|
||||
|
||||
/**
|
||||
* 주문 조회 요청 헤더를 만듭니다. 회원 토큰을 우선하고, 없으면 비회원 토큰을 씁니다.
|
||||
*
|
||||
* @return 헤더 객체. 둘 다 없으면 null (호출 자체를 하지 않아야 함)
|
||||
*/
|
||||
export function buildOrderRequestHeaders(): Record<string, string> | null {
|
||||
const authToken = getAuthToken();
|
||||
const guestToken = getGuestOrderToken();
|
||||
|
||||
if (!authToken && !guestToken) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const headers: Record<string, string> = { Accept: 'application/json' };
|
||||
|
||||
if (authToken) {
|
||||
headers.Authorization = `Bearer ${authToken}`;
|
||||
} else if (guestToken) {
|
||||
headers['X-Guest-Order-Token'] = guestToken;
|
||||
}
|
||||
|
||||
return headers;
|
||||
}
|
||||
@@ -407,7 +407,13 @@ export async function requestPaymentHandler(action: PaymentAction, _context?: un
|
||||
|
||||
// 4-2. 과세/비과세 금액 조회 (optional — 실패해도 결제 진행)
|
||||
try {
|
||||
const orderRes = await G7Core.api.get(`/modules/sirsoft-ecommerce/user/orders/${pgPaymentData.order_number}`);
|
||||
// 비회원 주문은 X-Guest-Order-Token 이 없으면 서버가 주문을 찾지 못한다.
|
||||
// 헤더를 빼면 과세/비과세 금액이 조회되지 않아 결제사에 세금 구분이 빠진 채 전달된다.
|
||||
const guestToken = G7Core?.state?.get?.('_global')?.guestOrderToken;
|
||||
const orderRes = await G7Core.api.get(
|
||||
`/modules/sirsoft-ecommerce/user/orders/${pgPaymentData.order_number}`,
|
||||
guestToken ? { headers: { 'X-Guest-Order-Token': guestToken } } : undefined,
|
||||
);
|
||||
const od = orderRes?.data as Record<string, unknown> | null | undefined;
|
||||
if (od) {
|
||||
const taxAmt = Number(od['total_tax_amount'] ?? 0);
|
||||
|
||||
@@ -1,9 +1,13 @@
|
||||
import { buildOrderRequestHeaders } from './guestOrderToken';
|
||||
|
||||
const PLUGIN_ID = 'sirsoft-pay_nicepayments';
|
||||
const FLAG = '__nicepayOrderShowInjectorInstalled';
|
||||
const ROW_ID = 'nicepay-mp-receipt-row';
|
||||
const VBANK_BLOCK_ID = 'nicepay-mp-vbank-info';
|
||||
|
||||
const ORDER_SHOW_RE = /^\/mypage\/orders\/([^/]+)$/;
|
||||
// 회원 마이페이지(/mypage/orders/{N}) 와 비회원 주문 상세(/shop/guest/orders/{N}) 를 함께 매칭한다.
|
||||
// 비회원 경로를 빼면 그 화면에서는 영수증 정보가 조회조차 되지 않는다 (서버는 지원한다).
|
||||
const ORDER_SHOW_RE = /^(?:\/mypage\/orders\/([^/]+)|\/shop\/guest\/orders\/([^/]+))$/;
|
||||
|
||||
interface Payment {
|
||||
pg_provider?: string;
|
||||
@@ -42,16 +46,14 @@ function getOrderFromState(orderNumber: string): OrderData | null {
|
||||
}
|
||||
}
|
||||
|
||||
function getToken(): string | null {
|
||||
return localStorage.getItem('auth_token');
|
||||
}
|
||||
|
||||
async function fetchReceiptInfo(orderNumber: string): Promise<ReceiptInfo | null> {
|
||||
const token = getToken();
|
||||
if (!token) return null;
|
||||
const headers = buildOrderRequestHeaders();
|
||||
if (!headers) return null;
|
||||
try {
|
||||
const res = await fetch(`/api/plugins/${PLUGIN_ID}/user/orders/${orderNumber}/receipt`, {
|
||||
headers: { Authorization: `Bearer ${token}`, Accept: 'application/json' },
|
||||
headers,
|
||||
credentials: 'same-origin',
|
||||
});
|
||||
if (!res.ok) return null;
|
||||
return (await res.json()) as ReceiptInfo;
|
||||
@@ -250,7 +252,9 @@ function startPolling(orderNumber: string): void {
|
||||
|
||||
function onRouteChange(): void {
|
||||
const match = location.pathname.match(ORDER_SHOW_RE);
|
||||
if (match) startPolling(match[1]);
|
||||
// 회원 그룹(match[1]) 또는 비회원 그룹(match[2]) 중 한쪽이 채워진다.
|
||||
const segment = match?.[1] ?? match?.[2];
|
||||
if (segment) startPolling(segment);
|
||||
}
|
||||
|
||||
export function installMypageOrderShowInjector(): void {
|
||||
|
||||
+12
-10
@@ -1,3 +1,5 @@
|
||||
import { buildOrderRequestHeaders } from './guestOrderToken';
|
||||
|
||||
const PLUGIN_ID = 'sirsoft-pay_nicepayments';
|
||||
const FLAG = '__nicepayOcReceiptInjectorInstalled';
|
||||
const BTN_ID = 'nicepay-oc-receipt-btn';
|
||||
@@ -16,17 +18,16 @@ interface ReceiptInfo {
|
||||
payment_method_display_label?: string | null;
|
||||
}
|
||||
|
||||
function getToken(): string | null {
|
||||
return localStorage.getItem('auth_token');
|
||||
}
|
||||
|
||||
async function fetchPayment(orderNumber: string): Promise<Payment | null> {
|
||||
const token = getToken();
|
||||
if (!token) return null;
|
||||
// 회원 토큰 또는 비회원 주문 조회 토큰 중 하나는 있어야 한다. 비회원 분기를 비우면
|
||||
// 비회원 손님에게는 영수증 버튼이 아예 나타나지 않는다 (서버는 지원한다).
|
||||
const headers = buildOrderRequestHeaders();
|
||||
if (!headers) return null;
|
||||
|
||||
try {
|
||||
const res = await fetch(`/api/modules/sirsoft-ecommerce/user/orders/${orderNumber}`, {
|
||||
headers: { Authorization: `Bearer ${token}`, Accept: 'application/json' },
|
||||
headers,
|
||||
credentials: 'same-origin',
|
||||
});
|
||||
if (!res.ok) return null;
|
||||
const data = (await res.json()) as { data?: { payment?: Payment } };
|
||||
@@ -37,12 +38,13 @@ async function fetchPayment(orderNumber: string): Promise<Payment | null> {
|
||||
}
|
||||
|
||||
async function fetchReceiptInfo(orderNumber: string): Promise<ReceiptInfo | null> {
|
||||
const token = getToken();
|
||||
if (!token) return null;
|
||||
const headers = buildOrderRequestHeaders();
|
||||
if (!headers) return null;
|
||||
|
||||
try {
|
||||
const res = await fetch(`/api/plugins/${PLUGIN_ID}/user/orders/${orderNumber}/receipt`, {
|
||||
headers: { Authorization: `Bearer ${token}`, Accept: 'application/json' },
|
||||
headers,
|
||||
credentials: 'same-origin',
|
||||
});
|
||||
if (!res.ok) return null;
|
||||
return (await res.json()) as ReceiptInfo;
|
||||
|
||||
@@ -6,6 +6,10 @@
|
||||
|
||||
## [1.0.3] - 2026-09-04
|
||||
|
||||
### Fixed
|
||||
|
||||
- 비회원으로 결제하다 결제창을 닫았을 때 취소 이력이 남지 않던 문제를 고쳤습니다. 이력을 남기는 요청에 비회원 주문 확인값이 함께 가지 않아 서버가 그 주문을 찾지 못했고, 화면에는 평소와 같은 안내가 떠서 기록이 빠졌다는 사실이 드러나지 않았습니다.
|
||||
|
||||
### Security
|
||||
|
||||
- 결제창 프로그램을 불러오는 주소가 토스페이먼츠의 주소인지 불러오기 직전에 확인합니다. 확인되지 않는 주소면 결제를 진행하지 않고 안내를 표시합니다. 또한 결제창 프로그램이 실제로 준비되었는지를 기준으로 다음 단계를 진행하도록 바꿔, 프로그램이 아직 준비되지 않았는데 결제창이 열리지 않고 멈추던 상황을 없앴습니다.
|
||||
|
||||
@@ -1 +1 @@
|
||||
(function(){"use strict";const F="sirsoft-tosspayments",y="g7:sirsoft-tosspayments:pendingClose",C="/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 q(){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 j(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(C,n);return}await fetch(C,{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify(n),keepalive:!0})}async function B(){const e=q();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 j(e,n,o!==""?o:n)}catch(r){console.warn(`[${F}] failed to report payment failure`,r)}}}const H=["js.tosspayments.com"];function Y(e,t){const s=window?.G7Core?.t;if(typeof s!="function")return t;const n=`sirsoft-tosspayments.${e}`,o=s(n);return typeof o=="string"&&o!==n?o:t}function W(e){let t=null;try{t=new URL(e)}catch{t=null}if(t===null||t.protocol!=="https:"||!H.includes(t.hostname.toLowerCase()))throw new Error(Y("payment.error.sdk_url_untrusted","결제 모듈 주소가 올바르지 않아 결제를 진행할 수 없습니다."))}async function J(e){if(W(e),window.TossPayments)return;document.querySelectorAll(`script[src="${CSS.escape(e)}"]`).forEach(s=>s.remove());const t=window?.G7Core?.asset?.loadScript;if(typeof t=="function"){await t(e,{},{label:"tosspayments SDK"});return}await new Promise((s,n)=>{const o=document.createElement("script");o.src=e,o.async=!0,o.onload=()=>s(),o.onerror=()=>n(new Error(`Failed to load script: ${e}`)),document.head.appendChild(o)})}function V(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 I(e){if(e==="on")return!0;if(e==="off")return!1}function z(e,t){const s={validHours:e.vbank?.valid_hours??24},n=e.vbank?.cash_receipt_type??"";n&&(s.cashReceipt={type:n});const o=I(e.use_escrow);return o!==void 0&&(s.useEscrow=o),s}function v(e,t,s){if(t.use_escrow==="off")return;const n=s.escrow_products??[];n.length>0&&(e.escrowProducts=n)}async function Q(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 J(i.sdk_url),window.TossPayments||await new Promise(m=>setTimeout(m,100)),!window.TossPayments){console.error("[sirsoft-tosspayments] TossPayments SDK not available");return}const ye=window.TossPayments(i.client_key).payment({customerKey:n.customer_key??window.TossPayments.ANONYMOUS}),T=n.currency??"KRW",{method:d,easyPay:S}=V(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 K=window.location.origin,c={method:d,amount:{currency:T,value:n.amount},orderId:n.order_number,orderName:n.order_name,successUrl:K+i.callback_urls.success,failUrl:K+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=z(i,n),v(c,i,n);else if(d==="TRANSFER"){const m=I(i.use_escrow);m!==void 0&&(c.transfer={useEscrow:m}),v(c,i,n)}G({orderId:n.order_number,amount:n.amount,buyer_email:n.customer_email??"",buyer_phone:n.customer_phone??""}),await ye.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_meLine truncated
|
||||
(function(){"use strict";const F="sirsoft-tosspayments",f="g7:sirsoft-tosspayments:pendingClose",v="/api/plugins/sirsoft-tosspayments/payment/close-report";function p(){try{return window.sessionStorage??null}catch{return null}}function q(e){const t=p();if(t)try{t.setItem(f,JSON.stringify(e))}catch{}}function I(){const e=p();if(e)try{e.removeItem(f)}catch{}}function j(){const e=p();if(!e)return null;try{const t=e.getItem(f);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(v,n);return}await fetch(v,{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify(n),keepalive:!0})}async function H(){const e=j();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)){I();return}const n=t.get("error")??"",o=t.get("message")??"";if(!(n===""&&s==="")){I();try{await B(e,n,o!==""?o:n)}catch(r){console.warn(`[${F}] failed to report payment failure`,r)}}}const Y=["js.tosspayments.com"];function W(e,t){const s=window?.G7Core?.t;if(typeof s!="function")return t;const n=`sirsoft-tosspayments.${e}`,o=s(n);return typeof o=="string"&&o!==n?o:t}function J(e){let t=null;try{t=new URL(e)}catch{t=null}if(t===null||t.protocol!=="https:"||!Y.includes(t.hostname.toLowerCase()))throw new Error(W("payment.error.sdk_url_untrusted","결제 모듈 주소가 올바르지 않아 결제를 진행할 수 없습니다."))}async function V(e){if(J(e),window.TossPayments)return;document.querySelectorAll(`script[src="${CSS.escape(e)}"]`).forEach(s=>s.remove());const t=window?.G7Core?.asset?.loadScript;if(typeof t=="function"){await t(e,{},{label:"tosspayments SDK"});return}await new Promise((s,n)=>{const o=document.createElement("script");o.src=e,o.async=!0,o.onload=()=>s(),o.onerror=()=>n(new Error(`Failed to load script: ${e}`)),document.head.appendChild(o)})}function z(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 Q(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 L(e,t,s){if(t.use_escrow==="off")return;const n=s.escrow_products??[];n.length>0&&(e.escrowProducts=n)}async function X(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 V(i.sdk_url),window.TossPayments||await new Promise(y=>setTimeout(y,100)),!window.TossPayments){console.error("[sirsoft-tosspayments] TossPayments SDK not available");return}const S=window.TossPayments(i.client_key).payment({customerKey:n.customer_key??window.TossPayments.ANONYMOUS}),C=n.currency??"KRW",{method:d,easyPay:E}=z(i,r);if(C!=="KRW"&&(d!=="CARD"||E!==null)){console.warn("[sirsoft-tosspayments] non-KRW currency supports card only",{currency:C,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 K=window.location.origin,c={method:d,amount:{currency:C,value:n.amount},orderId:n.order_number,orderName:n.order_name,successUrl:K+i.callback_urls.success,failUrl:K+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},E&&(c.card.flowMode="DIRECT",c.card.easyPay=E);else if(d==="VIRTUAL_ACCOUNT")c.virtualAccount=Q(i,n),L(c,i,n);else if(d==="TRANSFER"){const y=A(i.use_escrow);y!==void 0&&(c.transfer={useEscrow:y}),L(c,i,n)}q({orderId:n.order_number,amount:n.amount,buyer_email:n.customer_email??"",buyer_phone:n.customer_phone??""}),await S.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{const u=o?.state?.get?.("_global")?.guestOrderToken,S=u?{headers:{"X-Guest-Order-Token":u}}:void 0;await o.api.post(`Line truncated
|
||||
@@ -39,6 +39,14 @@
|
||||
하나(카드 한 장)를 열지, 사용자가 고른 개별 토스 결제수단(`params.paymentMethodId`)을
|
||||
지정해 열지가 갈리지만(`params.paymentMethod`, 미지정 시 `_local.paymentMethod` 참조) 그
|
||||
분기도 이 핸들러 하나 안에서 처리합니다.
|
||||
|
||||
구매자가 결제창을 닫으면(`USER_CANCEL`) 이 핸들러가 이커머스 모듈의 결제 취소 기록
|
||||
엔드포인트(`orders/{orderNumber}/cancel-payment`)를 부릅니다. 이 엔드포인트는 회원과
|
||||
비회원이 공유하고 서버가 소유권을 대조하므로, 비회원 주문이면 `_global.guestOrderToken`
|
||||
을 `X-Guest-Order-Token` 헤더로 함께 보내야 합니다 — 그 토큰은 주문 생성 직후 체크아웃이
|
||||
발급합니다. 헤더가 빠지면 서버가 404 로 거부하는데, 여기서는 `console.warn` 만 남기고
|
||||
취소 안내 모달이 평소대로 뜨기 때문에 이력이 유실된 사실이 화면에 드러나지 않습니다.
|
||||
`G7Core.api` 는 레이아웃의 `globalHeaders` 를 타지 않으므로 헤더는 호출부가 직접 붙입니다.
|
||||
<!-- @intent END -->
|
||||
|
||||
## 전역 진입점
|
||||
|
||||
+24
-3
@@ -27,7 +27,7 @@ const CLIENT_CONFIG_DATA = {
|
||||
describe('requestPaymentHandler', () => {
|
||||
let mockG7Core: {
|
||||
api: { get: ReturnType<typeof vi.fn>; post: ReturnType<typeof vi.fn> };
|
||||
state: { setLocal: ReturnType<typeof vi.fn> };
|
||||
state: { setLocal: ReturnType<typeof vi.fn>; get: ReturnType<typeof vi.fn> };
|
||||
modal: { open: ReturnType<typeof vi.fn> };
|
||||
};
|
||||
|
||||
@@ -37,7 +37,7 @@ describe('requestPaymentHandler', () => {
|
||||
get: vi.fn().mockResolvedValue(CLIENT_CONFIG_DATA),
|
||||
post: vi.fn().mockResolvedValue({ success: true }),
|
||||
},
|
||||
state: { setLocal: vi.fn() },
|
||||
state: { setLocal: vi.fn(), get: vi.fn().mockReturnValue({}) },
|
||||
modal: { open: vi.fn() },
|
||||
};
|
||||
(window as any).G7Core = mockG7Core;
|
||||
@@ -136,7 +136,28 @@ describe('requestPaymentHandler', () => {
|
||||
{
|
||||
cancel_code: 'USER_CANCEL',
|
||||
cancel_message: 'User cancelled',
|
||||
}
|
||||
},
|
||||
undefined
|
||||
);
|
||||
|
||||
consoleInfoSpy.mockRestore();
|
||||
consoleErrorSpy.mockRestore();
|
||||
});
|
||||
|
||||
it('비회원 컨텍스트에서는 취소 기록에 X-Guest-Order-Token 헤더를 첨부한다', async () => {
|
||||
// 이 엔드포인트는 회원/비회원 공유라 서버가 소유권을 대조한다. 토큰이 빠지면
|
||||
// 서버가 404 로 거부하는데 화면은 console.warn 만 남기고 평소대로 취소 안내를
|
||||
// 띄우므로, 이력이 유실된 사실이 어디에도 드러나지 않는다.
|
||||
const consoleInfoSpy = vi.spyOn(console, 'info').mockImplementation(() => {});
|
||||
const consoleErrorSpy = vi.spyOn(console, 'error').mockImplementation(() => {});
|
||||
mockG7Core.state.get.mockReturnValue({ guestOrderToken: 'guest-token-abc' });
|
||||
|
||||
await callWithCancel();
|
||||
|
||||
expect(mockG7Core.api.post).toHaveBeenCalledWith(
|
||||
'/modules/sirsoft-ecommerce/orders/ORD-002/cancel-payment',
|
||||
expect.anything(),
|
||||
{ headers: { 'X-Guest-Order-Token': 'guest-token-abc' } }
|
||||
);
|
||||
|
||||
consoleInfoSpy.mockRestore();
|
||||
|
||||
@@ -400,13 +400,24 @@ export async function requestPaymentHandler(action: any, _context?: any): Promis
|
||||
console.info('[sirsoft-tosspayments] Payment cancelled by user');
|
||||
|
||||
// 1. 결제 취소 이력 기록 API 호출 (PG사 응답값 전달)
|
||||
//
|
||||
// 이 엔드포인트는 회원/비회원 공유라 서버가 소유권을 대조한다. 비회원 주문은 조회
|
||||
// 토큰이 그 증명이므로 반드시 함께 보낸다 — 빠지면 서버가 404 로 거부하고, 여기서는
|
||||
// console.warn 만 남긴 채 취소 안내 모달이 평소대로 떠서 이력 유실이 드러나지 않는다.
|
||||
// 토큰은 주문 생성 직후 체크아웃이 발급해 _global.guestOrderToken 에 넣어 둔다.
|
||||
try {
|
||||
const guestToken = G7Core?.state?.get?.('_global')?.guestOrderToken;
|
||||
const config = guestToken
|
||||
? { headers: { 'X-Guest-Order-Token': guestToken } }
|
||||
: undefined;
|
||||
|
||||
await G7Core.api.post(
|
||||
`/modules/sirsoft-ecommerce/orders/${pgPaymentData.order_number}/cancel-payment`,
|
||||
{
|
||||
cancel_code: error.code,
|
||||
cancel_message: error.message,
|
||||
}
|
||||
},
|
||||
config
|
||||
);
|
||||
} catch (e) {
|
||||
console.warn('[sirsoft-tosspayments] Failed to record cancellation', e);
|
||||
|
||||
Reference in new issue
Block a user