fix(payment): NHN KCP 간편결제 메타와 중복 콜백 처리 보강

This commit is contained in:
thisgun committed 2026-07-03 19:03:54 +09:00
1 parent 76f7300e8f
commit 2a9f521487
10 files changed
+193 -27

No files matched your search

@@ -4,26 +4,6 @@
형식은 [Keep a Changelog](https://keepachangelog.com/ko/1.1.0/)를 따르며,
[Semantic Versioning](https://semver.org/lang/ko/)을 준수합니다.
## [Unreleased]
### Security
- 가상계좌 입금통보와 에스크로 공통통보가 주문번호만으로 처리되지 않도록 저장된 KCP 거래번호, site_cd, 계좌번호, 금액을 교차 검증하도록 보강했습니다.
- 모바일 승인키 발급 시 주문 소유자와 결제금액을 검증해 타인 주문번호 또는 변조 금액으로 승인키가 발급되지 않도록 차단했습니다.
- 무서명 브라우저 실패 콜백만으로 진행 중 주문이 취소/실패 상태로 바뀌지 않도록 차단했습니다.
- NHN KCP가 지원하지 않는 비-KRW 주문이 결제창/승인 콜백으로 진행되지 않도록 서버와 프론트 가드를 추가했습니다.
- KCP CLI 디버그 로그와 에스크로 배송등록 PG 응답 저장에서 비밀키, 카드번호, 수령자 개인정보 등 원문 민감값이 남지 않도록 축소했습니다.
- 에스크로 공통통보 replay 시 동일 payload가 내부 hook을 중복 발행하지 않도록 보강했습니다.
### Fixed
- 플러그인 설정 화면에 NHN KCP 상점관리자의 결제취소 서버 IP 등록 필요 안내와 서버 IP 복사 기능을 추가해 운영 모드 결제취소 실패 원인을 사전에 확인할 수 있도록 했습니다.
- 관리자 주문목록과 주문상세 레이아웃이 리뉴얼되거나 플러그인 업데이트 과정에서 NHN KCP 테스트결제 배지, 테스트 모드 안내, 결제 조회/결제 정보 패널이 누락될 수 있던 문제를 수정했습니다.
- 복합과세 모바일/PC 결제 필드의 공급가액, 부가세, 비과세 합계가 할인/마일리지 반영 후 실결제액과 일치하도록 재배분했습니다.
- 에스크로 테스트 site_cd가 비어 있으면 빈 값이 아닌 일반 테스트 site_cd로 fallback되도록 보정했습니다.
- 환불 처리 시 결제 당시 KCP site_cd와 테스트/운영 모드를 복원하도록 보강했습니다.
- KCP webhook IP 가드가 설정 누락 시 테스트 모드로 우회되지 않고 차단되도록 변경했습니다.
## [1.0.0-beta.5] - 2026-06-23
### Fixed
@@ -40,8 +20,25 @@
- 레이아웃 편집기에서 이 플러그인의 설정 화면을 테스트 모드/운영 모드 상태로 전환해 미리볼 수 있도록 했습니다.
- 레이아웃 편집기 데이터 소스 목록에서 이 확장이 제공하는 데이터 소스가 친화 명칭으로 표시되고, 어느 확장이 제공했는지 출처가 함께 표시됩니다.
### Security
- 가상계좌 입금통보와 에스크로 공통통보가 주문번호만으로 처리되지 않도록 저장된 KCP 거래번호, site_cd, 계좌번호, 금액을 교차 검증하도록 보강했습니다.
- 모바일 승인키 발급 시 주문 소유자와 결제금액을 검증해 타인 주문번호 또는 변조 금액으로 승인키가 발급되지 않도록 차단했습니다.
- 무서명 브라우저 실패 콜백만으로 진행 중 주문이 취소/실패 상태로 바뀌지 않도록 차단했습니다.
- NHN KCP가 지원하지 않는 비-KRW 주문이 결제창/승인 콜백으로 진행되지 않도록 서버와 프론트 가드를 추가했습니다.
- KCP CLI 디버그 로그와 에스크로 배송등록 PG 응답 저장에서 비밀키, 카드번호, 수령자 개인정보 등 원문 민감값이 남지 않도록 축소했습니다.
- 에스크로 공통통보 replay 시 동일 payload가 내부 hook을 중복 발행하지 않도록 보강했습니다.
### Fixed
- NHN KCP 간편결제 성공 시 원 결제수단이 주문 결제 메타와 간편결제 PG 필드에 보존되도록 보강했습니다.
- 이미 결제 완료된 주문의 카드 승인 콜백이 중복 도착하면 KCP 승인 API를 다시 호출하지 않고 멱등 성공 응답으로 처리하도록 보강했습니다.
- 플러그인 설정 화면에 NHN KCP 상점관리자의 결제취소 서버 IP 등록 필요 안내와 서버 IP 복사 기능을 추가해 운영 모드 결제취소 실패 원인을 사전에 확인할 수 있도록 했습니다.
- 관리자 주문목록과 주문상세 레이아웃이 리뉴얼되거나 플러그인 업데이트 과정에서 NHN KCP 테스트결제 배지, 테스트 모드 안내, 결제 조회/결제 정보 패널이 누락될 수 있던 문제를 수정했습니다.
- 복합과세 모바일/PC 결제 필드의 공급가액, 부가세, 비과세 합계가 할인/마일리지 반영 후 실결제액과 일치하도록 재배분했습니다.
- 에스크로 테스트 site_cd가 비어 있으면 빈 값이 아닌 일반 테스트 site_cd로 fallback되도록 보정했습니다.
- 환불 처리 시 결제 당시 KCP site_cd와 테스트/운영 모드를 복원하도록 보강했습니다.
- KCP webhook IP 가드가 설정 누락 시 테스트 모드로 우회되지 않고 차단되도록 변경했습니다.
- 이커머스 관리자 주문설정 결제수단 목록에서 NHN KCP 간편결제 항목이 브랜드 텍스트 배지로 표시되도록 보강했습니다.
- 체크아웃에서 주문설정으로 활성화한 NHN KCP 간편결제가 숨겨지거나 KG 이니시스 브랜드 문구로 잘못 보정되는 문제를 수정했습니다.
- 결제 취소/부분취소 시 KCP CLI 내부 필드 구분자가 안전성 검사에 막혀 취소 요청이 실패할 수 있던 문제를 수정했습니다.
+2 -2
View File
@@ -1,4 +1,4 @@
(function(){"use strict";function Qe(e){return/^https?:\/\//i.test(e)||e.startsWith("/api/")?e:e.startsWith("/plugins/")?`/api${e}`:e.startsWith("plugins/")?`/api/${e}`:e}function Xe(e){return e.trim().slice(0,160)}function Ze(e){if(e)return e.replace(/\/payment\/close-report$/,"/payment/retry")}async function ie(e,t,n=!1){const r=window.G7Core?.api;if(typeof r?.post=="function"){await r.post(e,t);return}const a=await fetch(Qe(e),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t),keepalive:n});if(!a.ok){let o=`NHN KCP payment request failed (${a.status})`;try{const s=await a.json(),i=Array.isArray(s?.errors?.message)?s.errors.message[0]:s?.error??s?.message;typeof i=="string"&&i.trim()!==""&&(o=i)}catch{}throw new Error(o)}}async function et(e){const t=Ze(e.closeReportUrl);t&&await ie(t,{oid:e.oid,price:Number(e.price),buyer_email:e.buyer_email??"",buyer_phone:e.buyer_phone??"",payment_method:e.payment_method??""})}async function tt(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:Xe(t)||"kcp-window-closed"};try{await ie(e.closeReportUrl,n,!0)}catch(r){console.warn("[sirsoft-pay_nhnkcp] failed to report payment window close",r)}}const nt="nhnkcp_applepay";function I(e){return e===nt}function K(){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 $(){return((typeof document<"u"?document.documentElement.lang:"")||"").toLowerCase().startsWith("ko")?"애플페이는 IOS 기기에 모바일결제만 가능합니다.":"Apple Pay is available only for mobile payments on iOS devices."}function B(e){return(e??"KRW").trim().toUpperCase()||"KRW"}function rt(e){return B(e)==="KRW"}function at(e){const t=B(e);return((typeof document<"u"?document.documentElement.lang:"")||"").toLowerCase().startsWith("ko")?`NHN KCP는 KRW 결제만 지원합니다. (${t})`:`NHN KCP supports KRW payments only. (${t})`}function ot(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))),a=Math.max(0,Math.round(Number(e.vat_amount??0))),o=Math.max(0,t-n),s=o>0&&r>0&&a>0?Math.min(o,Math.round(o*(a/r))):0,i=o-s;return{tax_flag:"TG03",comm_tax_mny:String(i),comm_vat_mny:String(s),comm_free_mny:String(n)}}class D extends Error{constructor(t){super(t??"결제가 취소되었습니다."),this.name="KcpCancelledError"}}const it={card:"100000000000",bank_transfer:"010000000000",virtual_account:"001000000000",mobile:"000010000000",bank:"010000000000",vbank:"001000000000",phone:"000010000000"},st={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 ct(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 dt(e,t){let n=!1,r,a;const o=()=>{n=!0,a&&(a.disconnect(),a=void 0),r!==void 0&&(window.clearInterval(r),r=void 0)},s=()=>{n||!ct(e)||(o(),t())},i=document.body??document.documentElement;return i&&typeof MutationObserver<"u"&&(a=new MutationObserver(s),a.observe(i,{attributes:!0,attributeFilter:["class","hidden","style"],childList:!0,subtree:!0})),r=window.setInterval(s,300),o}function lt(){if(typeof navigator>"u")return!1;if(K())return!0;const e=navigator;if(e.userAgentData?.mobile!==void 0)return e.userAgentData.mobile;const t=(navigator.userAgent||"").toLowerCase();return!!(/android|iphone|ipod|windows phone|iemobile|blackberry|opera mini|mobile safari/.test(t)||(navigator.maxTouchPoints??0)>1&&!t.includes("windows")&&!t.includes("macintosh"))}async function se(e,t){const{pgPaymentData:n,paymentMethod:r}=e.params||{};if(!n){console.error("[sirsoft-pay_nhnkcp] pgPaymentData is required");return}const a=r??n.pay_method??"card",o=typeof a=="string"&&a.startsWith("nhnkcp_"),s=window.G7Core;let i=null;try{if(!rt(n.currency)){const u=at(n.currency);s?.state?.setLocal?.({paymentErrorMessage:u,isSubmittingOrder:!1,paymentMethod:a}),s?.modal?.open?.("nhnkcp_payment_error_modal");return}if(I(a)&&!K()){const u=$();s?.state?.setLocal?.({paymentErrorMessage:u,isSubmittingOrder:!1,paymentMethod:a}),s?.modal?.open?.("nhnkcp_payment_error_modal");return}const c=await s.api.get("/modules/sirsoft-ecommerce/payments/client-config/nhnkcp");if(!c.data){console.error("[sirsoft-pay_nhnkcp] Failed to fetch client config",c);return}const l=c.data;i={closeReportUrl:l.callback_urls.close_report,oid:n.order_number,price:Number(n.Line truncated
(function(){"use strict";function Xe(e){return/^https?:\/\//i.test(e)||e.startsWith("/api/")?e:e.startsWith("/plugins/")?`/api${e}`:e.startsWith("plugins/")?`/api/${e}`:e}function Ze(e){return e.trim().slice(0,160)}function et(e){if(e)return e.replace(/\/payment\/close-report$/,"/payment/retry")}async function ie(e,t,n=!1){const r=window.G7Core?.api;if(typeof r?.post=="function"){await r.post(e,t);return}const a=await fetch(Xe(e),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t),keepalive:n});if(!a.ok){let o=`NHN KCP payment request failed (${a.status})`;try{const s=await a.json(),i=Array.isArray(s?.errors?.message)?s.errors.message[0]:s?.error??s?.message;typeof i=="string"&&i.trim()!==""&&(o=i)}catch{}throw new Error(o)}}async function tt(e){const t=et(e.closeReportUrl);t&&await ie(t,{oid:e.oid,price:Number(e.price),buyer_email:e.buyer_email??"",buyer_phone:e.buyer_phone??"",payment_method:e.payment_method??""})}async function nt(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:Ze(t)||"kcp-window-closed"};try{await ie(e.closeReportUrl,n,!0)}catch(r){console.warn("[sirsoft-pay_nhnkcp] failed to report payment window close",r)}}const rt="nhnkcp_applepay";function I(e){return e===rt}function K(){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 $(){return((typeof document<"u"?document.documentElement.lang:"")||"").toLowerCase().startsWith("ko")?"애플페이는 IOS 기기에 모바일결제만 가능합니다.":"Apple Pay is available only for mobile payments on iOS devices."}function B(e){return(e??"KRW").trim().toUpperCase()||"KRW"}function at(e){return B(e)==="KRW"}function ot(e){const t=B(e);return((typeof document<"u"?document.documentElement.lang:"")||"").toLowerCase().startsWith("ko")?`NHN KCP는 KRW 결제만 지원합니다. (${t})`:`NHN KCP supports KRW payments only. (${t})`}function it(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))),a=Math.max(0,Math.round(Number(e.vat_amount??0))),o=Math.max(0,t-n),s=o>0&&r>0&&a>0?Math.min(o,Math.round(o*(a/r))):0,i=o-s;return{tax_flag:"TG03",comm_tax_mny:String(i),comm_vat_mny:String(s),comm_free_mny:String(n)}}class j extends Error{constructor(t){super(t??"결제가 취소되었습니다."),this.name="KcpCancelledError"}}const st={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 ct(e,t){const n=e.toLowerCase();return!t||!Object.prototype.hasOwnProperty.call(se,n)?{}:{param_opt_1:n,nhnkcp_easy_pay_method:n}}function dt(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 lt(e,t){let n=!1,r,a;const o=()=>{n=!0,a&&(a.disconnect(),a=void 0),r!==void 0&&(window.clearInterval(r),r=void 0)},s=()=>{n||!dt(e)||(o(),t())},i=document.body??document.documentElement;return i&&typeof MutationObserver<"u"&&(a=new MutationObserver(s),a.observe(i,{attributes:!0,attributeFilter:["class","hidden","style"],childList:!0,subtree:!0})),r=window.setInterval(s,300),o}function ut(){if(typeof navigator>"u")return!1;if(K())return!0;const e=navigator;if(e.userAgentData?.mobile!==void 0)return e.userAgentData.mobile;const t=(navigator.userAgent||"").toLowerCase();return!!(/android|iphone|ipod|windows phone|iemobile|blackberry|opera mini|mobile safari/.test(t)||(navigator.maxTouchPoints??0)>1&&!t.includes("windows")&&!t.includes("macintosh"))}async function ce(e,t){const{pgPaymentData:n,paymentMethod:r}=e.params||{};if(!n){console.error("[sirsoft-pay_nhnkcp] pgPaymentData is required");return}const a=r??n.pay_method??"card",o=typeof a=="string"&&a.startsWith("nhnkcp_"),s=window.G7Core;let i=null;try{if(!at(n.currency)){const u=ot(n.currency);s?.state?.setLocal?.({paymentErrorMessage:u,isSubmittingOrder:!1,paymentMethod:a}),s?.modal?.open?.("nhnkcp_payment_error_modal");return}if(I(a)&&!K()){const u=$();s?.state?.setLocal?.({paymentErrorMessage:u,isSubmittingOrder:!1,paymentMethod:a}),s?.modal?.open?.("nhnkcp_payment_error_modal");return}const c=await s.api.get("/modules/sirsoft-ecommerce/payments/client-config/nhnkcp");if(!c.data){console.error("[sirsoft-pay_nhnkcpLine truncated
<script src="${e.sdk_url}"><\/script>
</head><body style="margin:0;padding:0;background:transparent;">
<form name="order_info">${c}</form>
@@ -14,5 +14,5 @@ try {
window.__kcpFail && window.__kcpFail(e);
}
<\/script>
</body></html>`),N.close(),h=window.setTimeout(()=>{v(new Error("KCP SDK load timeout"))},15e3),f.__kcpReady=()=>{h!==void 0&&(clearTimeout(h),h=void 0)}})}const mt={nhnkcp_payco:"PAYCO",nhnkcp_naverpay:"네이버페이",nhnkcp_naverpay_point:"네이버페이 포인트",nhnkcp_kakaopay:"카카오페이",nhnkcp_applepay:"Apple Pay"},yt="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 ft(e){const t=ce();if(!t)return;const n=mt[e];t.querySelectorAll("button").forEach(r=>{r.textContent?.trim()===n?(r.style.boxShadow=yt,r.style.outline="none"):(r.style.boxShadow="",r.style.outline="")})}function ht(e){const t=e.params?.paymentMethod;if(!t)return;const n=window.G7Core;if(I(t)&&!K()){const a=$();n?.state?.setLocal?.({paymentErrorMessage:a,isSubmittingOrder:!1}),n?.modal?.open?.("nhnkcp_payment_error_modal"),de();return}const r=typeof t=="string"&&t.startsWith("nhnkcp_");n?.state?.setLocal?.({paymentMethod:t,serverPaymentMethod:r?"card":t}),r?ft(t):de()}function gt(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 _t(e){const t=String(e.params?.text??"");if(t!==""){if(navigator.clipboard&&typeof navigator.clipboard.writeText=="function"){await navigator.clipboard.writeText(t);return}gt(t)}}const le={requestPayment:se,setPaymentMethod:ht,copyToClipboard:_t},ue="/api/modules/sirsoft-ecommerce/user/orders",wt="sirsoft-nhnkcp",j="sirsoft-pay_nhnkcp",pe="nhnkcp_",k={info:(...e)=>console.info(`[${j}]`,...e),warn:(...e)=>console.warn(`[${j}]`,...e),error:(...e)=>console.error(`[${j}]`,...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 kt(e,t){return t?.method?t.method.toUpperCase():typeof Request<"u"&&e instanceof Request?e.method.toUpperCase():"GET"}function bt(e,t){if(t!=="POST")return!1;const n=e.split("?")[0].split("#")[0];return n===ue||n.endsWith(ue)}function Nt(){return window.location.pathname+window.location.search+window.location.hash}function Ct(e,t){const n=JSON.stringify(t);return new Response(n,{status:e.status,statusText:e.statusText,headers:e.headers})}function xt(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 me(e){try{return JSON.parse(e).payment_method}catch{return}}function vt(e,t){try{const n=JSON.parse(e);return n.payment_method=t,JSON.stringify(n)}catch{return e}}function Et(){if(typeof window>"u"||typeof window.fetch!="function")return;const e="__sirsoftNhnkcpInterceptorInstalled",t=window;if(t[e])return;t[e]=!0;const n="__sirsoftPgOriginalFetch";t[n]||(t[n]=window.fetch.bind(window));const r=t[n],a=window.fetch.bind(window);window.fetch=async function(s,i){const c=Pt(s),l=kt(s,i);if(!bt(c,l))return a(s,i);let d,u=i;if(i?.body&&typeof i.body=="string"){const p=me(i.body);typeof p=="string"&&p.startsWith(pe)&&(d=p,u={...i,body:vt(i.body,"card")},k.info(`easy pay detected: replacing payment_method '${p}' → 'card'`))}if(!d)try{const p=window.G7Core?.state?.getLocal?.()?.paymentMethod;typeof p=="string"&&p.startsWith(pe)&&(d=p,k.info(`easy pay detected from local state: '${p}'`))}catch{}if(I(d)&&!K()){const p=$();return k.warn(p),xt(p)}const f=await(d?r:a)(s,u);let x;try{x=f.clone()}catch{return f}let h=null;try{h=await x.json()}catch{return f}const m=h?.data;if(!m)return f;const oe=m.requires_pg_payment===!0,v=m.pg_provider===wt;if(!d&&(!oe||!v)||d&&!m.order&&!m.pg_payment_data)return f;let w=m.pg_payment_data;if(!w&&d&&m.order){const p=m.order,_=p.options,P=_?.[0]?.product_name??String(p.order_number??""),T=(_?.length??0)>1?`${P} 외 ${(_?.length??0)-1}건`:P;w={order_number:p.order_number,order_name:T,amount:Math.floor(Number(p.total_due_amount??p.total_amount??0)),currency:"KRW",customer_name:p.orderer_name??null,customer_email:p.orderer_email??null,customer_phone:String(p.orderer_phone??"").replace(/[^0-9]/g,"")},k.info("pg_payment_data constructed from order (기본 PG가 타 PG)",{order_number:w.order_number,amount:w.amount})}if(!w)return k.warn("nhnkcp order detected but pg_payment_data missing"),f;k.info("intercepted order create response — opening PG popup");const N=m.order?{tax_amount:m.order.total_tax_amount??0,vat_amount:m.order.total_vat_amount??0,tax_free_amount:m.order.total_tax_free_amount??0}:{},g=!d&&u?.body&&typeof u.body=="string"?(()=>{const p=me(u.body);return p?{...w,pay_method:p,...N}:{...w,...N}})():{...w,...N};se({params:{pgPaymentData:g,paymentMethod:d}});const E={...h,data:{...m,requires_pg_payment:!1,redirect_url:Nt()}};Line truncated
</body></html>`),N.close(),h=window.setTimeout(()=>{v(new Error("KCP SDK load timeout"))},15e3),f.__kcpReady=()=>{h!==void 0&&(clearTimeout(h),h=void 0)}})}const yt={nhnkcp_payco:"PAYCO",nhnkcp_naverpay:"네이버페이",nhnkcp_naverpay_point:"네이버페이 포인트",nhnkcp_kakaopay:"카카오페이",nhnkcp_applepay:"Apple Pay"},ft="0 0 0 2px #ffffff, 0 0 0 5px rgba(0,0,0,0.55)";function de(){return document.querySelector(".nhnkcp-easy-pay-btns")??null}function le(){const e=de();e&&e.querySelectorAll("button").forEach(t=>{t.style.boxShadow="",t.style.outline=""})}function ht(e){const t=de();if(!t)return;const n=yt[e];t.querySelectorAll("button").forEach(r=>{r.textContent?.trim()===n?(r.style.boxShadow=ft,r.style.outline="none"):(r.style.boxShadow="",r.style.outline="")})}function _t(e){const t=e.params?.paymentMethod;if(!t)return;const n=window.G7Core;if(I(t)&&!K()){const a=$();n?.state?.setLocal?.({paymentErrorMessage:a,isSubmittingOrder:!1}),n?.modal?.open?.("nhnkcp_payment_error_modal"),le();return}const r=typeof t=="string"&&t.startsWith("nhnkcp_");n?.state?.setLocal?.({paymentMethod:t,serverPaymentMethod:r?"card":t}),r?ht(t):le()}function gt(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 wt(e){const t=String(e.params?.text??"");if(t!==""){if(navigator.clipboard&&typeof navigator.clipboard.writeText=="function"){await navigator.clipboard.writeText(t);return}gt(t)}}const ue={requestPayment:ce,setPaymentMethod:_t,copyToClipboard:wt},pe="/api/modules/sirsoft-ecommerce/user/orders",Pt="sirsoft-nhnkcp",D="sirsoft-pay_nhnkcp",me="nhnkcp_",k={info:(...e)=>console.info(`[${D}]`,...e),warn:(...e)=>console.warn(`[${D}]`,...e),error:(...e)=>console.error(`[${D}]`,...e)};function kt(e){return typeof e=="string"?e:e instanceof URL?e.toString():typeof Request<"u"&&e instanceof Request?e.url:String(e)}function bt(e,t){return t?.method?t.method.toUpperCase():typeof Request<"u"&&e instanceof Request?e.method.toUpperCase():"GET"}function Nt(e,t){if(t!=="POST")return!1;const n=e.split("?")[0].split("#")[0];return n===pe||n.endsWith(pe)}function Ct(){return window.location.pathname+window.location.search+window.location.hash}function xt(e,t){const n=JSON.stringify(t);return new Response(n,{status:e.status,statusText:e.statusText,headers:e.headers})}function vt(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 ye(e){try{return JSON.parse(e).payment_method}catch{return}}function Et(e,t){try{const n=JSON.parse(e);return n.payment_method=t,JSON.stringify(n)}catch{return e}}function At(){if(typeof window>"u"||typeof window.fetch!="function")return;const e="__sirsoftNhnkcpInterceptorInstalled",t=window;if(t[e])return;t[e]=!0;const n="__sirsoftPgOriginalFetch";t[n]||(t[n]=window.fetch.bind(window));const r=t[n],a=window.fetch.bind(window);window.fetch=async function(s,i){const c=kt(s),l=bt(s,i);if(!Nt(c,l))return a(s,i);let d,u=i;if(i?.body&&typeof i.body=="string"){const p=ye(i.body);typeof p=="string"&&p.startsWith(me)&&(d=p,u={...i,body:Et(i.body,"card")},k.info(`easy pay detected: replacing payment_method '${p}' → 'card'`))}if(!d)try{const p=window.G7Core?.state?.getLocal?.()?.paymentMethod;typeof p=="string"&&p.startsWith(me)&&(d=p,k.info(`easy pay detected from local state: '${p}'`))}catch{}if(I(d)&&!K()){const p=$();return k.warn(p),vt(p)}const f=await(d?r:a)(s,u);let x;try{x=f.clone()}catch{return f}let h=null;try{h=await x.json()}catch{return f}const m=h?.data;if(!m)return f;const oe=m.requires_pg_payment===!0,v=m.pg_provider===Pt;if(!d&&(!oe||!v)||d&&!m.order&&!m.pg_payment_data)return f;let w=m.pg_payment_data;if(!w&&d&&m.order){const p=m.order,g=p.options,P=g?.[0]?.product_name??String(p.order_number??""),T=(g?.length??0)>1?`${P} 외 ${(g?.length??0)-1}건`:P;w={order_number:p.order_number,order_name:T,amount:Math.floor(Number(p.total_due_amount??p.total_amount??0)),currency:"KRW",customer_name:p.orderer_name??null,customer_email:p.orderer_email??null,customer_phone:String(p.orderer_phone??"").replace(/[^0-9]/g,"")},k.info("pg_payment_data constructed from order (기본 PG가 타 PG)",{order_number:w.order_number,amount:w.amount})}if(!w)return k.warn("nhnkcp order detected but pg_payment_data missing"),f;k.info("intercepted order create response — opening PG popup");const N=m.order?{tax_amount:m.order.total_tax_amount??0,vat_amount:m.order.total_vat_amount??0,tax_free_amount:m.order.total_tax_free_amount??0}:{},_=!d&&u?.body&&typeof u.body=="string"?(()=>{const p=ye(u.body);return p?{...w,pay_method:p,...N}:{...w,...N}})():{...w,...N};ce({params:{pgPaymentData:_,paymentMethod:d}});const E={...h,data:{...m,requires_pg_payment:!1,redirect_url:Ct()}};Line truncated
//# sourceMappingURL=plugin.iife.js.map
@@ -1 +1 @@
{"version":3,"file":"plugin.iife.js","sources":["../../resources/js/paymentCloseReport.ts","../../resources/js/support/applePayDevice.ts","../../resources/js/handlers/requestPayment.ts","../../resources/js/handlers/setPaymentMethod.ts","../../resources/js/handlers/copyToClipboard.ts","../../resources/js/handlers/index.ts","../../resources/js/orderResponseInterceptor.ts","../../resources/js/orderCompleteReceiptInjector.ts","../../resources/js/mypageOrderShowInjector.ts","../../resources/js/checkoutEasyPayInjector.ts","../../resources/js/adminApplePayNoticeInjector.ts","../../resources/js/adminPaymentMethodBrandInjector.ts","../../resources/js/index.ts"],"sourcesContent":["export interface PaymentCloseReportContext {\n closeReportUrl?: string;\n oid: string;\n price: number;\n buyer_email?: string;\n buyer_phone?: string;\n payment_method?: string;\n}\n\nfunction resolveApiUrl(url: string): string {\n if (/^https?:\\/\\//i.test(url) || url.startsWith('/api/')) {\n return url;\n }\n\n if (url.startsWith('/plugins/')) {\n return `/api${url}`;\n }\n\n if (url.startsWith('plugins/')) {\n return `/api/${url}`;\n }\n\n return url;\n}\n\nfunction trimReason(reason: string): string {\n return reason.trim().slice(0, 160);\n}\n\nfunction resolveRetryUrl(closeReportUrl?: string): string | undefined {\n if (!closeReportUrl) {\n return undefined;\n }\n\n return closeReportUrl.replace(/\\/payment\\/close-report$/, '/payment/retry');\n}\n\nasync function postPaymentContext(url: string, payload: Record<string, unknown>, keepalive = false): Promise<void> {\n const apiClient = ((window as any).G7Core)?.api;\n if (typeof apiClient?.post === 'function') {\n await apiClient.post(url, payload);\n return;\n }\n\n const response = await fetch(resolveApiUrl(url), {\n method: 'POST',\n headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify(payload),\n keepalive,\n });\n\n if (!response.ok) {\n let message = `NHN KCP payment request failed (${response.status})`;\n try {\n const data = await response.json();\n const responseMessage = Array.isArray(data?.errors?.message)\n ? data.errors.message[0]\n : data?.error ?? data?.message;\n if (typeof responseMessage === 'string' && responseMessage.trim() !== '') {\n message = responseMessage;\n }\n } catch {\n // JSON 응답이 아니면 HTTP 상태 메시지를 사용한다.\n }\n throw new Error(message);\n }\n}\n\nexport async function preparePaymentRetry(context: PaymentCloseReportContext): Promise<void> {\n const retryUrl = resolveRetryUrl(context.closeReportUrl);\n if (!retryUrl) {\n return;\n }\n\n await postPaymentContext(retryUrl, {\n oid: context.oid,\n price: Number(context.price),\n buyer_email: context.buyer_email ?? '',\n buyer_phone: context.buyer_phone ?? '',\n payment_method: context.payment_method ?? '',\n });\n}\n\nexport async function reportPaymentWindowClosed(\n context: PaymentCloseReportContext,\n reason = 'kcp-window-closed',\n): Promise<void> {\n if (!context.closeReportUrl) {\n return;\n }\n\n const payload = {\n oid: context.oid,\n price: Number(context.price),\n buyer_email: context.buyer_email ?? '',\n buyer_phone: context.buyer_phone ?? '',\n payment_method: context.payment_method ?? '',\n reason: trimReason(reason) || 'kcp-window-closed',\n };\n\n try {\n await postPaymentContext(context.closeReportUrl, payload, true);\n } catch (error) {\n console.warn('[sirsoft-pay_nhnkcp] failed to report payment window close', error);\n }\n}\n","export const NHNKCP_APPLEPAY_METHOD = 'nhnkcp_applepay';\n\nexport function isNhnKcpApplePayMethod(paymentMethod: unknown): boolean {\n return paymentMethod === NHNKCP_APPLEPAY_METHOD;\n}\n\nexport function isIosMobileDevice(): boolean {\n if (typeof navigator === 'undefined') return false;\n\n const nav = navigator as Navigator & {\n userAgentData?: {\n mobile?: boolean;\n platform?: string;\n };\n maxTouchPoints?: number;\n };\n const ua = (nav.userAgent || '').toLowerCase();\n const platform = ((nav.userAgentData?.platform ?? nav.platform) || '').toLowerCase();\n const touchPoints = nav.maxTouchPoints ?? 0;\n\n if (/iphone|ipad|ipod/.test(ua) || /iphone|ipad|ipod|ios/.test(platform)) {\n return true;\n }\n\n return /macintosh|mac os x/.test(ua) && touchPoints > 1;\n}\n\nexport function applePayUnsupportedMessage(): string {\n const lang = typeof document !== 'undefined'\n ? document.documentElement.lang\n : '';\n\n if ((lang || '').toLowerCase().startsWith('ko')) {\n return '애플페이는 IOLine truncated
{"version":3,"file":"plugin.iife.js","sources":["../../resources/js/paymentCloseReport.ts","../../resources/js/support/applePayDevice.ts","../../resources/js/handlers/requestPayment.ts","../../resources/js/handlers/setPaymentMethod.ts","../../resources/js/handlers/copyToClipboard.ts","../../resources/js/handlers/index.ts","../../resources/js/orderResponseInterceptor.ts","../../resources/js/orderCompleteReceiptInjector.ts","../../resources/js/mypageOrderShowInjector.ts","../../resources/js/checkoutEasyPayInjector.ts","../../resources/js/adminApplePayNoticeInjector.ts","../../resources/js/adminPaymentMethodBrandInjector.ts","../../resources/js/index.ts"],"sourcesContent":["export interface PaymentCloseReportContext {\n closeReportUrl?: string;\n oid: string;\n price: number;\n buyer_email?: string;\n buyer_phone?: string;\n payment_method?: string;\n}\n\nfunction resolveApiUrl(url: string): string {\n if (/^https?:\\/\\//i.test(url) || url.startsWith('/api/')) {\n return url;\n }\n\n if (url.startsWith('/plugins/')) {\n return `/api${url}`;\n }\n\n if (url.startsWith('plugins/')) {\n return `/api/${url}`;\n }\n\n return url;\n}\n\nfunction trimReason(reason: string): string {\n return reason.trim().slice(0, 160);\n}\n\nfunction resolveRetryUrl(closeReportUrl?: string): string | undefined {\n if (!closeReportUrl) {\n return undefined;\n }\n\n return closeReportUrl.replace(/\\/payment\\/close-report$/, '/payment/retry');\n}\n\nasync function postPaymentContext(url: string, payload: Record<string, unknown>, keepalive = false): Promise<void> {\n const apiClient = ((window as any).G7Core)?.api;\n if (typeof apiClient?.post === 'function') {\n await apiClient.post(url, payload);\n return;\n }\n\n const response = await fetch(resolveApiUrl(url), {\n method: 'POST',\n headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify(payload),\n keepalive,\n });\n\n if (!response.ok) {\n let message = `NHN KCP payment request failed (${response.status})`;\n try {\n const data = await response.json();\n const responseMessage = Array.isArray(data?.errors?.message)\n ? data.errors.message[0]\n : data?.error ?? data?.message;\n if (typeof responseMessage === 'string' && responseMessage.trim() !== '') {\n message = responseMessage;\n }\n } catch {\n // JSON 응답이 아니면 HTTP 상태 메시지를 사용한다.\n }\n throw new Error(message);\n }\n}\n\nexport async function preparePaymentRetry(context: PaymentCloseReportContext): Promise<void> {\n const retryUrl = resolveRetryUrl(context.closeReportUrl);\n if (!retryUrl) {\n return;\n }\n\n await postPaymentContext(retryUrl, {\n oid: context.oid,\n price: Number(context.price),\n buyer_email: context.buyer_email ?? '',\n buyer_phone: context.buyer_phone ?? '',\n payment_method: context.payment_method ?? '',\n });\n}\n\nexport async function reportPaymentWindowClosed(\n context: PaymentCloseReportContext,\n reason = 'kcp-window-closed',\n): Promise<void> {\n if (!context.closeReportUrl) {\n return;\n }\n\n const payload = {\n oid: context.oid,\n price: Number(context.price),\n buyer_email: context.buyer_email ?? '',\n buyer_phone: context.buyer_phone ?? '',\n payment_method: context.payment_method ?? '',\n reason: trimReason(reason) || 'kcp-window-closed',\n };\n\n try {\n await postPaymentContext(context.closeReportUrl, payload, true);\n } catch (error) {\n console.warn('[sirsoft-pay_nhnkcp] failed to report payment window close', error);\n }\n}\n","export const NHNKCP_APPLEPAY_METHOD = 'nhnkcp_applepay';\n\nexport function isNhnKcpApplePayMethod(paymentMethod: unknown): boolean {\n return paymentMethod === NHNKCP_APPLEPAY_METHOD;\n}\n\nexport function isIosMobileDevice(): boolean {\n if (typeof navigator === 'undefined') return false;\n\n const nav = navigator as Navigator & {\n userAgentData?: {\n mobile?: boolean;\n platform?: string;\n };\n maxTouchPoints?: number;\n };\n const ua = (nav.userAgent || '').toLowerCase();\n const platform = ((nav.userAgentData?.platform ?? nav.platform) || '').toLowerCase();\n const touchPoints = nav.maxTouchPoints ?? 0;\n\n if (/iphone|ipad|ipod/.test(ua) || /iphone|ipad|ipod|ios/.test(platform)) {\n return true;\n }\n\n return /macintosh|mac os x/.test(ua) && touchPoints > 1;\n}\n\nexport function applePayUnsupportedMessage(): string {\n const lang = typeof document !== 'undefined'\n ? document.documentElement.lang\n : '';\n\n if ((lang || '').toLowerCase().startsWith('ko')) {\n return '애플페이는 IOLine truncated
@@ -8,6 +8,7 @@
*/
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
import {
buildKcpEasyPayReturnFields,
buildKcpTaxFields,
isSupportedKcpCurrency,
requestPaymentHandler,
@@ -212,4 +213,13 @@ describe('requestPaymentHandler', () => {
expect(isSupportedKcpCurrency('KRW')).toBe(true);
expect(isSupportedKcpCurrency('usd')).toBe(false);
});
it('간편결제 원 결제수단을 KCP callback 반환 필드에 싣는다', () => {
expect(buildKcpEasyPayReturnFields('nhnkcp_naverpay', true)).toEqual({
param_opt_1: 'nhnkcp_naverpay',
nhnkcp_easy_pay_method: 'nhnkcp_naverpay',
});
expect(buildKcpEasyPayReturnFields('card', false)).toEqual({});
expect(buildKcpEasyPayReturnFields('nhnkcp_unknown', true)).toEqual({});
});
});
@@ -120,6 +120,18 @@ const KCP_EASY_PAY_DIRECT: Record<string, Record<string, string>> = {
nhnkcp_applepay: { applepay_direct: 'Y' },
};
export function buildKcpEasyPayReturnFields(paymentMethod: string, isEasyPay: boolean): Record<string, string> {
const methodKey = paymentMethod.toLowerCase();
if (!isEasyPay || !Object.prototype.hasOwnProperty.call(KCP_EASY_PAY_DIRECT, methodKey)) {
return {};
}
return {
param_opt_1: methodKey,
nhnkcp_easy_pay_method: methodKey,
};
}
function isKcpPaymentFrameClosed(iframe: HTMLIFrameElement): boolean {
if (!iframe.isConnected) {
return true;
@@ -408,6 +420,7 @@ async function handlePcPayment(
};
Object.assign(fields, buildKcpTaxFields(pgPaymentData));
Object.assign(fields, buildKcpEasyPayReturnFields(paymentMethod, isEasyPay));
// 가상계좌 전용 파라미터
if (payMethod === '001000000000') {
@@ -190,6 +190,7 @@ class MobileApprovalController
if (isset(self::EASY_PAY_DIRECT_FIELDS[$payMethodKey])) {
$fields = [...$fields, ...self::EASY_PAY_DIRECT_FIELDS[$payMethodKey]];
}
$fields = [...$fields, ...$this->buildEasyPayReturnFields($payMethodKey)];
}
return response()->json([
@@ -243,6 +244,21 @@ class MobileApprovalController
];
}
/**
* @return array<string, string>
*/
private function buildEasyPayReturnFields(string $payMethodKey): array
{
if (! isset(self::EASY_PAY_DIRECT_FIELDS[$payMethodKey])) {
return [];
}
return [
'param_opt_1' => $payMethodKey,
'nhnkcp_easy_pay_method' => $payMethodKey,
];
}
private function isKrwPayment(Order $order, ?string $requestedCurrency): bool
{
return $this->normalizeCurrency($requestedCurrency) === 'KRW'
@@ -102,6 +102,29 @@ class PaymentCallbackController
'use_pay_method',
];
private const EASY_PAY_METHODS = [
'nhnkcp_payco' => [
'provider' => 'payco',
'label' => ['ko' => 'PAYCO (페이코)', 'en' => 'PAYCO'],
],
'nhnkcp_naverpay' => [
'provider' => 'naverpay',
'label' => ['ko' => '네이버페이', 'en' => 'NaverPay'],
],
'nhnkcp_naverpay_point' => [
'provider' => 'naverpay_point',
'label' => ['ko' => '네이버페이 포인트결제', 'en' => 'NaverPay Point'],
],
'nhnkcp_kakaopay' => [
'provider' => 'kakaopay',
'label' => ['ko' => '카카오페이', 'en' => 'KakaoPay'],
],
'nhnkcp_applepay' => [
'provider' => 'applepay',
'label' => ['ko' => '애플페이', 'en' => 'Apple Pay'],
],
];
public function __construct(
private readonly OrderProcessingService $orderService,
private readonly PluginSettingsService $pluginSettingsService,
@@ -203,6 +226,15 @@ class PaymentCallbackController
$order = $order->fresh('payment') ?? $order;
}
if (($order->payment?->isPaid() ?? false) || $order->order_status === OrderStatusEnum::PAYMENT_COMPLETE) {
Log::info('KCP: authCallback already paid order, skipping CLI approval', [
'ordr_idxx' => $ordrIdxx,
'transaction_id' => $order->payment?->transaction_id,
]);
return redirect($this->resolveSuccessUrl($ordrIdxx));
}
$expectedAmount = $this->expectedPaymentPrice($order);
if (! $this->isKrwOrder($order)) {
Log::warning('KCP: unsupported order currency', [
@@ -292,6 +324,7 @@ class PaymentCallbackController
$approvedAmtForCancel = $approvedAmt;
$isEscrow = ($pgResponse['escw_yn'] ?? '') === 'Y';
$easyPayMeta = $this->resolveEasyPayMeta($validated);
// 4단계: 주문 완료 처리
$this->orderService->completePayment($order, [
@@ -301,11 +334,16 @@ class PaymentCallbackController
'card_name' => $pgResponse['card_name'] ?? $pgResponse['bank_name'] ?? null,
'card_installment_months' => (int) ($pgResponse['quota'] ?? 0),
'is_interest_free' => false,
'embedded_pg_provider' => null,
'embedded_pg_provider' => $easyPayMeta['provider'] ?? null,
'receipt_url' => null,
'payment_meta' => [
'res_cd' => $pgResCd,
...$this->currentCredentialMeta(),
...($easyPayMeta === [] ? [] : [
'nhnkcp_easy_pay_method' => $easyPayMeta['method'],
'nhnkcp_easy_pay_provider' => $easyPayMeta['provider'],
'nhnkcp_easy_pay_label' => $easyPayMeta['label'],
]),
'use_pay_method' => $validated['use_pay_method'] ?? $pgResponse['use_pay_method'] ?? null,
'app_time' => $pgResponse['app_time'] ?? null,
'bank_name' => $pgResponse['bank_name'] ?? null,
@@ -748,6 +786,25 @@ class PaymentCallbackController
];
}
/**
* @return array{method: string, provider: string, label: array{ko: string, en: string}}|array{}
*/
private function resolveEasyPayMeta(array $payload): array
{
$method = strtolower(trim((string) ($payload['nhnkcp_easy_pay_method'] ?? $payload['param_opt_1'] ?? '')));
if (! isset(self::EASY_PAY_METHODS[$method])) {
return [];
}
$definition = self::EASY_PAY_METHODS[$method];
return [
'method' => $method,
'provider' => $definition['provider'],
'label' => $definition['label'],
];
}
private function resolveSuccessUrl(string $orderId): string
{
$settings = $this->pluginSettingsService->get(self::PLUGIN_IDENTIFIER) ?? [];
@@ -46,6 +46,8 @@ class AuthCallbackRequest extends FormRequest
'ordr_idxx' => ['required', 'string'],
'good_mny' => ['nullable', 'numeric', 'min:1'],
'use_pay_method' => ['nullable', 'string'],
'param_opt_1' => ['nullable', 'string', 'max:50'],
'nhnkcp_easy_pay_method' => ['nullable', 'string', 'max:50'],
// 모바일 SmartPhone Pay 가상계좌 콜백 (enc_data 없이 평문 전달)
// KCP가 보내는 변종 키 모두 허용 — handleVbankIssued 에서 우선순위로 처리
'bankname' => ['nullable', 'string'],
@@ -276,7 +276,9 @@ class MobileApprovalControllerTest extends PluginTestCase
->postJson(self::APPROVAL_KEY_ENDPOINT, $this->approvalKeyPayload($order, ['pay_method' => 'nhnkcp_naverpay']));
$response->assertOk()
->assertJsonPath('data.fields.naverpay_direct', 'Y');
->assertJsonPath('data.fields.naverpay_direct', 'Y')
->assertJsonPath('data.fields.param_opt_1', 'nhnkcp_naverpay')
->assertJsonPath('data.fields.nhnkcp_easy_pay_method', 'nhnkcp_naverpay');
}
public function test_kakaopay_easy_pay_includes_direct_field(): void
@@ -130,10 +130,13 @@ class PaymentCallbackControllerTest extends PluginTestCase
* NhnKcpApiService::approvePayment() 를 exec() 없이 mock.
* 기존 테스트는 Http::fake()로 CLI exec를 막으려 했으나 동작하지 않음.
*/
private function mockApiService(array $cliResponse): void
private function mockApiService(array $cliResponse, ?int $approveCalls = null): void
{
$mock = $this->createMock(NhnKcpApiService::class);
$mock->method('approvePayment')->willReturn($cliResponse);
$expectation = $approveCalls === null
? $mock->method('approvePayment')
: $mock->expects($this->exactly($approveCalls))->method('approvePayment');
$expectation->willReturn($cliResponse);
$this->app->instance(NhnKcpApiService::class, $mock);
}
@@ -201,6 +204,72 @@ class PaymentCallbackControllerTest extends PluginTestCase
$this->assertEquals('APP12345', $payment->card_approval_number);
}
public function test_auth_callback_stores_easy_pay_method_meta(): void
{
$order = $this->createTestOrder(50000);
$this->mockPluginSettings();
$tno = 'KCP_TNO_NAVERPAY';
$this->mockApiService($this->makeCliResponse($tno, $order->order_number, 50000));
$response = $this->post(
'/plugins/sirsoft-pay_nhnkcp/payment/callback',
$this->makeCallbackParams($order->order_number, 50000, [
'tno' => $tno,
'param_opt_1' => 'nhnkcp_naverpay',
'nhnkcp_easy_pay_method' => 'nhnkcp_naverpay',
])
);
$response->assertRedirect("/shop/orders/{$order->order_number}/complete");
$payment = $order->payment;
$payment->refresh();
$meta = $payment->payment_meta;
$this->assertSame('naverpay', $payment->embedded_pg_provider);
$this->assertSame('nhnkcp_naverpay', $meta['nhnkcp_easy_pay_method'] ?? null);
$this->assertSame('naverpay', $meta['nhnkcp_easy_pay_provider'] ?? null);
$this->assertSame('네이버페이', $meta['nhnkcp_easy_pay_label']['ko'] ?? null);
$this->assertSame('NaverPay', $meta['nhnkcp_easy_pay_label']['en'] ?? null);
}
public function test_auth_callback_skips_cli_approval_when_order_already_paid(): void
{
$order = $this->createTestOrder(50000);
$this->mockPluginSettings();
$existingTno = 'KCP_TNO_ALREADY_PAID';
$order->update([
'order_status' => OrderStatusEnum::PAYMENT_COMPLETE,
'paid_at' => now(),
'total_paid_amount' => 50000,
'total_due_amount' => 0,
]);
$order->payment->update([
'payment_status' => PaymentStatusEnum::PAID,
'paid_at' => now(),
'paid_amount_local' => 50000,
'paid_amount_base' => 50000,
'transaction_id' => $existingTno,
'card_approval_number' => 'APP_ALREADY',
]);
$this->mockApiService($this->makeCliResponse('KCP_TNO_SHOULD_NOT_APPROVE', $order->order_number, 50000), 0);
$response = $this->post(
'/plugins/sirsoft-pay_nhnkcp/payment/callback',
$this->makeCallbackParams($order->order_number, 50000, ['tno' => $existingTno])
);
$response->assertRedirect("/shop/orders/{$order->order_number}/complete");
$payment = $order->payment;
$payment->refresh();
$this->assertSame($existingTno, $payment->transaction_id);
$this->assertSame('APP_ALREADY', $payment->card_approval_number);
}
public function test_auth_callback_rejects_browser_amount_mismatch_before_cli_approval(): void
{
$order = $this->createTestOrder(50000);