refactor(ecommerce,pay): 간편결제 브랜드 마크 카탈로그 편입 + 애플페이 iOS 게이팅 이관

3사 PG 플러그인의 체크아웃 DOM 인젝터가 렌더 후 브랜드 마크를 주입하고
injector끼리 같은 버튼을 두고 경합하던 구조를 제거한다. 시각정보(색 배지/
SVG 로고)를 결제수단 카탈로그(_cached_brand_mark)로 편입해 코어 체크아웃
레이아웃의 신규 BrandMark 컴포넌트가 데이터 기반으로 직접 렌더한다.
reconcileKginicisPatchedDuplicates(중복 방어)도 함께 제거했다.

애플페이 iOS 게이팅도 injector 밖으로 이관: 이커머스 모듈 DetectDevice
미들웨어가 UA로 기기를 판정해 코어 core.frontend.filter_app_config 훅으로
appConfig.isIos를 주입하고(1차), 템플릿 부트스트랩이 iPadOS 데스크탑 UA를
클라 신호로 보정한다(2차). 코어는 훅만 제공하고 감지 로직은 모듈이 소유한다.

미들웨어는 Router::pushMiddlewareToGroup 이 아닌 HTTP Kernel::appendMiddlewareToGroup
으로 web 그룹에 등록한다(전자는 Router 레지스트리만 갱신해 SSR 셸 요청 파이프라인에
미반영 → isIos 항상 false). sirsoft-gdpr 선례와 동일.

코어 최소 요구 버전 7.0.5 상향(appConfig 필터 훅 도입).
This commit is contained in:
HeuJung committed 2026-07-15 17:50:39 +09:00
1 parent e896a47d4f
commit 8b9bfd0c91
58 files changed
+1582 -2013

No files matched your search

@@ -17,6 +17,7 @@
- 간편결제가 정식 결제수단으로 취급되어 주문 내역에 실제로 선택한 결제수단(예: 네이버페이)이 그대로 기록됩니다.
- 쇼핑몰 환경설정 > 주문설정의 결제수단 목록에서 간편결제가 "PG 고정 · KG이니시스"로 표시됩니다. 간편결제는 KG 이니시스 전용이므로 다른 결제대행사로 바꿀 수 없습니다.
- 결제창을 띄우기 위해 브라우저 요청을 가로채 결제수단을 바꿔치기하던 내부 처리를 제거했습니다. 결제 진행 방식이 표준화되어 주문서 입력값이 초기화되는 등의 부작용이 사라집니다.
- 주문서의 간편결제 버튼에 표시되는 브랜드 로고(네이버페이·삼성페이·카카오페이·L.pay 등)를 화면이 그려진 뒤 덧입히던 방식에서 결제수단 정보로 처음부터 표시하는 방식으로 바꿨습니다. 여러 결제사가 함께 켜져 있을 때 표시가 안정적입니다.
## [1.0.0] - 2026-07-01
@@ -1,7 +1,7 @@
{
"$schema": "https://json-schema.org/draft/2020-12/schema",
"identifier": "sirsoft-pay_kginicis",
"version": "1.0.0",
"version": "1.0.1",
"components": {
"basic": [],
"composite": [],
@@ -1,14 +1,14 @@
(function(){"use strict";const L="kginicis_pay_form_",M="__sirsoftKginicisReloadStandardPaySdk",w="__sirsoftKginicisMobilePaymentReturnPending";function de(){if(typeof document>"u")return 0;const e=document.querySelectorAll(`form[id^="${L}"]`);return e.forEach(t=>t.remove()),e.length}function at(){typeof window>"u"||(window[M]=!0)}function st(){if(typeof window>"u")return!1;const e=window,t=e[M]===!0;return delete e[M],t}function ct(e){typeof window>"u"||typeof document>"u"||(window.INIStdPay=void 0,document.querySelectorAll(`script[src="${e}"], script[src*="/INIStdPay_third-party.js"]`).forEach(t=>t.remove()))}function lt(e=Date.now()){if(!(typeof window>"u"))try{window.sessionStorage.setItem(w,String(e))}catch{window[w]=e}}function K(){if(!(typeof window>"u")){try{window.sessionStorage.removeItem(w)}catch{}delete window[w]}}function ue(e=Date.now()){if(typeof window>"u")return!1;let t=null;try{const n=window.sessionStorage.getItem(w);t=n?Number(n):null}catch{t=null}if(!Number.isFinite(t)){const n=window[w];t=typeof n=="number"?n:Number(n)}return!Number.isFinite(t)||e-t>18e5?(K(),!1):!0}const O="sirsoft-pay_kginicis",dt=O,ut="payment-window-closed",fe="__sirsoftKginicisPaymentCloseListenerInstalled",G="__sirsoftKginicisActiveStandardPaymentCloseContext",me=20,ft=100,$={info:(...e)=>console.info(`[${O}]`,...e),warn:(...e)=>console.warn(`[${O}]`,...e)};function mt(e){if(!e||typeof e!="object")return!1;const t=e;return t.source===dt&&t.type===ut}function D(){return/\/shop\/checkout\/?$/.test(window.location.pathname)}function E(){return window}function pt(){const e=E()[G];return!e||typeof e!="object"?null:e}function yt(e){return/^https?:\/\//i.test(e)||e.startsWith("/api/")?e:e.startsWith("/plugins/")?`/api${e}`:e.startsWith("plugins/")?`/api/${e}`:e}function ht(e){e.closeReportUrl&&(E()[G]={...e,reported:!1})}function pe(){delete E()[G]}function ye(){pe()}async function gt(e="payment-window-closed"){const t=pt();if(!t||t.reported||!D())return;t.reported=!0;const n={oid:t.oid,price:t.price,buyer_email:t.buyer_email??"",buyer_phone:t.buyer_phone??"",payment_method:t.payment_method??"",reason:e};try{const i=window.G7Core?.api;typeof i?.post=="function"?await i.post(t.closeReportUrl,n):await fetch(yt(t.closeReportUrl),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(n),keepalive:!0})}catch(i){$.warn("failed to report KG payment window close",{reason:e,error:i})}finally{pe()}}function he(e="payment-window-closed",t=!0){if(!D())return!1;const i=window.G7Core?.state?.setLocal;return typeof i!="function"?(t&&$.warn("G7Core.state.setLocal not available while resetting payment submit state"),!1):(de(),at(),i({isSubmittingOrder:!1}),$.info("checkout submit state reset after KG payment close",{reason:e}),!0)}function _t(e,t=!1){let n=0;const i=()=>{if(n++,!(t&&!ue())){if(he(e,n>=me)){t&&K();return}!D()||n>=me||window.setTimeout(i,ft)}};i()}function v(e){ue()&&_t(e,!0)}function wt(){if(typeof window>"u")return;const e=E();e[fe]||(window.addEventListener("message",t=>{t.origin===window.location.origin&&mt(t.data)&&(gt(t.data.reason),he(t.data.reason))}),window.addEventListener("pagehide",()=>{ye()}),window.addEventListener("beforeunload",()=>{ye()}),window.addEventListener("pageshow",t=>{v(t.persisted?"mobile-payment-bfcache-return":"mobile-payment-page-show")}),window.addEventListener("focus",()=>{v("mobile-payment-window-focus")}),document.addEventListener("visibilitychange",()=>{document.visibilityState==="visible"&&v("mobile-payment-visibility-return")}),e[fe]=!0,v("mobile-payment-listener-installed"))}function ge(){if(typeof navigator>"u")return!1;const e=navigator;if(e.userAgentData?.mobile!==void 0)return e.userAgentData.mobile;const t=(e.userAgent||"").toLowerCase(),n=((e.userAgentData?.platform??e.platform)||"").toLowerCase();if(/android|iphone|ipad|ipod|windows phone|iemobile|blackberry|opera mini|mobile safari/.test(t)||/iphone|ipad|ipod|ios/.test(n))return!0;const i=e.maxTouchPoints??0;return/macintosh|mac os x/.test(t)&&i>1}function bt(e){return new Promise((t,n)=>{if(document.querySelector(`script[src="${e}"]`)){t();return}const i=document.createElement("script");i.src=e,i.async=!0,i.onload=()=>t(),i.onerror=()=>n(new Error(`Failed to load script: ${e}`)),document.head.appendChild(i)})}function _e(e,t){if(!t.startsWith("kginicis_"))return e;const n=new URL(e,window.location.origin);return n.searchParams.set("selectedPaymentMethod",t),n.toString()}function kt(e){const t=(e??"").trim().toUpperCase();return t===""||t==="WON"?"KRW":t}function we(e,t,n="utf-8",i){const r=document.createElement("form");i&&(r.id=i),r.method="POST",r.action=e,r.acceptCharset=n,r.style.display="none";for(const[o,a]of Object.entries(t)){const s=document.createElement("input");s.type="hidden",s.name=o,s.value=a,r.appendChild(s)}document.body.appendChild(r),r.submit()}const Pt={card:"Card",vbank:"VBank",bank:"DirectBank",phone:"HPP",kginicis_samsung_pay:"onlyssp",kginicis_naverpay:"onlynaverpay",kginicis_lLine truncated
(function(){"use strict";const x="kginicis_pay_form_",R="__sirsoftKginicisReloadStandardPaySdk",w="__sirsoftKginicisMobilePaymentReturnPending";function oe(){if(typeof document>"u")return 0;const e=document.querySelectorAll(`form[id^="${x}"]`);return e.forEach(t=>t.remove()),e.length}function qe(){typeof window>"u"||(window[R]=!0)}function We(){if(typeof window>"u")return!1;const e=window,t=e[R]===!0;return delete e[R],t}function Ve(e){typeof window>"u"||typeof document>"u"||(window.INIStdPay=void 0,document.querySelectorAll(`script[src="${e}"], script[src*="/INIStdPay_third-party.js"]`).forEach(t=>t.remove()))}function ze(e=Date.now()){if(!(typeof window>"u"))try{window.sessionStorage.setItem(w,String(e))}catch{window[w]=e}}function M(){if(!(typeof window>"u")){try{window.sessionStorage.removeItem(w)}catch{}delete window[w]}}function ie(e=Date.now()){if(typeof window>"u")return!1;let t=null;try{const n=window.sessionStorage.getItem(w);t=n?Number(n):null}catch{t=null}if(!Number.isFinite(t)){const n=window[w];t=typeof n=="number"?n:Number(n)}return!Number.isFinite(t)||e-t>18e5?(M(),!1):!0}const N="sirsoft-pay_kginicis",Xe=N,Ze="payment-window-closed",ae="__sirsoftKginicisPaymentCloseListenerInstalled",L="__sirsoftKginicisActiveStandardPaymentCloseContext",se=20,Qe=100,O={info:(...e)=>console.info(`[${N}]`,...e),warn:(...e)=>console.warn(`[${N}]`,...e)};function et(e){if(!e||typeof e!="object")return!1;const t=e;return t.source===Xe&&t.type===Ze}function $(){return/\/shop\/checkout\/?$/.test(window.location.pathname)}function P(){return window}function tt(){const e=P()[L];return!e||typeof e!="object"?null:e}function nt(e){return/^https?:\/\//i.test(e)||e.startsWith("/api/")?e:e.startsWith("/plugins/")?`/api${e}`:e.startsWith("plugins/")?`/api/${e}`:e}function rt(e){e.closeReportUrl&&(P()[L]={...e,reported:!1})}function ce(){delete P()[L]}function de(){ce()}async function ot(e="payment-window-closed"){const t=tt();if(!t||t.reported||!$())return;t.reported=!0;const n={oid:t.oid,price:t.price,buyer_email:t.buyer_email??"",buyer_phone:t.buyer_phone??"",payment_method:t.payment_method??"",reason:e};try{const r=window.G7Core?.api;typeof r?.post=="function"?await r.post(t.closeReportUrl,n):await fetch(nt(t.closeReportUrl),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(n),keepalive:!0})}catch(r){O.warn("failed to report KG payment window close",{reason:e,error:r})}finally{ce()}}function le(e="payment-window-closed",t=!0){if(!$())return!1;const r=window.G7Core?.state?.setLocal;return typeof r!="function"?(t&&O.warn("G7Core.state.setLocal not available while resetting payment submit state"),!1):(oe(),qe(),r({isSubmittingOrder:!1}),O.info("checkout submit state reset after KG payment close",{reason:e}),!0)}function it(e,t=!1){let n=0;const r=()=>{if(n++,!(t&&!ie())){if(le(e,n>=se)){t&&M();return}!$()||n>=se||window.setTimeout(r,Qe)}};r()}function I(e){ie()&&it(e,!0)}function at(){if(typeof window>"u")return;const e=P();e[ae]||(window.addEventListener("message",t=>{t.origin===window.location.origin&&et(t.data)&&(ot(t.data.reason),le(t.data.reason))}),window.addEventListener("pagehide",()=>{de()}),window.addEventListener("beforeunload",()=>{de()}),window.addEventListener("pageshow",t=>{I(t.persisted?"mobile-payment-bfcache-return":"mobile-payment-page-show")}),window.addEventListener("focus",()=>{I("mobile-payment-window-focus")}),document.addEventListener("visibilitychange",()=>{document.visibilityState==="visible"&&I("mobile-payment-visibility-return")}),e[ae]=!0,I("mobile-payment-listener-installed"))}function ue(){if(typeof navigator>"u")return!1;const e=navigator;if(e.userAgentData?.mobile!==void 0)return e.userAgentData.mobile;const t=(e.userAgent||"").toLowerCase(),n=((e.userAgentData?.platform??e.platform)||"").toLowerCase();if(/android|iphone|ipad|ipod|windows phone|iemobile|blackberry|opera mini|mobile safari/.test(t)||/iphone|ipad|ipod|ios/.test(n))return!0;const r=e.maxTouchPoints??0;return/macintosh|mac os x/.test(t)&&r>1}function st(e){return new Promise((t,n)=>{if(document.querySelector(`script[src="${e}"]`)){t();return}const r=document.createElement("script");r.src=e,r.async=!0,r.onload=()=>t(),r.onerror=()=>n(new Error(`Failed to load script: ${e}`)),document.head.appendChild(r)})}function me(e,t){if(!t.startsWith("kginicis_"))return e;const n=new URL(e,window.location.origin);return n.searchParams.set("selectedPaymentMethod",t),n.toString()}function ct(e){const t=(e??"").trim().toUpperCase();return t===""||t==="WON"?"KRW":t}function fe(e,t,n="utf-8",r){const o=document.createElement("form");r&&(o.id=r),o.method="POST",o.action=e,o.acceptCharset=n,o.style.display="none";for(const[i,s]of Object.entries(t)){const a=document.createElement("input");a.type="hidden",a.name=i,a.value=s,o.appendChild(a)}document.body.appendChild(o),o.submit()}const dt={card:"Card",vbank:"VBank",bank:"DirectBank",phone:"HPP",kginicis_samsung_pay:"onlyssp",kginicis_naverpay:"onlynaverpay",kginicis_lLine truncated
<div class="row">
<dt>${x(o.label)}</dt>
<dd>${x(o.value)}</dd>
<dt>${E(i.label)}</dt>
<dd>${E(i.value)}</dd>
</div>
`).join("");t.document.open(),t.document.write(`<!doctype html>
<html lang="ko">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>${x(n)}</title>
<title>${E(n)}</title>
<style>
body {
margin: 0;
@@ -81,11 +81,11 @@
</head>
<body>
<main>
<h1>${x(n)}</h1>
${i?`<p class="notice">${x(i)}</p>`:""}
<dl>${r}</dl>
<h1>${E(n)}</h1>
${r?`<p class="notice">${E(r)}</p>`:""}
<dl>${o}</dl>
<div class="actions"><button type="button" onclick="window.print()">인쇄</button></div>
</main>
</body>
</html>`),t.document.close()}function x(e){return e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#039;")}const B="sirsoft-pay_kginicis",Ee="__kginicisOrderShowInjectorInstalled",j="kginicis-mp-receipt-row",ve=/^(?:\/mypage\/orders\/([^/]+)|\/shop\/guest\/orders\/([^/]+))$/,Y=new Map;function Yt(e){try{const n=window.G7Core?.getState,o=n?.()?.currentDataContext?.order?.data;return o&&(o.order_number===e||o.id!==void 0&&String(o.id)===e)?o:null}catch{return null}}function Ut(){const e=document.getElementById("order_payment_info_panel");if(e)return Array.from(e.children).find(i=>i.className?.includes("space-y"))??e;const t=Array.from(document.querySelectorAll("h3")).find(i=>{const r=i.textContent?.trim()??"";return r.includes("결제 정보")||/^Payment Information$/i.test(r)});if(!t)return null;const n=t.parentElement?.parentElement;return n?Array.from(n.children).find(i=>i.className?.includes("space-y"))??n:null}function Ht(e,t){if(!t)return!1;const n=Array.from(e.querySelectorAll("div"));for(const i of n){const r=Array.from(i.children).filter(s=>s instanceof HTMLElement&&s.tagName==="SPAN");if(r.length<2)continue;const o=r[0].textContent?.trim();if(o!=="결제 방법"&&o!=="결제수단"&&o!=="Payment Method")continue;const a=r[r.length-1];return a.textContent?.trim()===t?(i.dataset.kginicisPaymentMethodRow="true",!0):(a.textContent=t,a.dataset.kginicisPaymentMethodPatched="true",i.dataset.kginicisPaymentMethodRow="true",!0)}return!1}function Jt(e,t){const n=document.createElement("div");n.id=j,n.className="flex items-center justify-between",n.dataset.kginicisReceiptRow="mypage-order";const i=document.createElement("span");i.className="text-gray-500 dark:text-gray-400 text-sm",i.textContent=Bt(t);const r=document.createElement("button");return r.type="button",r.dataset.kginicisReceiptButton="mypage-order",r.className="inline-flex items-center gap-1 text-sm text-blue-600 dark:text-blue-400 hover:underline disabled:opacity-50",r.textContent=I(t),r.addEventListener("click",async()=>{r.disabled=!0,r.textContent="로딩 중...";const o=await S(e);r.disabled=!1,r.textContent=I(o??t),P(o)&&Ce(o)}),n.appendChild(i),n.appendChild(r),n}async function Ft(e,t){const n=Yt(e),i=n?.payment;if(i&&(i.pg_provider!=="kginicis"||!i.transaction_id))return!0;const r=n?.order_number??(t?e:null);if(!r)return!1;if(!t&&n&&!i)return!0;const o=Ut();if(!o)return!1;const{status:a,info:s}=await xe(r);if(!t&&a===404)return!0;const c=i?.payment_status==="paid",u=s?.receipt_type==="cbt_confirmation";if(i&&!c&&!u)return!0;if(!i&&!P(s))return!1;const l=Ht(o,s?.payment_method_display_label);return!document.getElementById(j)&&P(s)&&(o.appendChild(Jt(r,s)),console.info(`[${B}] receipt button injected on mypage order show`)),l&&console.info(`[${B}] payment method display patched on mypage order show`),!!(document.getElementById(j)||l)}function Wt(e,t){if(Y.has(e))return;let n=0;const i=window.setInterval(()=>{n++,Ft(e,t).then(r=>{(r||n>=30)&&(window.clearInterval(i),Y.delete(e))})},400);Y.set(e,i)}function qt(){const e=location.pathname.match(ve);if(e){const t=e[1],n=e[2],i=t??n;i&&Wt(i,n!==void 0)}}function zt(){if(typeof window>"u")return;const e=window;if(e[Ee])return;e[Ee]=!0,console.info(`[${B}] mypage order show injector installed`);let t=null;const n=(s=1500)=>{t!==null&&window.clearTimeout(t),t=window.setTimeout(()=>{t=null,qt()},s)};document.readyState==="loading"?document.addEventListener("DOMContentLoaded",()=>n()):n();const i=history.pushState.bind(history);history.pushState=(...s)=>{i(...s),n(600)};const r=history.replaceState.bind(history);history.replaceState=(...s)=>{r(...s),n(600)},window.addEventListener("popstate",()=>n(500));const o=document.getElementById("app")??document.body;new MutationObserver(()=>{ve.test(location.pathname)&&n(250)}).observe(o,{childList:!0,subtree:!0})}const U="sirsoft-pay_kginicis",Se="__kginicisAdminPaymentDisplayInjectorInstalled",Vt=/^\/admin\/ecommerce\/orders\/([^/]+)$/;function Xt(){return localStorage.getItem("auth_token")}async function Zt(e){const t=Xt();if(!t)return null;try{const n=await fetch(`/api/plugins/${U}/admin/orders/${e}/transaction-status`,{headers:{Authorization:`Bearer ${t}`,Accept:"application/json"}});if(!n.ok)return null;const i=await n.json();return("data"in i?i.data:i)??null}catch{return null}}function Qt(e){return Array.from(e.children).filter(t=>t instanceof HTMLElement)}function en(e,t){let n=!1;const i=Array.from(e.querySelectorAll("div"));for(const r of i){const o=Qt(r),a=o.findIndex(d=>d.textContent?.trim()==="결제수단");if(a<0)continue;const s=o.slice(a+1).find(d=>d.textContent?.trim()&&d.textContent.trim()!=="결제수단");if(!s)continue;const c=o.slice(a+2).find(d=>/^\(.+\)$/.test(d.textContent?.trim()??"")),u=c?.textContent?.trim().replace(/^\(|\)$/g,"")??"",l=u&&t.endsWith(")")?t.replace(/\)$/,`, ${u})`):t;s.textContent?.trim()!==l&&(s.textContent=l,s.dataset.kginicisPaymentMethodPatched="true"),r.dataLine truncated
</html>`),t.document.close()}function E(e){return e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#039;")}const D="sirsoft-pay_kginicis",we="__kginicisOrderShowInjectorInstalled",K="kginicis-mp-receipt-row",be=/^(?:\/mypage\/orders\/([^/]+)|\/shop\/guest\/orders\/([^/]+))$/,G=new Map;function Tt(e){try{const n=window.G7Core?.getState,i=n?.()?.currentDataContext?.order?.data;return i&&(i.order_number===e||i.id!==void 0&&String(i.id)===e)?i:null}catch{return null}}function xt(){const e=document.getElementById("order_payment_info_panel");if(e)return Array.from(e.children).find(r=>r.className?.includes("space-y"))??e;const t=Array.from(document.querySelectorAll("h3")).find(r=>{const o=r.textContent?.trim()??"";return o.includes("결제 정보")||/^Payment Information$/i.test(o)});if(!t)return null;const n=t.parentElement?.parentElement;return n?Array.from(n.children).find(r=>r.className?.includes("space-y"))??n:null}function Rt(e,t){if(!t)return!1;const n=Array.from(e.querySelectorAll("div"));for(const r of n){const o=Array.from(r.children).filter(a=>a instanceof HTMLElement&&a.tagName==="SPAN");if(o.length<2)continue;const i=o[0].textContent?.trim();if(i!=="결제 방법"&&i!=="결제수단"&&i!=="Payment Method")continue;const s=o[o.length-1];return s.textContent?.trim()===t?(r.dataset.kginicisPaymentMethodRow="true",!0):(s.textContent=t,s.dataset.kginicisPaymentMethodPatched="true",r.dataset.kginicisPaymentMethodRow="true",!0)}return!1}function Mt(e,t){const n=document.createElement("div");n.id=K,n.className="flex items-center justify-between",n.dataset.kginicisReceiptRow="mypage-order";const r=document.createElement("span");r.className="text-gray-500 dark:text-gray-400 text-sm",r.textContent=vt(t);const o=document.createElement("button");return o.type="button",o.dataset.kginicisReceiptButton="mypage-order",o.className="inline-flex items-center gap-1 text-sm text-blue-600 dark:text-blue-400 hover:underline disabled:opacity-50",o.textContent=A(t),o.addEventListener("click",async()=>{o.disabled=!0,o.textContent="로딩 중...";const i=await v(e);o.disabled=!1,o.textContent=A(i??t),C(i)&&ge(i)}),n.appendChild(r),n.appendChild(o),n}async function Nt(e,t){const n=Tt(e),r=n?.payment;if(r&&(r.pg_provider!=="kginicis"||!r.transaction_id))return!0;const o=n?.order_number??(t?e:null);if(!o)return!1;if(!t&&n&&!r)return!0;const i=xt();if(!i)return!1;const{status:s,info:a}=await he(o);if(!t&&s===404)return!0;const c=r?.payment_status==="paid",u=a?.receipt_type==="cbt_confirmation";if(r&&!c&&!u)return!0;if(!r&&!C(a))return!1;const d=Rt(i,a?.payment_method_display_label);return!document.getElementById(K)&&C(a)&&(i.appendChild(Mt(o,a)),console.info(`[${D}] receipt button injected on mypage order show`)),d&&console.info(`[${D}] payment method display patched on mypage order show`),!!(document.getElementById(K)||d)}function Lt(e,t){if(G.has(e))return;let n=0;const r=window.setInterval(()=>{n++,Nt(e,t).then(o=>{(o||n>=30)&&(window.clearInterval(r),G.delete(e))})},400);G.set(e,r)}function Ot(){const e=location.pathname.match(be);if(e){const t=e[1],n=e[2],r=t??n;r&&Lt(r,n!==void 0)}}function $t(){if(typeof window>"u")return;const e=window;if(e[we])return;e[we]=!0,console.info(`[${D}] mypage order show injector installed`);let t=null;const n=(a=1500)=>{t!==null&&window.clearTimeout(t),t=window.setTimeout(()=>{t=null,Ot()},a)};document.readyState==="loading"?document.addEventListener("DOMContentLoaded",()=>n()):n();const r=history.pushState.bind(history);history.pushState=(...a)=>{r(...a),n(600)};const o=history.replaceState.bind(history);history.replaceState=(...a)=>{o(...a),n(600)},window.addEventListener("popstate",()=>n(500));const i=document.getElementById("app")??document.body;new MutationObserver(()=>{be.test(location.pathname)&&n(250)}).observe(i,{childList:!0,subtree:!0})}const j="sirsoft-pay_kginicis",ke="__kginicisAdminPaymentDisplayInjectorInstalled",Dt=/^\/admin\/ecommerce\/orders\/([^/]+)$/;function Kt(){return localStorage.getItem("auth_token")}async function Gt(e){const t=Kt();if(!t)return null;try{const n=await fetch(`/api/plugins/${j}/admin/orders/${e}/transaction-status`,{headers:{Authorization:`Bearer ${t}`,Accept:"application/json"}});if(!n.ok)return null;const r=await n.json();return("data"in r?r.data:r)??null}catch{return null}}function jt(e){return Array.from(e.children).filter(t=>t instanceof HTMLElement)}function Yt(e,t){let n=!1;const r=Array.from(e.querySelectorAll("div"));for(const o of r){const i=jt(o),s=i.findIndex(l=>l.textContent?.trim()==="결제수단");if(s<0)continue;const a=i.slice(s+1).find(l=>l.textContent?.trim()&&l.textContent.trim()!=="결제수단");if(!a)continue;const c=i.slice(s+2).find(l=>/^\(.+\)$/.test(l.textContent?.trim()??"")),u=c?.textContent?.trim().replace(/^\(|\)$/g,"")??"",d=u&&t.endsWith(")")?t.replace(/\)$/,`, ${u})`):t;a.textContent?.trim()!==d&&(a.textContent=d,a.dataset.kginicisPaymentMethodPatched="true"),o.dataLine truncated
//# sourceMappingURL=plugin.iife.js.map
@@ -1,233 +0,0 @@
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import {
installCheckoutNaverpayBrandButton,
patchRenderedNaverpayBrandButton,
resetCheckoutNaverpayBrandButtonForTests,
} from '../checkoutNaverpayBrandButton';
function brandButton(label: string, description: string, icon = 'wallet'): string {
return `
<button type="button">
<div class="flex items-center gap-2">
<i class="fas fa-${icon}" data-original-icon="true" role="img"></i>
<div>
<p>${label}</p>
<p>${description}</p>
</div>
</div>
</button>
`;
}
function renderPaymentButtons(): void {
document.body.innerHTML = `
${brandButton('네이버페이 (KG이니시스)', '네이버페이로 결제')}
${brandButton('삼성페이 (KG이니시스)', '삼성페이로 결제 — KG 이니시스를 통해 처리', 'mobile-screen-button')}
${brandButton('L.pay (KG이니시스)', 'L.pay 로 결제 — KG 이니시스를 통해 처리', 'mobile-screen-button')}
${brandButton('카카오페이 (KG이니시스)', '카카오페이로 결제 — KG 이니시스를 통해 처리', 'mobile-screen-button')}
${brandButton('PayPay (일본 KG이니시스)', '일본 엔(JPY) 주문을 KG 이니시스 CBT PayPay로 결제')}
${brandButton('일본 편의점결제 (KG이니시스)', '일본 엔(JPY) 주문을 KG 이니시스 CBT 편의점 결제로 접수', 'store')}
<button type="button">
<div class="flex items-center gap-3">
<svg data-original-icon="true"></svg>
<div>
<p>신용카드</p>
<p>카드로 결제</p>
</div>
</div>
</button>
`;
}
describe('checkoutNaverpayBrandButton', () => {
beforeEach(() => {
document.documentElement.lang = 'ko';
window.history.pushState({}, '', '/shop/checkout');
vi.spyOn(console, 'info').mockImplementation(() => {});
});
afterEach(() => {
resetCheckoutNaverpayBrandButtonForTests();
document.body.innerHTML = '';
vi.restoreAllMocks();
});
it('네이버페이 버튼에 title 과 브랜드 마크를 적용한다', () => {
renderPaymentButtons();
expect(patchRenderedNaverpayBrandButton()).toBe(true);
const naverpayButton = document.querySelector<HTMLButtonElement>('button[data-kginicis-brand-payment-method="kginicis_naverpay"]');
expect(naverpayButton).not.toBeNull();
expect(naverpayButton?.title).toBe('네이버페이로 결제 (kg이니시스)');
expect(naverpayButton?.dataset.kginicisNaverpayBrandButton).toBe('true');
expect(naverpayButton?.querySelector('[data-kginicis-brand-payment-mark="true"]')).not.toBeNull();
expect(naverpayButton?.querySelector('[data-kginicis-naverpay-mark="true"]')).not.toBeNull();
expect(naverpayButton?.querySelector('[data-original-icon="true"]')).toBeNull();
const heading = naverpayButton?.querySelector<HTMLElement>('p');
expect(heading?.getAttribute('aria-label')).toBe('네이버페이');
expect(heading?.textContent).toBe('네이버페이');
expect(heading?.querySelector('span')).toBeNull();
expect(heading?.style.fontSize).toBe('');
expect(heading?.style.whiteSpace).toBe('normal');
expect(heading?.style.wordBreak).toBe('keep-all');
expect(heading?.style.overflowWrap).toBe('anywhere');
const description = naverpayButton?.querySelectorAll<HTMLElement>('p')[1];
expect(description?.textContent).toBe('네이버페이로 결제 (kg이니시스)');
expect(description?.style.fontSize).toBe('12px');
expect(description?.style.lineHeight).toBe('1rem');
const row = naverpayButton?.querySelector<HTMLElement>('.flex.items-center');
expect(row?.style.width).toBe('100%');
expect(row?.style.minWidth).toBe('0');
expect(row?.style.maxWidth).toBe('100%');
const textWrapper = heading?.parentElement;
expect(textWrapper?.style.flex).toBe('1 1 0px');
expect(textWrapper?.style.minWidth).toBe('0');
expect(textWrapper?.style.maxWidth).toBe('100%');
expect(naverpayButton?.querySelector<HTMLElement>('[data-kginicis-brand-payment-mark="true"]')?.style.width).toBe('32px');
const cardButton = Array.from(document.querySelectorAll<HTMLButtonElement>('button'))
.find((button) => button.textContent?.includes('신용카드'));
expect(cardButton?.querySelector('[data-original-icon="true"]')).not.toBeNull();
});
it('브랜드 버튼 설정 대상 결제수단을 모두 아이콘과 짧은 문구로 표시한다', () => {
renderPaymentButtons();
expect(patchRenderedNaverpayBrandButton()).toBe(true);
const expected = [
['kginicis_samsung_pay', '삼성페이', '삼성페이로 결제 (kg이니시스)'],
['kginicis_naverpay', '네이버페이', '네이버페이로 결제 (kg이니시스)'],
['kginicis_lpay', 'L.pay', 'L.pay로 결제 (kg이니시스)'],
['kginicis_kakaopay', '카카오페이', '카카오페이로 결제 (kg이니시스)'],
['kginicis_japan_paypay', 'PayPay', 'PayPay로 결제 (일본 KG)'],
['kginicis_japan_cvs', '일본 편의점결제', '편의점 결제 (일본 KG)'],
];
expected.forEach(([methodId, heading, description]) => {
const button = document.querySelector<HTMLButtonElement>(`button[data-kginicis-brand-payment-method="${methodId}"]`);
expect(button).not.toBeNull();
expect(button?.querySelector('[data-kginicis-brand-payment-mark="true"]')).not.toBeNull();
expect(button?.querySelector('[data-original-icon="true"]')).toBeNull();
expect(button?.querySelectorAll<HTMLElement>('p')[0]?.textContent).toBe(heading);
expect(button?.querySelectorAll<HTMLElement>('p')[1]?.textContent).toBe(description);
});
expect(document.querySelectorAll('button[data-kginicis-brand-payment-button="true"]')).toHaveLength(6);
expect(document.querySelectorAll('[data-kginicis-brand-payment-mark="true"]')).toHaveLength(6);
});
it('좁은 카드에서는 제목과 설명을 총 2줄 compact layout 으로 정렬한다', () => {
renderPaymentButtons();
vi.spyOn(HTMLElement.prototype, 'getBoundingClientRect').mockImplementation(function (this: HTMLElement): DOMRect {
const isNaverpayButton = this instanceof HTMLButtonElement
&& (this.textContent ?? '').includes('네이버페이');
const width = isNaverpayButton ? 180 : 0;
return {
bottom: 80,
height: 80,
left: 0,
right: width,
top: 0,
width,
x: 0,
y: 0,
toJSON: () => ({}),
} as DOMRect;
});
expect(patchRenderedNaverpayBrandButton()).toBe(true);
const naverpayButton = document.querySelector<HTMLButtonElement>('button[data-kginicis-brand-payment-method="kginicis_naverpay"]');
const row = naverpayButton?.querySelector<HTMLElement>('.flex.items-center');
const paragraphs = naverpayButton?.querySelectorAll<HTMLElement>('p');
const heading = paragraphs?.[0];
const description = paragraphs?.[1];
const textWrapper = heading?.parentElement;
expect(naverpayButton?.style.paddingLeft).toBe('10px');
expect(naverpayButton?.style.paddingRight).toBe('10px');
expect(row?.style.gap).toBe('6px');
expect(row?.style.maxWidth).toBe('100%');
expect(row?.style.flexWrap).toBe('wrap');
expect(textWrapper?.style.display).toBe('contents');
expect(heading?.style.order).toBe('2');
expect(heading?.style.flex).toBe('1 1 0px');
expect(description?.style.order).toBe('3');
expect(description?.style.flex).toBe('0 0 100%');
expect(description?.style.whiteSpace).toBe('nowrap');
expect(description?.style.wordBreak).toBe('normal');
expect(description?.style.overflowWrap).toBe('normal');
expect(description?.style.fontSize).toBe('11px');
});
it('클라이언트 설정이 비활성화면 버튼을 건드리지 않는다', async () => {
renderPaymentButtons();
const fetchSpy = vi.fn(async () => new Response(JSON.stringify({
data: { easy_pay_show_brand_button: false },
}), { status: 200, headers: { 'Content-Type': 'application/json' } }));
installCheckoutNaverpayBrandButton(fetchSpy as unknown as typeof fetch);
await new Promise((resolve) => setTimeout(resolve, 0));
expect(document.querySelector('[data-kginicis-brand-payment-button="true"]')).toBeNull();
expect(document.querySelector('[data-kginicis-brand-payment-mark="true"]')).toBeNull();
});
it('클라이언트 설정이 활성화면 체크아웃에서 자동 적용한다', async () => {
renderPaymentButtons();
const fetchSpy = vi.fn(async () => new Response(JSON.stringify({
data: { easy_pay_show_brand_button: true },
}), { status: 200, headers: { 'Content-Type': 'application/json' } }));
installCheckoutNaverpayBrandButton(fetchSpy as unknown as typeof fetch);
await new Promise((resolve) => setTimeout(resolve, 0));
expect(document.querySelector('[data-kginicis-brand-payment-button="true"]')).not.toBeNull();
expect(document.querySelector('[data-kginicis-brand-payment-mark="true"]')).not.toBeNull();
});
it('결제수단 텍스트가 늦게 채워져도 자동 적용한다', async () => {
document.body.innerHTML = `
<button>
<div class="flex items-center gap-3">
<i class="fas fa-wallet" data-original-icon="true" role="img"></i>
<div>
<p id="late-heading"></p>
<p id="late-description"></p>
</div>
</div>
</button>
`;
const heading = document.getElementById('late-heading');
const description = document.getElementById('late-description');
heading?.appendChild(document.createTextNode(''));
description?.appendChild(document.createTextNode(''));
const fetchSpy = vi.fn(async () => new Response(JSON.stringify({
data: { easy_pay_show_brand_button: true },
}), { status: 200, headers: { 'Content-Type': 'application/json' } }));
installCheckoutNaverpayBrandButton(fetchSpy as unknown as typeof fetch);
await new Promise((resolve) => setTimeout(resolve, 0));
expect(document.querySelector('[data-kginicis-brand-payment-button="true"]')).toBeNull();
if (heading?.firstChild) heading.firstChild.nodeValue = '네이버페이 (KG이니시스)';
if (description?.firstChild) description.firstChild.nodeValue = '네이버페이로 결제';
await new Promise((resolve) => setTimeout(resolve, 0));
const naverpayButton = document.querySelector<HTMLButtonElement>('button[data-kginicis-brand-payment-method="kginicis_naverpay"]');
expect(naverpayButton).not.toBeNull();
expect(naverpayButton?.title).toBe('네이버페이로 결제 (kg이니시스)');
expect(naverpayButton?.querySelector('[data-kginicis-brand-payment-mark="true"]')).not.toBeNull();
expect(naverpayButton?.querySelector<HTMLElement>('p')?.textContent).toBe('네이버페이');
expect(naverpayButton?.querySelectorAll<HTMLElement>('p')[1]?.textContent).toBe('네이버페이로 결제 (kg이니시스)');
});
});
@@ -1,504 +0,0 @@
const PLUGIN_ID = 'sirsoft-pay_kginicis';
const FLAG = '__sirsoftKginicisCheckoutBrandPaymentButtonsInstalled';
const CHECKOUT_RE = /^\/shop\/checkout\/?$/;
const CLIENT_CONFIG_PATH = '/api/modules/sirsoft-ecommerce/payments/client-config/kginicis';
const TWO_LINE_COMPACT_WIDTH = 220;
const DEFAULT_PADDING_X = 12;
const COMPACT_PADDING_X = 10;
let observer: MutationObserver | null = null;
let cachedEnabled: Promise<boolean> | null = null;
let retryTimer: number | null = null;
interface ClientConfigBody {
data?: {
easy_pay_show_brand_button?: boolean;
};
}
interface BrandPaymentCopy {
heading: string;
description: string;
title: string;
}
interface BrandPaymentDefinition {
id: string;
labels: string[];
ko: BrandPaymentCopy;
en: BrandPaymentCopy;
markSvg: string;
}
const BRAND_PAYMENT_DEFINITIONS: BrandPaymentDefinition[] = [
{
id: 'kginicis_naverpay',
labels: ['네이버페이 (KG이니시스)', 'Naver Pay (KG Inicis)'],
ko: {
heading: '네이버페이',
description: '네이버페이로 결제 (kg이니시스)',
title: '네이버페이로 결제 (kg이니시스)',
},
en: {
heading: 'Naver Pay',
description: 'Pay with Naver Pay (KG Inicis)',
title: 'Pay with Naver Pay (KG Inicis)',
},
markSvg: [
'<svg xmlns="http://www.w3.org/2000/svg" width="32" height="32" viewBox="0 0 40 40" role="img" aria-label="Naver Pay">',
'<rect width="40" height="40" rx="8" fill="#03C75A"/>',
'<text x="20" y="17" text-anchor="middle" fill="#ffffff" font-family="Arial, sans-serif" font-size="12" font-weight="700">N</text>',
'<text x="20" y="29" text-anchor="middle" fill="#ffffff" font-family="Arial, sans-serif" font-size="9" font-weight="700">Pay</text>',
'</svg>',
].join(''),
},
{
id: 'kginicis_samsung_pay',
labels: ['삼성페이 (KG이니시스)', 'Samsung Pay (KG Inicis)'],
ko: {
heading: '삼성페이',
description: '삼성페이로 결제 (kg이니시스)',
title: '삼성페이로 결제 (kg이니시스)',
},
en: {
heading: 'Samsung Pay',
description: 'Pay with Samsung Pay (KG Inicis)',
title: 'Pay with Samsung Pay (KG Inicis)',
},
markSvg: [
'<svg xmlns="http://www.w3.org/2000/svg" width="32" height="32" viewBox="0 0 40 40" role="img" aria-label="Samsung Pay">',
'<rect width="40" height="40" rx="8" fill="#1428A0"/>',
'<text x="20" y="18" text-anchor="middle" fill="#ffffff" font-family="Arial, sans-serif" font-size="10" font-weight="700">S</text>',
'<text x="20" y="29" text-anchor="middle" fill="#ffffff" font-family="Arial, sans-serif" font-size="9" font-weight="700">Pay</text>',
'</svg>',
].join(''),
},
{
id: 'kginicis_lpay',
labels: ['L.pay (KG이니시스)', 'L.pay (KG Inicis)'],
ko: {
heading: 'L.pay',
description: 'L.pay로 결제 (kg이니시스)',
title: 'L.pay로 결제 (kg이니시스)',
},
en: {
heading: 'L.pay',
description: 'Pay with L.pay (KG Inicis)',
title: 'Pay with L.pay (KG Inicis)',
},
markSvg: [
'<svg xmlns="http://www.w3.org/2000/svg" width="32" height="32" viewBox="0 0 40 40" role="img" aria-label="L.pay">',
'<rect width="40" height="40" rx="8" fill="#D71920"/>',
'<text x="20" y="18" text-anchor="middle" fill="#ffffff" font-family="Arial, sans-serif" font-size="12" font-weight="700">L</text>',
'<text x="20" y="29" text-anchor="middle" fill="#ffffff" font-family="Arial, sans-serif" font-size="8" font-weight="700">pay</text>',
'</svg>',
].join(''),
},
{
id: 'kginicis_kakaopay',
labels: ['카카오페이 (KG이니시스)', 'Kakao Pay (KG Inicis)'],
ko: {
heading: '카카오페이',
description: '카카오페이로 결제 (kg이니시스)',
title: '카카오페이로 결제 (kg이니시스)',
},
en: {
heading: 'Kakao Pay',
description: 'Pay with Kakao Pay (KG Inicis)',
title: 'Pay with Kakao Pay (KG Inicis)',
},
markSvg: [
'<svg xmlns="http://www.w3.org/2000/svg" width="32" height="32" viewBox="0 0 40 40" role="img" aria-label="Kakao Pay">',
'<rect width="40" height="40" rx="8" fill="#FEE500"/>',
'<text x="20" y="18" text-anchor="middle" fill="#111111" font-family="Arial, sans-serif" font-size="9" font-weight="700">Kakao</text>',
'<text x="20" y="29" text-anchor="middle" fill="#111111" font-family="Arial, sans-serif" font-size="9" font-weight="700">Pay</text>',
'</svg>',
].join(''),
},
{
id: 'kginicis_japan_paypay',
labels: ['PayPay (일본 KG이니시스)', 'PayPay (KG Inicis Japan)'],
ko: {
heading: 'PayPay',
description: 'PayPay로 결제 (일본 KG)',
title: 'PayPay로 결제 (일본 KG이니시스)',
},
en: {
heading: 'PayPay',
description: 'Pay with PayPay (KG Japan)',
title: 'Pay with PayPay (KG Inicis Japan)',
},
markSvg: [
'<svg xmlns="http://www.w3.org/2000/svg" width="32" height="32" viewBox="0 0 40 40" role="img" aria-label="PayPay">',
'<rect width="40" height="40" rx="8" fill="#E60012"/>',
'<text x="20" y="18" text-anchor="middle" fill="#ffffff" font-family="Arial, sans-serif" font-size="8" font-weight="700">Pay</text>',
'<text x="20" y="29" text-anchor="middle" fill="#ffffff" font-family="Arial, sans-serif" font-size="8" font-weight="700">Pay</text>',
'</svg>',
].join(''),
},
{
id: 'kginicis_japan_cvs',
labels: ['일본 편의점결제 (KG이니시스)', 'Japan Convenience Store (KG Inicis)'],
ko: {
heading: '일본 편의점결제',
description: '편의점 결제 (일본 KG)',
title: '일본 편의점결제 (KG이니시스)',
},
en: {
heading: 'Convenience Store',
description: 'Pay at store (KG Japan)',
title: 'Japan Convenience Store (KG Inicis)',
},
markSvg: [
'<svg xmlns="http://www.w3.org/2000/svg" width="32" height="32" viewBox="0 0 40 40" role="img" aria-label="Convenience Store">',
'<rect width="40" height="40" rx="8" fill="#0072CE"/>',
'<text x="20" y="18" text-anchor="middle" fill="#ffffff" font-family="Arial, sans-serif" font-size="9" font-weight="700">CVS</text>',
'<text x="20" y="29" text-anchor="middle" fill="#ffffff" font-family="Arial, sans-serif" font-size="8" font-weight="700">JP</text>',
'</svg>',
].join(''),
},
];
const logger = {
info: (...args: unknown[]) => console.info(`[${PLUGIN_ID}]`, ...args),
};
function windowRecord(): Record<string, unknown> {
return window as unknown as Record<string, unknown>;
}
function isCheckoutPage(): boolean {
return CHECKOUT_RE.test(window.location.pathname);
}
function isKoreanPage(): boolean {
const lang = document.documentElement.lang || navigator.language || '';
return lang.toLowerCase().startsWith('ko');
}
function copyFor(definition: BrandPaymentDefinition): BrandPaymentCopy {
return isKoreanPage() ? definition.ko : definition.en;
}
function normalizedText(value: string | null | undefined): string {
return (value ?? '').replace(/\s+/g, ' ').trim();
}
function getButtonWidth(button: HTMLButtonElement): number {
const rectWidth = button.getBoundingClientRect().width;
return rectWidth > 0 ? rectWidth : button.clientWidth;
}
function shouldUseTwoLineCompactLayout(button: HTMLButtonElement): boolean {
const width = getButtonWidth(button);
return width > 0 && width < TWO_LINE_COMPACT_WIDTH;
}
function compactDescriptionFontSize(button: HTMLButtonElement): string {
const availableWidth = getButtonWidth(button) - (COMPACT_PADDING_X * 2);
if (availableWidth > 0 && availableWidth < 144) {
return '9.5px';
}
if (availableWidth > 0 && availableWidth < 160) {
return '10px';
}
if (availableWidth > 0 && availableWidth < 176) {
return '11px';
}
return '12px';
}
async function fetchEnabled(fetchImpl: typeof fetch): Promise<boolean> {
if (cachedEnabled !== null) return cachedEnabled;
cachedEnabled = (async () => {
try {
const response = await fetchImpl(CLIENT_CONFIG_PATH, {
headers: { Accept: 'application/json' },
});
if (!response.ok) return false;
const body = (await response.json()) as ClientConfigBody;
return body.data?.easy_pay_show_brand_button === true;
} catch {
return false;
}
})();
return cachedEnabled;
}
function findBrandPaymentDefinition(button: HTMLButtonElement): BrandPaymentDefinition | null {
const methodId = button.dataset.kginicisBrandPaymentMethod;
const existing = BRAND_PAYMENT_DEFINITIONS.find((definition) => definition.id === methodId);
if (existing) return existing;
if (button.dataset.kginicisNaverpayBrandButton === 'true') {
return BRAND_PAYMENT_DEFINITIONS.find((definition) => definition.id === 'kginicis_naverpay') ?? null;
}
const text = normalizedText(button.textContent);
return BRAND_PAYMENT_DEFINITIONS.find((definition) => {
const copy = copyFor(definition);
return definition.labels.some((label) => text.includes(label))
|| text.includes(definition.ko.heading)
|| text.includes(definition.en.heading)
|| text.includes(copy.heading);
}) ?? null;
}
function findHeading(
paragraphs: HTMLParagraphElement[] | HTMLElement[],
definition: BrandPaymentDefinition,
): HTMLElement | null {
const copy = copyFor(definition);
return paragraphs.find((element) => {
const text = normalizedText(element.textContent);
return element.dataset.kginicisBrandPaymentHeading === definition.id
|| definition.labels.some((label) => text.includes(label))
|| text.includes(definition.ko.heading)
|| text.includes(definition.en.heading)
|| text.includes(copy.heading);
}) ?? null;
}
function formatBrandPaymentText(button: HTMLButtonElement, definition: BrandPaymentDefinition): void {
const paragraphs = Array.from(button.querySelectorAll<HTMLParagraphElement>('p'));
const heading = findHeading(paragraphs, definition);
if (!heading) return;
const copy = copyFor(definition);
if (heading.textContent !== copy.heading) {
heading.textContent = copy.heading;
}
heading.dataset.kginicisBrandPaymentHeading = definition.id;
if (definition.id === 'kginicis_naverpay') {
heading.dataset.kginicisNaverpayHeading = copy.heading;
}
if (heading.getAttribute('aria-label') !== copy.heading) {
heading.setAttribute('aria-label', copy.heading);
}
const description = paragraphs[paragraphs.indexOf(heading as HTMLParagraphElement) + 1]
?? paragraphs.find((element) => element !== heading);
if (!description) return;
if (description.textContent !== copy.description) {
description.textContent = copy.description;
}
description.dataset.kginicisBrandPaymentDescription = definition.id;
if (definition.id === 'kginicis_naverpay') {
description.dataset.kginicisNaverpayDescription = copy.description;
}
}
function applyCompactBrandPaymentLayout(button: HTMLButtonElement, definition: BrandPaymentDefinition): void {
const useTwoLineCompact = shouldUseTwoLineCompactLayout(button);
const paddingX = useTwoLineCompact ? COMPACT_PADDING_X : DEFAULT_PADDING_X;
button.style.paddingLeft = `${paddingX}px`;
button.style.paddingRight = `${paddingX}px`;
button.style.boxSizing = 'border-box';
button.style.minWidth = '0';
const row = button.querySelector<HTMLElement>('.flex.items-center.gap-2, .flex.items-center.gap-3')
?? button.querySelector<HTMLElement>('.flex.items-center');
if (row) {
row.style.gap = useTwoLineCompact ? '6px' : '8px';
row.style.width = '100%';
row.style.minWidth = '0';
row.style.maxWidth = '100%';
row.style.boxSizing = 'border-box';
row.style.flexWrap = useTwoLineCompact ? 'wrap' : 'nowrap';
}
const heading = findHeading(
Array.from(button.querySelectorAll<HTMLElement>('p')),
definition,
);
if (!heading) return;
heading.style.whiteSpace = 'normal';
heading.style.wordBreak = 'keep-all';
heading.style.overflowWrap = 'anywhere';
heading.style.removeProperty('font-size');
heading.style.removeProperty('line-height');
heading.style.maxWidth = '100%';
const textWrapper = heading.parentElement;
if (textWrapper instanceof HTMLElement) {
textWrapper.style.display = useTwoLineCompact ? 'contents' : '';
textWrapper.style.flex = useTwoLineCompact ? '' : '1 1 0px';
textWrapper.style.minWidth = '0';
textWrapper.style.maxWidth = '100%';
Array.from(textWrapper.querySelectorAll<HTMLElement>('p')).forEach((paragraph) => {
paragraph.style.minWidth = '0';
paragraph.style.maxWidth = '100%';
paragraph.style.whiteSpace = 'normal';
paragraph.style.wordBreak = 'keep-all';
paragraph.style.overflowWrap = 'anywhere';
paragraph.style.removeProperty('order');
paragraph.style.removeProperty('flex');
});
const description = Array.from(textWrapper.querySelectorAll<HTMLElement>('p')).find((paragraph) => (
paragraph.dataset.kginicisBrandPaymentDescription === definition.id
|| paragraph !== heading
));
if (description) {
if (useTwoLineCompact) {
heading.style.order = '2';
heading.style.flex = '1 1 0px';
description.style.order = '3';
description.style.flex = '0 0 100%';
description.style.whiteSpace = 'nowrap';
description.style.wordBreak = 'normal';
description.style.overflowWrap = 'normal';
}
description.style.fontSize = useTwoLineCompact
? compactDescriptionFontSize(button)
: '12px';
description.style.lineHeight = '1rem';
}
}
}
function createBrandPaymentMark(definition: BrandPaymentDefinition): HTMLSpanElement {
const mark = document.createElement('span');
mark.dataset.kginicisBrandPaymentMark = 'true';
mark.dataset.kginicisBrandPaymentMethod = definition.id;
if (definition.id === 'kginicis_naverpay') {
mark.dataset.kginicisNaverpayMark = 'true';
}
mark.setAttribute('aria-hidden', 'true');
mark.style.display = 'inline-flex';
mark.style.width = '32px';
mark.style.height = '32px';
mark.style.flex = '0 0 32px';
mark.style.alignItems = 'center';
mark.style.justifyContent = 'center';
mark.innerHTML = definition.markSvg;
return mark;
}
function findPaymentIcon(button: HTMLButtonElement): Element | null {
return button.querySelector('svg')
?? button.querySelector('i[class*="fa-"], i[role="img"], i');
}
function findPaymentRow(button: HTMLButtonElement): HTMLElement | null {
return button.querySelector<HTMLElement>('.flex.items-center.gap-2, .flex.items-center.gap-3')
?? button.querySelector<HTMLElement>('.flex.items-center');
}
export function patchRenderedNaverpayBrandButton(root: ParentNode = document): boolean {
let patched = false;
root.querySelectorAll<HTMLButtonElement>('button').forEach((button) => {
const definition = findBrandPaymentDefinition(button);
if (!definition) return;
const copy = copyFor(definition);
button.title = copy.title;
button.dataset.kginicisBrandPaymentButton = 'true';
button.dataset.kginicisBrandPaymentMethod = definition.id;
if (definition.id === 'kginicis_naverpay') {
button.dataset.kginicisNaverpayBrandButton = 'true';
}
formatBrandPaymentText(button, definition);
applyCompactBrandPaymentLayout(button, definition);
if (button.querySelector('[data-kginicis-brand-payment-mark="true"], [data-kginicis-naverpay-mark="true"]')) {
return;
}
const mark = createBrandPaymentMark(definition);
const icon = findPaymentIcon(button);
if (icon && icon.parentElement) {
icon.replaceWith(mark);
patched = true;
return;
}
const row = findPaymentRow(button);
if (!row) return;
row.prepend(mark);
patched = true;
});
return patched;
}
function stopPatchRetries(): void {
if (retryTimer === null) return;
window.clearInterval(retryTimer);
retryTimer = null;
}
function startPatchRetries(): void {
stopPatchRetries();
let attempts = 0;
retryTimer = window.setInterval(() => {
attempts += 1;
patchRenderedNaverpayBrandButton();
if (attempts >= 50) {
stopPatchRetries();
}
}, 200);
}
async function startDomPatchLoop(fetchImpl: typeof fetch): Promise<void> {
if (!isCheckoutPage()) return;
if (!(await fetchEnabled(fetchImpl))) return;
patchRenderedNaverpayBrandButton();
startPatchRetries();
if (observer === null) {
observer = new MutationObserver(() => {
patchRenderedNaverpayBrandButton();
});
observer.observe(document.body, { childList: true, subtree: true, characterData: true });
}
}
export function installCheckoutNaverpayBrandButton(fetchImpl: typeof fetch = fetch): void {
if (typeof window === 'undefined' || typeof document === 'undefined') return;
if (windowRecord()[FLAG] === true) return;
windowRecord()[FLAG] = true;
void startDomPatchLoop(fetchImpl).then(() => {
logger.info('checkout KG Inicis brand payment button patcher installed');
});
}
export function resetCheckoutNaverpayBrandButtonForTests(): void {
observer?.disconnect();
observer = null;
stopPatchRetries();
cachedEnabled = null;
delete windowRecord()[FLAG];
}
@@ -6,7 +6,6 @@ import { installOrderCompleteReceiptInjector } from './orderCompleteReceiptInjec
import { installVbankInfoInjector } from './vbankInfoInjector';
import { installPaymentCloseMessageListener } from './paymentCloseMessageListener';
import { installCheckoutJpyPaymentMethodRestrictor } from './checkoutJpyPaymentMethodRestrictor';
import { installCheckoutNaverpayBrandButton } from './checkoutNaverpayBrandButton';
import { installAdminPaymentMethodBrandInjector } from './adminPaymentMethodBrandInjector';
const PLUGIN_IDENTIFIER = 'sirsoft-pay_kginicis';
@@ -88,7 +87,6 @@ function initPlugin(): void {
// (체크아웃 템플릿이 코어 영역이라 수정 불가하므로 클라이언트 사이드 우회)
installOrderResponseInterceptor();
installCheckoutJpyPaymentMethodRestrictor();
installCheckoutNaverpayBrandButton();
installMypageOrderShowInjector();
installAdminOrderPaymentDisplayInjector();
@@ -37,6 +37,25 @@ class RegisterEasyPayMethodsListener implements HookListenerInterface
'kginicis_kakaopay' => 'easy_pay_kakaopay',
];
/**
* 결제수단별 브랜드 마크(인라인 SVG 로고).
*
* 코어 카탈로그가 `_cached_brand_mark` 로 전달하고, 체크아웃 레이아웃의 BrandMark
* 컴포넌트가 화이트리스트 sanitize 후 렌더한다. 과거에는 체크아웃 DOM 인젝터
* (checkoutNaverpayBrandButton.ts) 가 렌더 후 이 SVG 를 주입했으나, 시각정보를
* 카탈로그로 편입해 인젝터를 제거했다.
*
* @var array<string, string>
*/
private const BRAND_MARK_SVG = [
'kginicis_naverpay' => '<svg xmlns="http://www.w3.org/2000/svg" width="32" height="32" viewBox="0 0 40 40" role="img" aria-label="Naver Pay"><rect width="40" height="40" rx="8" fill="#03C75A"/><text x="20" y="17" text-anchor="middle" fill="#ffffff" font-family="Arial, sans-serif" font-size="12" font-weight="700">N</text><text x="20" y="29" text-anchor="middle" fill="#ffffff" font-family="Arial, sans-serif" font-size="9" font-weight="700">Pay</text></svg>',
'kginicis_samsung_pay' => '<svg xmlns="http://www.w3.org/2000/svg" width="32" height="32" viewBox="0 0 40 40" role="img" aria-label="Samsung Pay"><rect width="40" height="40" rx="8" fill="#1428A0"/><text x="20" y="18" text-anchor="middle" fill="#ffffff" font-family="Arial, sans-serif" font-size="10" font-weight="700">S</text><text x="20" y="29" text-anchor="middle" fill="#ffffff" font-family="Arial, sans-serif" font-size="9" font-weight="700">Pay</text></svg>',
'kginicis_lpay' => '<svg xmlns="http://www.w3.org/2000/svg" width="32" height="32" viewBox="0 0 40 40" role="img" aria-label="L.pay"><rect width="40" height="40" rx="8" fill="#D71920"/><text x="20" y="18" text-anchor="middle" fill="#ffffff" font-family="Arial, sans-serif" font-size="12" font-weight="700">L</text><text x="20" y="29" text-anchor="middle" fill="#ffffff" font-family="Arial, sans-serif" font-size="8" font-weight="700">pay</text></svg>',
'kginicis_kakaopay' => '<svg xmlns="http://www.w3.org/2000/svg" width="32" height="32" viewBox="0 0 40 40" role="img" aria-label="Kakao Pay"><rect width="40" height="40" rx="8" fill="#FEE500"/><text x="20" y="18" text-anchor="middle" fill="#111111" font-family="Arial, sans-serif" font-size="9" font-weight="700">Kakao</text><text x="20" y="29" text-anchor="middle" fill="#111111" font-family="Arial, sans-serif" font-size="9" font-weight="700">Pay</text></svg>',
'kginicis_japan_paypay' => '<svg xmlns="http://www.w3.org/2000/svg" width="32" height="32" viewBox="0 0 40 40" role="img" aria-label="PayPay"><rect width="40" height="40" rx="8" fill="#E60012"/><text x="20" y="18" text-anchor="middle" fill="#ffffff" font-family="Arial, sans-serif" font-size="8" font-weight="700">Pay</text><text x="20" y="29" text-anchor="middle" fill="#ffffff" font-family="Arial, sans-serif" font-size="8" font-weight="700">Pay</text></svg>',
'kginicis_japan_cvs' => '<svg xmlns="http://www.w3.org/2000/svg" width="32" height="32" viewBox="0 0 40 40" role="img" aria-label="Convenience Store"><rect width="40" height="40" rx="8" fill="#0072CE"/><text x="20" y="18" text-anchor="middle" fill="#ffffff" font-family="Arial, sans-serif" font-size="9" font-weight="700">CVS</text><text x="20" y="29" text-anchor="middle" fill="#ffffff" font-family="Arial, sans-serif" font-size="8" font-weight="700">JP</text></svg>',
];
/**
* 구독할 훅 매핑 반환.
*
@@ -193,7 +212,7 @@ class RegisterEasyPayMethodsListener implements HookListenerInterface
*/
private function buildEntry(string $id, string $nameKey, string $descriptionKey, string $icon, bool $isActive = false): array
{
return [
$entry = [
'id' => $id,
'name' => [
'ko' => __($nameKey, [], 'ko'),
@@ -219,5 +238,13 @@ class RegisterEasyPayMethodsListener implements HookListenerInterface
'mileage_deduction_timing' => 'payment_complete',
],
];
// 브랜드 마크(SVG 로고)가 정의된 수단만 카탈로그에 실어 내린다.
// 레이아웃 BrandMark 컴포넌트가 svg 키를 화이트리스트 sanitize 후 렌더한다.
if (isset(self::BRAND_MARK_SVG[$id])) {
$entry['brand_mark'] = ['svg' => self::BRAND_MARK_SVG[$id]];
}
return $entry;
}
}
@@ -164,6 +164,46 @@ class RegisterEasyPayMethodsListenerTest extends PluginTestCase
}
}
/**
* @scenario mark_form=svg, requires_ios=false, device=ipados_desktop_ua
*
* @effects brand_mark_flows_to_cached, svg_renders_inline_logo, shared_helpers_preserved
*/
public function test_easy_pay_methods_carry_svg_brand_mark(): void
{
// 브랜드 SVG 로고를 카탈로그로 편입 — 과거 checkoutNaverpayBrandButton 이
// DOM 후처리로 주입하던 markSvg 를 등록 데이터(brand_mark.svg)로 이관.
$this->mockSettings([
'easy_pay_samsung_pay' => false,
'easy_pay_naverpay' => false,
'easy_pay_lpay' => false,
'easy_pay_kakaopay' => false,
'japan_enabled' => true,
]);
$listener = new RegisterEasyPayMethodsListener;
$methods = collect($listener->injectEasyPayMethods([
['id' => 'phone'],
['id' => 'point'],
]))->keyBy('id');
$naverpay = $methods->get('kginicis_naverpay');
$kakaopay = $methods->get('kginicis_kakaopay');
$this->assertIsArray($naverpay['brand_mark'] ?? null);
$this->assertArrayHasKey('svg', $naverpay['brand_mark']);
$this->assertStringContainsString('<svg', $naverpay['brand_mark']['svg']);
$this->assertStringContainsString('#03C75A', $naverpay['brand_mark']['svg']);
$this->assertStringContainsString('#FEE500', $kakaopay['brand_mark']['svg'] ?? '');
// KG 이니시스는 애플페이 수단이 없으므로 requires_ios 플래그도 없어야 한다.
foreach ($methods as $method) {
$this->assertArrayNotHasKey('requires_ios', $method);
}
}
public function test_legacy_easy_pay_settings_are_used_as_default_active_state(): void
{
$this->mockSettings([
@@ -22,6 +22,8 @@
- 간편결제가 정식 결제수단으로 취급되어 주문 내역에 실제로 선택한 결제수단(예: 네이버페이)이 그대로 기록됩니다.
- 쇼핑몰 환경설정 > 주문설정의 결제수단 목록에서 간편결제가 "PG 고정 · NHN KCP"로 표시됩니다. 간편결제는 NHN KCP 전용이므로 다른 결제대행사로 바꿀 수 없습니다.
- 결제창을 띄우기 위해 브라우저 요청을 가로채 결제수단을 바꿔치기하던 내부 처리를 제거했습니다. 결제 진행 방식이 표준화됩니다.
- 주문서의 간편결제 버튼에 표시되는 브랜드 마크(PAYCO·네이버페이·카카오페이 등의 색상 배지)를 화면이 그려진 뒤 덧입히던 방식에서 결제수단 정보로 처음부터 표시하는 방식으로 바꿨습니다. 여러 결제사가 함께 켜져 있을 때 표시가 안정적입니다.
- 애플페이 간편결제 버튼이 iOS 기기(iPhone·iPad)에서만 주문서에 표시되도록 했습니다. 애플페이는 iOS에서만 결제할 수 있으므로 다른 기기에서는 버튼을 감춰 혼선을 줄입니다.
## [1.0.0-beta.5] - 2026-06-23
+2 -2
View File
@@ -1,4 +1,4 @@
(function(){"use strict";function Je(e){return/^https?:\/\//i.test(e)||e.startsWith("/api/")?e:e.startsWith("/plugins/")?`/api${e}`:e.startsWith("plugins/")?`/api/${e}`:e}function Qe(e){return e.trim().slice(0,160)}function Xe(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 a=await fetch(Je(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 i=await a.json(),s=Array.isArray(i?.errors?.message)?i.errors.message[0]:i?.error??i?.message;typeof s=="string"&&s.trim()!==""&&(o=s)}catch{}throw new Error(o)}}async function Ze(e){const t=Xe(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??""})}async function et(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:Qe(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 tt="nhnkcp_applepay";function N(e){return e===tt}function P(){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 M(){return((typeof document<"u"?document.documentElement.lang:"")||"").toLowerCase().startsWith("ko")?"애플페이는 IOS 기기에 모바일결제만 가능합니다.":"Apple Pay is available only for mobile payments on iOS devices."}function T(e){return(e??"KRW").trim().toUpperCase()||"KRW"}function nt(e){return T(e)==="KRW"}function rt(e){const t=T(e);return((typeof document<"u"?document.documentElement.lang:"")||"").toLowerCase().startsWith("ko")?`NHN KCP는 KRW 결제만 지원합니다. (${t})`:`NHN KCP supports KRW payments only. (${t})`}function at(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),i=o>0&&r>0&&a>0?Math.min(o,Math.round(o*(a/r))):0,s=o-i;return{tax_flag:"TG03",comm_tax_mny:String(s),comm_vat_mny:String(i),comm_free_mny:String(n)}}class $ extends Error{constructor(t){super(t??"결제가 취소되었습니다."),this.name="KcpCancelledError"}}const ot={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 it(e,t){const n=e.toLowerCase();return!t||!Object.prototype.hasOwnProperty.call(ie,n)?{}:{param_opt_1:n,nhnkcp_easy_pay_method:n}}function st(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 ct(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)},i=()=>{n||!st(e)||(o(),t())},s=document.body??document.documentElement;return s&&typeof MutationObserver<"u"&&(a=new MutationObserver(i),a.observe(s,{attributes:!0,attributeFilter:["class","hidden","style"],childList:!0,subtree:!0})),r=window.setInterval(i,300),o}function dt(){if(typeof navigator>"u")return!1;if(P())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 lt(e,t){const{pgPaymentData:n,paymentMethod:r}=e.params||{};if(!n){console.error("[sirsoft-pay_nhnkcp] pgPaymentData is required");return}const a=r??n.payment_method??n.pay_method??"card",o=typeof a=="string"&&a.startsWith("nhnkcp_"),i=window.G7Core;let s=null;try{if(!nt(n.currency)){const u=rt(n.currency);i?.state?.setLocal?.({paymentErrorMessage:u,isSubmittingOrder:!1,paymentMethod:a}),i?.modal?.open?.("nhnkcp_payment_error_modal");return}if(N(a)&&!P()){const u=M();i?.state?.setLocal?.({paymentErrorMessage:u,isSubmittingOrder:!1,paymentMethod:a}),i?.modal?.open?.("nhnkcp_payment_error_modal");return}const c=await i.api.get("/modules/sirsoft-ecommerce/payments/client-config/nhnkcp");if(!c.data){console.error("[Line truncated
(function(){"use strict";function Le(e){return/^https?:\/\//i.test(e)||e.startsWith("/api/")?e:e.startsWith("/plugins/")?`/api${e}`:e.startsWith("plugins/")?`/api/${e}`:e}function Oe(e){return e.trim().slice(0,160)}function Ke(e){if(e)return e.replace(/\/payment\/close-report$/,"/payment/retry")}async function ee(e,t,n=!1){const o=window.G7Core?.api;if(typeof o?.post=="function"){await o.post(e,t);return}const r=await fetch(Le(e),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t),keepalive:n});if(!r.ok){let a=`NHN KCP payment request failed (${r.status})`;try{const s=await r.json(),i=Array.isArray(s?.errors?.message)?s.errors.message[0]:s?.error??s?.message;typeof i=="string"&&i.trim()!==""&&(a=i)}catch{}throw new Error(a)}}async function je(e){const t=Ke(e.closeReportUrl);t&&await ee(t,{oid:e.oid,price:Number(e.price),buyer_email:e.buyer_email??"",buyer_phone:e.buyer_phone??"",payment_method:e.payment_method??""})}async function Be(e,t="kcp-window-closed"){if(!e.closeReportUrl)return;const n={oid:e.oid,price:Number(e.price),buyer_email:e.buyer_email??"",buyer_phone:e.buyer_phone??"",payment_method:e.payment_method??"",reason:Oe(t)||"kcp-window-closed"};try{await ee(e.closeReportUrl,n,!0)}catch(o){console.warn("[sirsoft-pay_nhnkcp] failed to report payment window close",o)}}const De="nhnkcp_applepay";function S(e){return e===De}function x(){if(typeof navigator>"u")return!1;const e=navigator,t=(e.userAgent||"").toLowerCase(),n=((e.userAgentData?.platform??e.platform)||"").toLowerCase(),o=e.maxTouchPoints??0;return/iphone|ipad|ipod/.test(t)||/iphone|ipad|ipod|ios/.test(n)?!0:/macintosh|mac os x/.test(t)&&o>1}function M(){return((typeof document<"u"?document.documentElement.lang:"")||"").toLowerCase().startsWith("ko")?"애플페이는 IOS 기기에 모바일결제만 가능합니다.":"Apple Pay is available only for mobile payments on iOS devices."}function T(e){return(e??"KRW").trim().toUpperCase()||"KRW"}function He(e){return T(e)==="KRW"}function Fe(e){const t=T(e);return((typeof document<"u"?document.documentElement.lang:"")||"").toLowerCase().startsWith("ko")?`NHN KCP는 KRW 결제만 지원합니다. (${t})`:`NHN KCP supports KRW payments only. (${t})`}function qe(e){const t=Math.max(0,Math.round(Number(e.amount??0))),n=Math.min(Math.max(0,Math.round(Number(e.tax_free_amount??0))),t);if(n<=0)return{};const o=Math.max(0,Math.round(Number(e.tax_amount??0))),r=Math.max(0,Math.round(Number(e.vat_amount??0))),a=Math.max(0,t-n),s=a>0&&o>0&&r>0?Math.min(a,Math.round(a*(r/o))):0,i=a-s;return{tax_flag:"TG03",comm_tax_mny:String(i),comm_vat_mny:String(s),comm_free_mny:String(n)}}class R extends Error{constructor(t){super(t??"결제가 취소되었습니다."),this.name="KcpCancelledError"}}const Ue={card:"100000000000",bank_transfer:"010000000000",virtual_account:"001000000000",mobile:"000010000000",bank:"010000000000",vbank:"001000000000",phone:"000010000000"},te={nhnkcp_payco:{payco_direct:"Y"},nhnkcp_naverpay:{naverpay_direct:"Y"},nhnkcp_naverpay_point:{naverpay_direct:"Y",naverpay_point_direct:"Y"},nhnkcp_kakaopay:{kakaopay_direct:"Y"},nhnkcp_applepay:{applepay_direct:"Y"}};function Ye(e,t){const n=e.toLowerCase();return!t||!Object.prototype.hasOwnProperty.call(te,n)?{}:{param_opt_1:n,nhnkcp_easy_pay_method:n}}function Ge(e){if(!e.isConnected)return!0;const t=window.getComputedStyle(e);if(t.display==="none"||t.visibility==="hidden")return!0;const n=e.getBoundingClientRect();return n.width<=0||n.height<=0}function We(e,t){let n=!1,o,r;const a=()=>{n=!0,r&&(r.disconnect(),r=void 0),o!==void 0&&(window.clearInterval(o),o=void 0)},s=()=>{n||!Ge(e)||(a(),t())},i=document.body??document.documentElement;return i&&typeof MutationObserver<"u"&&(r=new MutationObserver(s),r.observe(i,{attributes:!0,attributeFilter:["class","hidden","style"],childList:!0,subtree:!0})),o=window.setInterval(s,300),a}function ze(){if(typeof navigator>"u")return!1;if(x())return!0;const e=navigator;if(e.userAgentData?.mobile!==void 0)return e.userAgentData.mobile;const t=(navigator.userAgent||"").toLowerCase();return!!(/android|iphone|ipod|windows phone|iemobile|blackberry|opera mini|mobile safari/.test(t)||(navigator.maxTouchPoints??0)>1&&!t.includes("windows")&&!t.includes("macintosh"))}async function Je(e,t){const{pgPaymentData:n,paymentMethod:o}=e.params||{};if(!n){console.error("[sirsoft-pay_nhnkcp] pgPaymentData is required");return}const r=o??n.payment_method??n.pay_method??"card",a=typeof r=="string"&&r.startsWith("nhnkcp_"),s=window.G7Core;let i=null;try{if(!He(n.currency)){const u=Fe(n.currency);s?.state?.setLocal?.({paymentErrorMessage:u,isSubmittingOrder:!1,paymentMethod:r}),s?.modal?.open?.("nhnkcp_payment_error_modal");return}if(S(r)&&!x()){const u=M();s?.state?.setLocal?.({paymentErrorMessage:u,isSubmittingOrder:!1,paymentMethod:r}),s?.modal?.open?.("nhnkcp_payment_error_modal");return}const c=await s.api.get("/modules/sirsoft-ecommerce/payments/client-config/nhnkcp");if(!c.data){console.error("[Line truncated
<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>`),ne.close(),f=window.setTimeout(()=>{S(new Error("KCP SDK load timeout"))},15e3),y.__kcpReady=()=>{f!==void 0&&(clearTimeout(f),f=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 se(){return document.querySelector(".nhnkcp-easy-pay-btns")??null}function ce(){const e=se();e&&e.querySelectorAll("button").forEach(t=>{t.style.boxShadow="",t.style.outline=""})}function ft(e){const t=se();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(N(t)&&!P()){const a=M();n?.state?.setLocal?.({paymentErrorMessage:a,isSubmittingOrder:!1}),n?.modal?.open?.("nhnkcp_payment_error_modal"),ce();return}const r=typeof t=="string"&&t.startsWith("nhnkcp_");n?.state?.setLocal?.({paymentMethod:t}),r?ft(t):ce()}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 de={requestPayment:lt,setPaymentMethod:ht,copyToClipboard:_t},le="/api/modules/sirsoft-ecommerce/user/orders",R="sirsoft-pay_nhnkcp",ue={info:(...e)=>console.info(`[${R}]`,...e),warn:(...e)=>console.warn(`[${R}]`,...e),error:(...e)=>console.error(`[${R}]`,...e)};function wt(e){return typeof e=="string"?e:e instanceof URL?e.toString():typeof Request<"u"&&e instanceof Request?e.url:String(e)}function Pt(e,t){return t?.method?t.method.toUpperCase():typeof Request<"u"&&e instanceof Request?e.method.toUpperCase():"GET"}function kt(e,t){if(t!=="POST")return!1;const n=e.split("?")[0].split("#")[0];return n===le||n.endsWith(le)}function bt(e){try{return JSON.parse(e).payment_method}catch{return}}function Ct(e){return new Response(JSON.stringify({success:!1,message:e,error:e,errors:{payment_method:[e]}}),{status:422,statusText:"Unprocessable Content",headers:{"Content-Type":"application/json"}})}function Nt(){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(a,o){const i=wt(a),s=Pt(a,o);if(!kt(i,s))return n(a,o);let c;if(o?.body&&typeof o.body=="string"&&(c=bt(o.body)),N(c)&&!P()){const d=M();return ue.warn(d),Ct(d)}return n(a,o)},ue.info("order request interceptor installed (Apple Pay device guard)")}const H="sirsoft-pay_nhnkcp",pe="__kcpOcReceiptInjectorInstalled",me="kcp-oc-receipt-btn",xt=/^\/shop\/orders\/([^/]+)\/complete$/;function ye(){return localStorage.getItem("auth_token")}async function vt(e){const t=ye();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 L(e){const t=ye();if(!t)return null;try{const n=await fetch(`/api/plugins/${H}/user/orders/${e}/receipt`,{headers:{Authorization:`Bearer ${t}`,Accept:"application/json"}});return n.ok?await n.json():null}catch{return null}}function fe(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 Et(e){if(!e)return!1;const t=Array.from(document.querySelectorAll("div"));for(const n of t){const r=Array.from(n.children).filter(i=>i instanceof HTMLElement&&i.tagName==="SPAN");if(r.length<2)continue;const a=r[0].textContent?.trim();if(a!=="결제 방법"&&a!=="결제수단"&&a!=="결제 방식")continue;const o=r[r.length-1];return o.textContent?.trim()===e?(n.dataset.nhnkcpPaymentMethodRow="true",!0):(o.textContent=e,o.dataset.nhnkcpPaymentMethodPatched="true",n.dataset.nhnkcpPaymentMethodRow="true",!0)}return!1}async function At(e){if(document.getElementById(me))return;const t=await vt(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 L(e);Et(r?.payment_method_display_label);const a=n.parentElement,o=fe("영수증 조회",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 L(e);if(c.disabled=!1,c.textContent="영수증 조회",d){const l=window.KcpReceiptPopup;l&&new l({url:d.rLine truncated
</body></html>`),Q.close(),y=window.setTimeout(()=>{N(new Error("KCP SDK load timeout"))},15e3),f.__kcpReady=()=>{y!==void 0&&(clearTimeout(y),y=void 0)}})}const Xe={nhnkcp_payco:"PAYCO",nhnkcp_naverpay:"네이버페이",nhnkcp_naverpay_point:"네이버페이 포인트",nhnkcp_kakaopay:"카카오페이",nhnkcp_applepay:"Apple Pay"},Ze="0 0 0 2px #ffffff, 0 0 0 5px rgba(0,0,0,0.55)";function ne(){return document.querySelector(".nhnkcp-easy-pay-btns")??null}function oe(){const e=ne();e&&e.querySelectorAll("button").forEach(t=>{t.style.boxShadow="",t.style.outline=""})}function et(e){const t=ne();if(!t)return;const n=Xe[e];t.querySelectorAll("button").forEach(o=>{o.textContent?.trim()===n?(o.style.boxShadow=Ze,o.style.outline="none"):(o.style.boxShadow="",o.style.outline="")})}function tt(e){const t=e.params?.paymentMethod;if(!t)return;const n=window.G7Core;if(S(t)&&!x()){const r=M();n?.state?.setLocal?.({paymentErrorMessage:r,isSubmittingOrder:!1}),n?.modal?.open?.("nhnkcp_payment_error_modal"),oe();return}const o=typeof t=="string"&&t.startsWith("nhnkcp_");n?.state?.setLocal?.({paymentMethod:t}),o?et(t):oe()}function nt(e){const t=document.createElement("textarea");t.value=e,t.setAttribute("readonly","readonly"),t.style.position="fixed",t.style.left="-9999px",t.style.top="0",document.body.appendChild(t),t.select();try{document.execCommand("copy")}finally{t.remove()}}async function ot(e){const t=String(e.params?.text??"");if(t!==""){if(navigator.clipboard&&typeof navigator.clipboard.writeText=="function"){await navigator.clipboard.writeText(t);return}nt(t)}}const re={requestPayment:Je,setPaymentMethod:tt,copyToClipboard:ot},ae="/api/modules/sirsoft-ecommerce/user/orders",$="sirsoft-pay_nhnkcp",se={info:(...e)=>console.info(`[${$}]`,...e),warn:(...e)=>console.warn(`[${$}]`,...e),error:(...e)=>console.error(`[${$}]`,...e)};function rt(e){return typeof e=="string"?e:e instanceof URL?e.toString():typeof Request<"u"&&e instanceof Request?e.url:String(e)}function at(e,t){return t?.method?t.method.toUpperCase():typeof Request<"u"&&e instanceof Request?e.method.toUpperCase():"GET"}function st(e,t){if(t!=="POST")return!1;const n=e.split("?")[0].split("#")[0];return n===ae||n.endsWith(ae)}function it(e){try{return JSON.parse(e).payment_method}catch{return}}function ct(e){return new Response(JSON.stringify({success:!1,message:e,error:e,errors:{payment_method:[e]}}),{status:422,statusText:"Unprocessable Content",headers:{"Content-Type":"application/json"}})}function dt(){if(typeof window>"u"||typeof window.fetch!="function")return;const e="__sirsoftNhnkcpInterceptorInstalled",t=window;if(t[e])return;t[e]=!0;const n=window.fetch.bind(window);window.fetch=async function(r,a){const s=rt(r),i=at(r,a);if(!st(s,i))return n(r,a);let c;if(a?.body&&typeof a.body=="string"&&(c=it(a.body)),S(c)&&!x()){const d=M();return se.warn(d),ct(d)}return n(r,a)},se.info("order request interceptor installed (Apple Pay device guard)")}const L="sirsoft-pay_nhnkcp",ie="__kcpOcReceiptInjectorInstalled",ce="kcp-oc-receipt-btn",lt=/^\/shop\/orders\/([^/]+)\/complete$/;function de(){return localStorage.getItem("auth_token")}async function ut(e){const t=de();if(!t)return null;try{const n=await fetch(`/api/modules/sirsoft-ecommerce/user/orders/${e}`,{headers:{Authorization:`Bearer ${t}`,Accept:"application/json"}});return n.ok?(await n.json())?.data?.payment??null:null}catch{return null}}async function O(e){const t=de();if(!t)return null;try{const n=await fetch(`/api/plugins/${L}/user/orders/${e}/receipt`,{headers:{Authorization:`Bearer ${t}`,Accept:"application/json"}});return n.ok?await n.json():null}catch{return null}}function le(e,t,n){const o=document.createElement("button");return o.type="button",o.className=t,o.textContent=e,o.addEventListener("click",()=>n(o)),o}function pt(e){if(!e)return!1;const t=Array.from(document.querySelectorAll("div"));for(const n of t){const o=Array.from(n.children).filter(s=>s instanceof HTMLElement&&s.tagName==="SPAN");if(o.length<2)continue;const r=o[0].textContent?.trim();if(r!=="결제 방법"&&r!=="결제수단"&&r!=="결제 방식")continue;const a=o[o.length-1];return a.textContent?.trim()===e?(n.dataset.nhnkcpPaymentMethodRow="true",!0):(a.textContent=e,a.dataset.nhnkcpPaymentMethodPatched="true",n.dataset.nhnkcpPaymentMethodRow="true",!0)}return!1}async function mt(e){if(document.getElementById(ce))return;const t=await ut(e);if(!t||t.pg_provider!=="nhnkcp"||!t.transaction_id||!t.paid_at)return;const n=Array.from(document.querySelectorAll('button[type="button"]')).find(c=>c.className.includes("bg-blue-600"));if(!n?.parentElement)return;const o=await O(e);pt(o?.payment_method_display_label);const r=n.parentElement,a=le("영수증 조회",n.className.replace(/bg-blue-\d+/g,"bg-green-600").replace(/hover:bg-blue-\d+/g,"hover:bg-green-700"),async c=>{c.disabled=!0,c.textContent="로딩 중...";const d=await O(e);if(c.disabled=!1,c.textContent="영수증 조회",d){const l=window.KcpReceiptPopup;l&&new l({url:d.reLine truncated
//# sourceMappingURL=plugin.iife.js.map
@@ -1,226 +0,0 @@
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import {
resetCheckoutEasyPayInjectorForTests,
syncRenderedCheckoutEasyPayMethods,
} from '../checkoutEasyPayInjector';
function paymentButton(label: string, description: string): string {
return `
<button type="button">
<div class="flex items-center gap-3">
<i class="fas fa-wallet" role="img"></i>
<div>
<p>${label}</p>
<p>${description}</p>
</div>
</div>
</button>
`;
}
function renderPaymentButtons(): void {
document.body.innerHTML = `
${paymentButton('Naver Pay (KG Inicis)', 'Pay with Naver Pay')}
${paymentButton('Kakao Pay (KG Inicis)', 'Pay with Kakao Pay')}
${paymentButton('PAYCO (NHN KCP)', 'Pay with PAYCO')}
${paymentButton('Naver Pay (NHN KCP)', 'Pay with Naver Pay')}
${paymentButton('Naver Pay Point (NHN KCP)', 'Pay with Naver Pay points')}
${paymentButton('Kakao Pay (NHN KCP)', 'Pay with Kakao Pay')}
${paymentButton('Apple Pay (NHN KCP)', 'Pay with Apple Pay')}
${paymentButton('Credit Card', 'Pay securely with credit card')}
`;
}
function visibleButtonTexts(): string[] {
return Array.from(document.querySelectorAll<HTMLButtonElement>('button'))
.filter((button) => !button.hidden && button.style.display !== 'none')
.map((button) => plainText(button));
}
function plainText(element: Element | null | undefined): string {
return (element?.textContent ?? '').replace(/\u200B/g, '').replace(/\s+/g, ' ').trim();
}
function mockIosDevice(): void {
vi.spyOn(window.navigator, 'userAgent', 'get').mockReturnValue(
'Mozilla/5.0 (iPhone; CPU iPhone OS 17_0 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/17.0 Mobile/15E148 Safari/604.1',
);
vi.spyOn(window.navigator, 'platform', 'get').mockReturnValue('iPhone');
}
describe('checkoutEasyPayInjector', () => {
beforeEach(() => {
document.documentElement.lang = 'en';
window.history.pushState({}, '', '/shop/checkout');
renderPaymentButtons();
});
afterEach(() => {
resetCheckoutEasyPayInjectorForTests();
document.body.innerHTML = '';
vi.restoreAllMocks();
});
it('주문설정에서 렌더링된 NHN KCP 간편결제는 KCP 플러그인 설정과 무관하게 유지한다', async () => {
mockIosDevice();
await syncRenderedCheckoutEasyPayMethods();
expect(visibleButtonTexts()).toEqual([
'Naver Pay (KG Inicis) Pay with Naver Pay',
'Kakao Pay (KG Inicis) Pay with Kakao Pay',
'P PAYCO Pay with PAYCO (NHN KCP)',
'N Naver Pay (Card) Pay by Naver Pay credit card (NHN KCP)',
'NP Naver Pay (Point) Pay with Naver Pay Money/Points (NHN KCP)',
'K Kakao Pay Pay with Kakao Pay (NHN KCP)',
'A Apple Pay Pay with Apple Pay (NHN KCP)',
'Credit Card Pay securely with credit card',
]);
expect(document.querySelectorAll('[data-nhnkcp-easy-pay-hidden="true"]')).toHaveLength(0);
});
it('한국어 체크아웃에서 요청한 NHN KCP 간편결제 문구와 왼쪽 정렬을 적용한다', async () => {
mockIosDevice();
document.documentElement.lang = 'ko';
document.body.innerHTML = `
${paymentButton('PAYCO (NHN KCP)', 'PAYCO로 결제')}
${paymentButton('네이버페이 (NHN KCP)', '네이버페이로 결제')}
${paymentButton('네이버페이 포인트 (NHN KCP)', '네이버페이 포인트로 결제')}
${paymentButton('카카오페이 (NHN KCP)', '카카오페이로 결제')}
${paymentButton('Apple Pay (NHN KCP)', 'Apple Pay로 결제')}
`;
await syncRenderedCheckoutEasyPayMethods();
expect(visibleButtonTexts()).toEqual([
'P PAYCO PAYCO로 결제 (NHN KCP)',
'N 네이버페이 (카드) 네이버페이 신용카드로 결제 (NHN KCP)',
'NP 네이버페이 (포인트) 네이버페이 머니/포인트로 결제 (NHN KCP)',
'K 카카오페이 카카오페이로 결제 (NHN KCP)',
'A 애플페이 애플페이로 결제 (NHN KCP)',
]);
const paycoButton = document.querySelector<HTMLButtonElement>('[data-nhnkcp-easy-pay-method="nhnkcp_payco"]');
const appleButton = document.querySelector<HTMLButtonElement>('[data-nhnkcp-easy-pay-method="nhnkcp_applepay"]');
const paycoRow = paycoButton?.querySelector<HTMLElement>('.flex.items-center');
const appleRow = appleButton?.querySelector<HTMLElement>('.flex.items-center');
expect(paycoButton?.style.textAlign).toBe('left');
expect(appleButton?.style.textAlign).toBe('left');
expect(paycoRow?.style.justifyContent).toBe('flex-start');
expect(appleRow?.style.justifyContent).toBe('flex-start');
expect(paycoButton?.querySelectorAll('p')[0].style.textAlign).toBe('left');
expect(appleButton?.querySelectorAll('p')[0].style.textAlign).toBe('left');
});
it('KG 이니시스 브랜드 보정기가 다시 잡지 않도록 충돌되는 원문 매칭을 피한다', async () => {
await syncRenderedCheckoutEasyPayMethods();
const naverButton = document.querySelector<HTMLButtonElement>('[data-nhnkcp-easy-pay-method="nhnkcp_naverpay"]');
const kakaoButton = document.querySelector<HTMLButtonElement>('[data-nhnkcp-easy-pay-method="nhnkcp_kakaopay"]');
expect(naverButton?.textContent).not.toContain('Naver Pay');
expect(kakaoButton?.textContent).not.toContain('Kakao Pay');
expect((naverButton?.textContent ?? '').replace(/\u200B/g, '')).toContain('Naver Pay (Card)');
expect((kakaoButton?.textContent ?? '').replace(/\u200B/g, '')).toContain('Kakao Pay');
});
it('KG 브랜드 문구로 바뀐 버튼을 NHN KCP 문구로 복구한다', async () => {
await syncRenderedCheckoutEasyPayMethods();
const naverButton = document.querySelector<HTMLButtonElement>('[data-nhnkcp-easy-pay-method="nhnkcp_naverpay"]');
const kakaoButton = document.querySelector<HTMLButtonElement>('[data-nhnkcp-easy-pay-method="nhnkcp_kakaopay"]');
expect(naverButton).not.toBeNull();
expect(kakaoButton).not.toBeNull();
if (naverButton && kakaoButton) {
naverButton.dataset.kginicisBrandPaymentMethod = 'kginicis_naverpay';
naverButton.querySelectorAll('p')[0].textContent = 'Naver Pay';
naverButton.querySelectorAll('p')[1].textContent = 'Pay with Naver Pay (KG Inicis)';
kakaoButton.dataset.kginicisBrandPaymentMethod = 'kginicis_kakaopay';
kakaoButton.querySelectorAll('p')[0].textContent = 'Kakao Pay';
kakaoButton.querySelectorAll('p')[1].textContent = 'Pay with Kakao Pay (KG Inicis)';
const kgMark = document.createElement('span');
kgMark.dataset.kginicisBrandPaymentMark = 'true';
kgMark.textContent = 'KakaoPay';
kakaoButton.querySelector('.flex.items-center')?.prepend(kgMark);
}
await syncRenderedCheckoutEasyPayMethods();
expect(naverButton?.dataset.kginicisBrandPaymentMethod).toBeUndefined();
expect(plainText(naverButton)).toContain('Naver Pay (Card)');
expect(plainText(naverButton)).toContain('Pay by Naver Pay credit card (NHN KCP)');
expect(naverButton?.textContent).not.toContain('KG Inicis');
expect(kakaoButton?.dataset.kginicisBrandPaymentMethod).toBeUndefined();
expect(plainText(kakaoButton)).toContain('Kakao Pay');
expect(plainText(kakaoButton)).toContain('Pay with Kakao Pay (NHN KCP)');
expect(kakaoButton?.textContent).not.toContain('KG Inicis');
expect(kakaoButton?.querySelector('[data-kginicis-brand-payment-mark="true"]')).toBeNull();
});
it('iOS 모바일 기기에서는 Apple Pay도 주문설정에서 렌더링된 경우 숨기지 않는다', async () => {
mockIosDevice();
await syncRenderedCheckoutEasyPayMethods();
const appleButton = document.querySelector<HTMLButtonElement>('[data-nhnkcp-easy-pay-method="nhnkcp_applepay"]');
expect(appleButton).not.toBeNull();
expect(appleButton?.hidden).toBe(false);
expect(appleButton?.style.display).not.toBe('none');
expect(appleButton?.textContent).toContain('Pay with Apple Pay (NHN KCP)');
});
it('iOS 모바일 기기가 아니면 Apple Pay 버튼을 숨긴다', async () => {
await syncRenderedCheckoutEasyPayMethods();
const appleButton = document.querySelector<HTMLButtonElement>('[data-nhnkcp-easy-pay-method="nhnkcp_applepay"]');
expect(appleButton).not.toBeNull();
expect(appleButton?.hidden).toBe(true);
expect(appleButton?.disabled).toBe(true);
expect(appleButton?.style.display).toBe('none');
expect(visibleButtonTexts()).not.toContain('A Apple Pay Pay with Apple Pay (NHN KCP)');
});
it('KG 보정기가 먼저 NHN KCP Naver/Kakao 버튼을 KG 버튼으로 바꿔도 중복 버튼을 회수한다', async () => {
document.body.innerHTML = `
${paymentButton('NPay Naver Pay', 'Pay with Naver Pay (KG Inicis)')}
${paymentButton('KakaoPay Kakao Pay', 'Pay with Kakao Pay (KG Inicis)')}
${paymentButton('NPay Naver Pay', 'Pay with Naver Pay (KG Inicis)')}
${paymentButton('NPay Naver Pay', 'Pay with Naver Pay (KG Inicis)')}
${paymentButton('KakaoPay Kakao Pay', 'Pay with Kakao Pay (KG Inicis)')}
`;
const buttons = document.querySelectorAll<HTMLButtonElement>('button');
buttons[0].dataset.kginicisBrandPaymentMethod = 'kginicis_naverpay';
buttons[1].dataset.kginicisBrandPaymentMethod = 'kginicis_kakaopay';
buttons[2].dataset.kginicisBrandPaymentMethod = 'kginicis_naverpay';
buttons[3].dataset.kginicisBrandPaymentMethod = 'kginicis_naverpay';
buttons[4].dataset.kginicisBrandPaymentMethod = 'kginicis_kakaopay';
await syncRenderedCheckoutEasyPayMethods();
expect(buttons[0].hidden).toBe(false);
expect(buttons[1].hidden).toBe(false);
expect(buttons[2].dataset.nhnkcpEasyPayMethod).toBe('nhnkcp_naverpay');
expect(buttons[2].hidden).toBe(false);
expect(plainText(buttons[2])).toContain('Naver Pay (Card)');
expect(plainText(buttons[2])).toContain('Pay by Naver Pay credit card (NHN KCP)');
expect(buttons[2].textContent).not.toContain('KG Inicis');
expect(buttons[3].dataset.nhnkcpEasyPayMethod).toBe('nhnkcp_naverpay_point');
expect(buttons[3].hidden).toBe(false);
expect(plainText(buttons[3])).toContain('Naver Pay (Point)');
expect(plainText(buttons[3])).toContain('Pay with Naver Pay Money/Points (NHN KCP)');
expect(buttons[3].textContent).not.toContain('KG Inicis');
expect(buttons[4].dataset.nhnkcpEasyPayMethod).toBe('nhnkcp_kakaopay');
expect(buttons[4].hidden).toBe(false);
expect(plainText(buttons[4])).toContain('Kakao Pay');
expect(plainText(buttons[4])).toContain('Pay with Kakao Pay (NHN KCP)');
expect(buttons[4].textContent).not.toContain('KG Inicis');
});
});
@@ -1,429 +0,0 @@
import {
isIosMobileDevice,
isNhnKcpApplePayMethod,
} from './support/applePayDevice';
const PLUGIN_ID = 'sirsoft-pay_nhnkcp';
const FLAG = '__kcpCheckoutEasyPayInjectorInstalled';
const CHECKOUT_RE = /^\/shop\/checkout\/?$/;
const LISTENER_FLAG = '__kcpCheckoutEasyPaySyncListenerAttached';
const SYNC_RETRY_INTERVAL_MS = 200;
const SYNC_RETRY_ATTEMPTS = 120;
interface EasyPayCopy {
heading: string;
description: string;
title: string;
}
interface EasyPayDefinition {
id: string;
configKey: string;
labels: string[];
ko: EasyPayCopy;
en: EasyPayCopy;
markText: string;
markClassName: string;
}
const EASY_PAY_DEFINITIONS: EasyPayDefinition[] = [
{
id: 'nhnkcp_payco',
configKey: 'PAYCO',
labels: ['PAYCO (NHN KCP)', 'PAYCO NHN KCP 간편결제', 'PAYCO로 결제 (NHN KCP)', 'Pay with PAYCO (NHN KCP)'],
ko: {
heading: 'PAYCO',
description: 'PAYCO로 결제 (NHN KCP)',
title: 'PAYCO로 결제 (NHN KCP)',
},
en: {
heading: 'PAYCO',
description: 'Pay with PAYCO (NHN KCP)',
title: 'Pay with PAYCO (NHN KCP)',
},
markText: 'P',
markClassName: 'bg-red-500 text-white',
},
{
id: 'nhnkcp_naverpay',
configKey: 'NAVERPAY',
labels: ['네이버페이 (NHN KCP)', '네이버페이 신용카드로 결제 (NHN KCP)', 'NaverPay NHN KCP 간편결제', 'Naver Pay (NHN KCP)', 'NaverPay (NHN KCP)', 'Pay by Naver Pay credit card (NHN KCP)'],
ko: {
heading: '네이버페이 (카드)',
description: '네이버페이 신용카드로 결제 (NHN KCP)',
title: '네이버페이 신용카드로 결제 (NHN KCP)',
},
en: {
heading: 'Naver Pay (Card)',
description: 'Pay by Naver Pay credit card (NHN KCP)',
title: 'Pay by Naver Pay credit card (NHN KCP)',
},
markText: 'N',
markClassName: 'bg-green-500 text-white',
},
{
id: 'nhnkcp_naverpay_point',
configKey: 'NAVERPAY POINT',
labels: ['네이버페이 포인트 (NHN KCP)', '네이버페이 머니/포인트로 결제 (NHN KCP)', 'NaverPay 포인트 NHN KCP 포인트 간편결제', 'Naver Pay Point (NHN KCP)', 'NaverPay Point (NHN KCP)', 'Pay with Naver Pay Money/Points (NHN KCP)'],
ko: {
heading: '네이버페이 (포인트)',
description: '네이버페이 머니/포인트로 결제 (NHN KCP)',
title: '네이버페이 머니/포인트로 결제 (NHN KCP)',
},
en: {
heading: 'Naver Pay (Point)',
description: 'Pay with Naver Pay Money/Points (NHN KCP)',
title: 'Pay with Naver Pay Money/Points (NHN KCP)',
},
markText: 'NP',
markClassName: 'bg-green-600 text-white',
},
{
id: 'nhnkcp_kakaopay',
configKey: 'KAKAOPAY',
labels: ['카카오페이 (NHN KCP)', '카카오페이로 결제 (NHN KCP)', 'KakaoPay NHN KCP 간편결제', 'Kakao Pay (NHN KCP)', 'KakaoPay (NHN KCP)', 'Pay with Kakao Pay (NHN KCP)'],
ko: {
heading: '카카오페이',
description: '카카오페이로 결제 (NHN KCP)',
title: '카카오페이로 결제 (NHN KCP)',
},
en: {
heading: 'Kakao Pay',
description: 'Pay with Kakao Pay (NHN KCP)',
title: 'Pay with Kakao Pay (NHN KCP)',
},
markText: 'K',
markClassName: 'bg-yellow-400 text-gray-950',
},
{
id: 'nhnkcp_applepay',
configKey: 'APPLEPAY',
labels: ['애플페이 (NHN KCP)', '애플페이로 결제 (NHN KCP)', 'Apple Pay NHN KCP 간편결제', 'Apple Pay (NHN KCP)', 'Pay with Apple Pay (NHN KCP)'],
ko: {
heading: '애플페이',
description: '애플페이로 결제 (NHN KCP)',
title: '애플페이로 결제 (NHN KCP)',
},
en: {
heading: 'Apple Pay',
description: 'Pay with Apple Pay (NHN KCP)',
title: 'Pay with Apple Pay (NHN KCP)',
},
markText: 'A',
markClassName: 'bg-gray-900 text-white',
},
];
let observer: MutationObserver | null = null;
let retryTimer: number | null = null;
let syncQueued = false;
function windowRecord(): Record<string, unknown> {
return window as unknown as Record<string, unknown>;
}
function isCheckoutPage(): boolean {
return CHECKOUT_RE.test(window.location.pathname);
}
function normalizedText(value: string | null | undefined): string {
return (value ?? '').replace(/\s+/g, ' ').trim();
}
function isKoreanPage(): boolean {
const lang = document.documentElement.lang || navigator.language || '';
return lang.toLowerCase().startsWith('ko');
}
function copyFor(definition: EasyPayDefinition): EasyPayCopy {
return isKoreanPage() ? definition.ko : definition.en;
}
function displayText(value: string): string {
return value
.replaceAll('네이버페이', '네이\u200B버페이')
.replaceAll('카카오페이', '카카\u200B오페이')
.replaceAll('Naver Pay', 'Naver\u200B Pay')
.replaceAll('Kakao Pay', 'Kakao\u200B Pay');
}
function findDefinitionById(id: string | undefined): EasyPayDefinition | null {
return EASY_PAY_DEFINITIONS.find((definition) => definition.id === id) ?? null;
}
function findDefinitionForButton(button: HTMLButtonElement): EasyPayDefinition | null {
const markedDefinition = findDefinitionById(button.dataset.nhnkcpEasyPayMethod);
if (markedDefinition) return markedDefinition;
const text = normalizedText(button.textContent);
return EASY_PAY_DEFINITIONS.find((definition) => (
definition.labels.some((label) => text.includes(label))
)) ?? null;
}
function findPaymentRow(button: HTMLButtonElement): HTMLElement | null {
return button.querySelector<HTMLElement>('.flex.items-center.gap-2, .flex.items-center.gap-3')
?? button.querySelector<HTMLElement>('.flex.items-center');
}
function alignPaymentTextLeft(button: HTMLButtonElement, heading?: HTMLElement, description?: HTMLElement): void {
button.style.textAlign = 'left';
const row = findPaymentRow(button);
if (row) {
row.style.justifyContent = 'flex-start';
row.style.textAlign = 'left';
row.style.width = '100%';
}
const textContainer = heading?.parentElement ?? description?.parentElement;
if (textContainer instanceof HTMLElement) {
textContainer.style.textAlign = 'left';
textContainer.style.minWidth = '0';
}
}
function createMark(definition: EasyPayDefinition): HTMLSpanElement {
const mark = document.createElement('span');
mark.dataset.nhnkcpEasyPayMark = 'true';
mark.dataset.nhnkcpEasyPayMethod = definition.id;
mark.setAttribute('aria-hidden', 'true');
mark.className = `inline-flex items-center justify-center rounded-lg text-xs font-bold ${definition.markClassName}`;
mark.style.width = '32px';
mark.style.height = '32px';
mark.style.flex = '0 0 32px';
mark.textContent = definition.markText;
return mark;
}
function removeKginicisBrandArtifacts(button: HTMLButtonElement): void {
delete button.dataset.kginicisBrandPaymentButton;
delete button.dataset.kginicisBrandPaymentMethod;
delete button.dataset.kginicisNaverpayBrandButton;
button.querySelectorAll<HTMLElement>('[data-kginicis-brand-payment-mark="true"], [data-kginicis-naverpay-mark="true"]').forEach((element) => {
element.remove();
});
button.querySelectorAll<HTMLElement>('[data-kginicis-brand-payment-heading], [data-kginicis-brand-payment-description], [data-kginicis-naverpay-heading], [data-kginicis-naverpay-description]').forEach((element) => {
delete element.dataset.kginicisBrandPaymentHeading;
delete element.dataset.kginicisBrandPaymentDescription;
delete element.dataset.kginicisNaverpayHeading;
delete element.dataset.kginicisNaverpayDescription;
});
}
function findPaymentIcon(button: HTMLButtonElement): Element | null {
return button.querySelector('[data-kginicis-brand-payment-mark="true"], [data-kginicis-naverpay-mark="true"]')
?? button.querySelector('[data-nhnkcp-easy-pay-mark="true"]')
?? button.querySelector('svg')
?? button.querySelector('i[class*="fa-"], i[role="img"], i');
}
function ensureMark(button: HTMLButtonElement, definition: EasyPayDefinition): void {
const existingMark = button.querySelector<HTMLElement>('[data-nhnkcp-easy-pay-mark="true"]');
if (existingMark) {
existingMark.dataset.nhnkcpEasyPayMethod = definition.id;
existingMark.className = `inline-flex items-center justify-center rounded-lg text-xs font-bold ${definition.markClassName}`;
existingMark.textContent = definition.markText;
return;
}
const mark = createMark(definition);
const icon = findPaymentIcon(button);
if (icon && icon.parentElement) {
icon.replaceWith(mark);
return;
}
const row = findPaymentRow(button);
row?.prepend(mark);
}
function updatePaymentText(button: HTMLButtonElement, definition: EasyPayDefinition): void {
const paragraphs = Array.from(button.querySelectorAll<HTMLParagraphElement>('p'));
const copy = copyFor(definition);
const headingText = displayText(copy.heading);
const descriptionText = displayText(copy.description);
const heading = paragraphs[0];
const description = paragraphs[1];
if (heading && heading.textContent !== headingText) {
heading.textContent = headingText;
}
if (heading) {
heading.setAttribute('aria-label', copy.heading);
heading.style.textAlign = 'left';
heading.style.whiteSpace = 'normal';
heading.style.wordBreak = 'keep-all';
heading.style.overflowWrap = 'anywhere';
}
if (description && description.textContent !== descriptionText) {
description.textContent = descriptionText;
}
if (description) {
description.style.textAlign = 'left';
description.style.fontSize = '12px';
description.style.lineHeight = '1rem';
description.style.whiteSpace = 'normal';
description.style.wordBreak = 'keep-all';
description.style.overflowWrap = 'anywhere';
}
alignPaymentTextLeft(button, heading, description);
button.title = copy.title;
}
function showButton(button: HTMLButtonElement, definition: EasyPayDefinition): void {
if (isNhnKcpApplePayMethod(definition.id) && !isIosMobileDevice()) {
button.hidden = true;
button.disabled = true;
button.style.display = 'none';
button.setAttribute('aria-hidden', 'true');
button.dataset.nhnkcpEasyPayMethod = definition.id;
button.dataset.nhnkcpEasyPayHidden = 'true';
delete button.dataset.nhnkcpEasyPayVisible;
return;
}
if (button.hidden) button.hidden = false;
if (button.disabled) button.disabled = false;
if (button.style.display === 'none') button.style.removeProperty('display');
button.removeAttribute('aria-hidden');
button.dataset.nhnkcpEasyPayMethod = definition.id;
button.dataset.nhnkcpEasyPayVisible = 'true';
delete button.dataset.nhnkcpEasyPayHidden;
removeKginicisBrandArtifacts(button);
ensureMark(button, definition);
updatePaymentText(button, definition);
}
function reconcileKginicisPatchedDuplicates(root: ParentNode): boolean {
const duplicateGroups: Record<string, string[]> = {
kginicis_naverpay: ['nhnkcp_naverpay', 'nhnkcp_naverpay_point'],
kginicis_kakaopay: ['nhnkcp_kakaopay'],
};
let changed = false;
Object.entries(duplicateGroups).forEach(([kginicisMethod, nhnkcpMethods]) => {
const buttons = Array.from(root.querySelectorAll<HTMLButtonElement>(`button[data-kginicis-brand-payment-method="${kginicisMethod}"]`))
.filter((button) => !button.dataset.nhnkcpEasyPayMethod);
buttons.slice(1).forEach((button, index) => {
const definition = findDefinitionById(nhnkcpMethods[index]);
if (!definition) return;
showButton(button, definition);
changed = true;
});
});
return changed;
}
export async function syncRenderedCheckoutEasyPayMethods(
root: ParentNode = document,
): Promise<boolean> {
if (typeof window === 'undefined' || typeof document === 'undefined') return false;
if (!isCheckoutPage()) return false;
let changed = false;
root.querySelectorAll<HTMLButtonElement>('button').forEach((button) => {
const definition = findDefinitionForButton(button);
if (!definition) return;
showButton(button, definition);
changed = true;
});
if (reconcileKginicisPatchedDuplicates(root)) {
changed = true;
}
return changed;
}
function queueSync(): void {
if (syncQueued) return;
syncQueued = true;
window.setTimeout(() => {
syncQueued = false;
void syncRenderedCheckoutEasyPayMethods();
}, 0);
}
function stopRetries(): void {
if (retryTimer === null) return;
window.clearInterval(retryTimer);
retryTimer = null;
}
function startSync(): void {
if (!isCheckoutPage()) return;
stopRetries();
void syncRenderedCheckoutEasyPayMethods();
let attempts = 0;
retryTimer = window.setInterval(() => {
attempts += 1;
void syncRenderedCheckoutEasyPayMethods();
if (attempts >= SYNC_RETRY_ATTEMPTS) {
stopRetries();
}
}, SYNC_RETRY_INTERVAL_MS);
const body = document.body as HTMLElement & Record<string, unknown>;
if (body[LISTENER_FLAG]) return;
body[LISTENER_FLAG] = true;
observer = new MutationObserver(() => queueSync());
observer.observe(document.body, { childList: true, subtree: true, characterData: true });
}
function onRouteChange(): void {
if (isCheckoutPage()) startSync();
}
export function installCheckoutEasyPayInjector(): void {
if (typeof window === 'undefined' || typeof document === 'undefined') return;
const w = windowRecord();
if (w[FLAG]) return;
w[FLAG] = true;
console.info(`[${PLUGIN_ID}] checkout easy pay method sync installed`);
if (document.readyState === 'loading') {
document.addEventListener('DOMContentLoaded', () => startSync());
} else {
startSync();
}
const origPush = history.pushState.bind(history);
history.pushState = (...args: Parameters<typeof history.pushState>) => {
origPush(...args);
window.setTimeout(() => onRouteChange(), 200);
};
window.addEventListener('popstate', () => window.setTimeout(() => onRouteChange(), 200));
}
export function resetCheckoutEasyPayInjectorForTests(): void {
observer?.disconnect();
observer = null;
stopRetries();
syncQueued = false;
delete windowRecord()[FLAG];
if (document.body) {
delete ((document.body as HTMLElement & Record<string, unknown>)[LISTENER_FLAG]);
}
}
@@ -2,7 +2,6 @@ import { handlerMap } from './handlers';
import { installOrderResponseInterceptor } from './orderResponseInterceptor';
import { installOrderCompleteReceiptInjector } from './orderCompleteReceiptInjector';
import { installMypageOrderShowInjector } from './mypageOrderShowInjector';
import { installCheckoutEasyPayInjector } from './checkoutEasyPayInjector';
import { installAdminApplePayNoticeInjector } from './adminApplePayNoticeInjector';
import { installAdminPaymentMethodBrandInjector } from './adminPaymentMethodBrandInjector';
import { installAdminOrderPaymentDisplayInjector } from './adminOrderPaymentDisplayInjector';
@@ -98,7 +97,6 @@ function initPlugin(): void {
installOrderResponseInterceptor();
installOrderCompleteReceiptInjector();
installMypageOrderShowInjector();
installCheckoutEasyPayInjector();
installAdminApplePayNoticeInjector();
installAdminPaymentMethodBrandInjector();
installAdminOrderPaymentDisplayInjector();
@@ -26,30 +26,38 @@ class RegisterEasyPayMethodsListener implements HookListenerInterface
'name_key' => 'sirsoft-pay_nhnkcp::payment_methods.payco.name',
'description_key' => 'sirsoft-pay_nhnkcp::payment_methods.payco.description',
'icon' => 'wallet',
'brand_mark' => ['text' => 'P', 'class' => 'bg-red-500 text-white'],
],
[
'id' => 'nhnkcp_naverpay',
'name_key' => 'sirsoft-pay_nhnkcp::payment_methods.naverpay.name',
'description_key' => 'sirsoft-pay_nhnkcp::payment_methods.naverpay.description',
'icon' => 'wallet',
'brand_mark' => ['text' => 'N', 'class' => 'bg-green-500 text-white'],
],
[
'id' => 'nhnkcp_naverpay_point',
'name_key' => 'sirsoft-pay_nhnkcp::payment_methods.naverpay_point.name',
'description_key' => 'sirsoft-pay_nhnkcp::payment_methods.naverpay_point.description',
'icon' => 'wallet-cards',
'brand_mark' => ['text' => 'NP', 'class' => 'bg-green-600 text-white'],
],
[
'id' => 'nhnkcp_kakaopay',
'name_key' => 'sirsoft-pay_nhnkcp::payment_methods.kakaopay.name',
'description_key' => 'sirsoft-pay_nhnkcp::payment_methods.kakaopay.description',
'icon' => 'message-circle',
'brand_mark' => ['text' => 'K', 'class' => 'bg-yellow-400 text-gray-950'],
],
[
'id' => 'nhnkcp_applepay',
'name_key' => 'sirsoft-pay_nhnkcp::payment_methods.applepay.name',
'description_key' => 'sirsoft-pay_nhnkcp::payment_methods.applepay.description',
'icon' => 'smartphone',
'brand_mark' => ['text' => 'A', 'class' => 'bg-gray-900 text-white'],
// 애플페이는 iOS 기기에서만 결제 가능 — 비-iOS 기기에서는 체크아웃 레이아웃이
// 이 수단을 렌더하지 않는다(과거 checkoutEasyPayInjector 의 iOS 게이팅 이관).
'requires_ios' => true,
],
];
@@ -84,6 +92,8 @@ class RegisterEasyPayMethodsListener implements HookListenerInterface
nameKey: $method['name_key'],
descriptionKey: $method['description_key'],
icon: $method['icon'],
brandMark: $method['brand_mark'] ?? null,
requiresIos: $method['requires_ios'] ?? false,
),
self::EASY_PAY_METHODS
);
@@ -135,9 +145,19 @@ class RegisterEasyPayMethodsListener implements HookListenerInterface
return $insertAfter;
}
private function buildEntry(string $id, string $nameKey, string $descriptionKey, string $icon): array
{
return [
/**
* @param array{text: string, class: string}|null $brandMark 배지 브랜드 마크(텍스트+색상 클래스)
* @param bool $requiresIos iOS 기기에서만 노출되는 수단 여부(애플페이)
*/
private function buildEntry(
string $id,
string $nameKey,
string $descriptionKey,
string $icon,
?array $brandMark = null,
bool $requiresIos = false,
): array {
$entry = [
'id' => $id,
'name' => [
'ko' => __($nameKey, [], 'ko'),
@@ -163,5 +183,18 @@ class RegisterEasyPayMethodsListener implements HookListenerInterface
'mileage_deduction_timing' => 'payment_complete',
],
];
// 브랜드 마크(색 배지) — 레이아웃 BrandMark 컴포넌트가 text+class 로 렌더한다.
// 과거 checkoutEasyPayInjector 가 DOM 후처리로 주입하던 markText/markClassName 이관.
if ($brandMark !== null) {
$entry['brand_mark'] = $brandMark;
}
// iOS 전용 수단(애플페이)은 비-iOS 기기에서 체크아웃 레이아웃이 렌더하지 않는다.
if ($requiresIos) {
$entry['requires_ios'] = true;
}
return $entry;
}
}
@@ -114,4 +114,73 @@ class RegisterEasyPayMethodsListenerTest extends TestCase
$applepay['description']['ko'] ?? null,
);
}
/**
* @scenario mark_form=badge, requires_ios=false, device=ios
*
* @effects brand_mark_flows_to_cached, badge_renders_text_and_color
*/
public function test_easy_pay_methods_carry_badge_brand_mark(): void
{
// 브랜드 마크(색 배지)를 카탈로그로 편입 — 과거 checkoutEasyPayInjector 가
// DOM 후처리로 주입하던 markText/markClassName 을 등록 데이터로 이관.
$listener = new RegisterEasyPayMethodsListener;
$methods = $listener->injectEasyPayMethods([
['id' => 'phone'],
['id' => 'point'],
]);
$naverpay = collect($methods)->firstWhere('id', 'nhnkcp_naverpay');
$kakaopay = collect($methods)->firstWhere('id', 'nhnkcp_kakaopay');
$this->assertSame(['text' => 'N', 'class' => 'bg-green-500 text-white'], $naverpay['brand_mark'] ?? null);
$this->assertSame(['text' => 'K', 'class' => 'bg-yellow-400 text-gray-950'], $kakaopay['brand_mark'] ?? null);
}
/**
* @scenario mark_form=badge, requires_ios=true, device=ipados_desktop_ua
*
* @effects requires_ios_flag_carried
*/
public function test_only_apple_pay_requires_ios(): void
{
// 애플페이만 iOS 전용 노출 플래그를 가진다(비-iOS 기기에서 체크아웃 레이아웃이 숨김).
$listener = new RegisterEasyPayMethodsListener;
$methods = $listener->injectEasyPayMethods([
['id' => 'phone'],
['id' => 'point'],
]);
$applepay = collect($methods)->firstWhere('id', 'nhnkcp_applepay');
$naverpay = collect($methods)->firstWhere('id', 'nhnkcp_naverpay');
$this->assertTrue($applepay['requires_ios'] ?? false);
$this->assertArrayNotHasKey('requires_ios', $naverpay);
}
/**
* 브랜드 마크를 카탈로그로 편입하면서 체크아웃 DOM 인젝터를 제거했다.
* 인젝터 파일 부재 + index.ts 에 install 호출 부재를 구조로 확인한다.
* 결제 시점 방어(applePayDevice) 는 잔존한다.
*
* @scenario mark_form=badge, requires_ios=true, device=ios
*
* @effects injectors_removed, shared_helpers_preserved
*/
public function test_checkout_easy_pay_injector_removed_but_shared_helpers_preserved(): void
{
$jsDir = base_path('plugins/_bundled/sirsoft-pay_nhnkcp/resources/js');
// 브랜드 인젝터 제거됨.
$this->assertFileDoesNotExist($jsDir.'/checkoutEasyPayInjector.ts');
// index.ts 에 install 호출 부재.
$indexTs = file_get_contents($jsDir.'/index.ts');
$this->assertStringNotContainsString('installCheckoutEasyPayInjector', $indexTs);
// 결제 시점 방어 헬퍼(applePayDevice)는 잔존 — requestPayment/orderResponseInterceptor 가 사용.
$this->assertFileExists($jsDir.'/support/applePayDevice.ts');
}
}
@@ -18,6 +18,8 @@
- 간편결제가 정식 결제수단으로 취급되어 주문 내역에 실제로 선택한 결제수단(예: 네이버페이)이 그대로 기록됩니다.
- 쇼핑몰 환경설정 > 주문설정의 결제수단 목록에서 간편결제가 "PG 고정 · 나이스페이먼츠"로 표시됩니다. 간편결제는 나이스페이먼츠 전용이므로 다른 결제대행사로 바꿀 수 없습니다.
- 결제창을 띄우기 위해 브라우저 요청을 가로채 결제수단을 바꿔치기하던 내부 처리를 제거했습니다. 결제 진행 방식이 표준화됩니다.
- 주문서의 간편결제 버튼에 표시되는 브랜드 마크(네이버페이·카카오페이·삼성페이·11pay·SSG페이·L.pay 등의 색상 배지)를 화면이 그려진 뒤 덧입히던 방식에서 결제수단 정보로 처음부터 표시하는 방식으로 바꿨습니다. 여러 결제사가 함께 켜져 있을 때 표시가 안정적입니다.
- 애플페이 간편결제 버튼이 iOS 기기(iPhone·iPad)에서만 주문서에 표시되도록 했습니다. 애플페이는 iOS에서만 결제할 수 있으므로 다른 기기에서는 버튼을 감춰 혼선을 줄입니다.
### Security
@@ -1,2 +1,2 @@
(function(){"use strict";function Ne(e){return/^https?:\/\//i.test(e)||e.startsWith("/api/")?e:e.startsWith("/plugins/")?`/api${e}`:e.startsWith("plugins/")?`/api/${e}`:e}function ke(e){return e.trim().slice(0,160)}async function Se(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:ke(t)||"nicepay-window-closed"};try{const a=window.G7Core?.api;if(typeof a?.post=="function"){await a.post(e.closeReportUrl,n);return}await fetch(Ne(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)}}function Ce(e){return new Promise((t,n)=>{if(document.querySelector(`script[src="${e}"]`)){t();return}const a=document.createElement("script");a.src=e,a.onload=()=>t(),a.onerror=()=>n(new Error(`Failed to load script: ${e}`)),document.head.appendChild(a)})}function xe(e,t){const n=document.createElement("form");n.id="nicepayForm",n.method="post",n.action=e,n.acceptCharset="utf-8";for(const[a,o]of Object.entries(t)){const r=document.createElement("input");r.type="hidden",r.name=a,r.value=o,n.appendChild(r)}return document.body.appendChild(n),n}const Ee="/plugins/sirsoft-pay_nicepayments/payment/callback",Ae="https://web.nicepay.co.kr/v3/v3Payment.jsp";function ve(){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 Le(e,t){const{pgPaymentData:n,paymentMethod:a}=e.params??{},o=window.__templateApp?.globalState?._local,r=a??n?.payment_method??o?.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=ve();if(!d&&(await Ce(l.sdk_url),typeof window.goPay!="function")){i?.toast?.error?.("나이스페이먼츠 SDK를 불러올 수 없습니다. 잠시 후 다시 시도해주세요."),i?.state?.setLocal?.({isSubmittingOrder:!1,paymentMethod:r});return}const b=window.location.origin+l.sign_data_url,y=typeof localStorage<"u"?localStorage.getItem("auth_token"):null,me={"Content-Type":"application/json","X-Requested-With":"XMLHttpRequest",Accept:"application/json"};y&&(me.Authorization=`Bearer ${y}`);const fe=await fetch(b,{method:"POST",credentials:"include",headers:me,body:JSON.stringify({amt:n.amount,moid:n.order_number,buyer_email:n.customer_email??"",buyer_phone:n.customer_phone??""})});if(!fe.ok)throw new Error("SignData 생성에 실패했습니다.");const R=await fe.json(),he=window.location.origin+Ee,D=typeof r=="string"&&r.startsWith("nicepay_"),ge=D?"CARD":{card:"CARD",vbank:"VBANK",bank:"BANK",phone:"CELLPHONE"}[r??"card"]??"CARD",c={PayMethod:ge,GoodsName:n.order_name,Amt:String(n.amount),MID:R.mid,Moid:n.order_number,BuyerName:n.customer_name??"",BuyerEmail:n.customer_email??"",BuyerTel:n.customer_phone??"",ReturnURL:he,EdiDate:R.ediDate,SignData:R.signData,CharSet:"utf-8",GoodsCl:"1",DirectShowOpt:"",DirectEasyPay:"",NicepayReserved:"",EasyPayMethod:"",MallReserved:"",MallReserved1:""};ge==="CELLPHONE"&&(c.GoodsCl=n.goods_cl??"1");const Jt=l.useEscrow&&!D;if(c.TransType=Jt?"1":"0",D)switch(c.DirectShowOpt="CARD",c.MallReserved=`nicepay_easy_pay_method=${encodeURIComponent(r)}`,c.MallReserved1=r,r){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 p=(await i.api.get(`/modules/sirsoft-ecommerce/user/orders/${n.order_number}`))?.data;if(p){const N=Number(p.total_tax_amount??0),h=Number(p.total_vat_amount??0),be=Number(p.total_tax_free_amount??0);(N>0||h>0||be>0)&&(c.TaxAmt=String(N),c.VatAmt=String(h),c.TaxFreeAmt=String(be))}}catch{}const u=xe(he,c);if(d){u.action=Ae,u.acceptCharset="euc-kr";const f=u.querySelector('input[name="CharSet"]');f&&(f.value="euc-kr"),u.submit();return}window.nicepaySubmit=()=>{u.submit()};let Pe=!1;const Xt=new Set(document.body.children),we=(f,p)=>{if(Pe)return;Pe=!0;const N=[f,p].filter(Boolean).join(": ")||"nicepay-window-closed";Se({closeReportUrl:l.close_report_url,oid:n.order_number,price:Number(n.aLine truncated
(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)}}function pe(e){return new Promise((t,n)=>{if(document.querySelector(`script[src="${e}"]`)){t();return}const a=document.createElement("script");a.src=e,a.onload=()=>t(),a.onerror=()=>n(new Error(`Failed to load script: ${e}`)),document.head.appendChild(a)})}function me(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 ye="/plugins/sirsoft-pay_nicepayments/payment/callback",fe="https://web.nicepay.co.kr/v3/v3Payment.jsp";function he(){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 be(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=he();if(!d&&(await pe(l.sdk_url),typeof window.goPay!="function")){i?.toast?.error?.("나이스페이먼츠 SDK를 불러올 수 없습니다. 잠시 후 다시 시도해주세요."),i?.state?.setLocal?.({isSubmittingOrder:!1,paymentMethod:o});return}const w=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(w,{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+ye,L=typeof o=="string"&&o.startsWith("nicepay_"),oe=L?"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 ft=l.useEscrow&&!L;if(c.TransType=ft?"1":"0",L)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-ecommerce/user/orders/${n.order_number}`))?.data;if(m){const P=Number(m.total_tax_amount??0),h=Number(m.total_vat_amount??0),ce=Number(m.total_tax_free_amount??0);(P>0||h>0||ce>0)&&(c.TaxAmt=String(P),c.VatAmt=String(h),c.TaxFreeAmt=String(ce))}}catch{}const p=me(ae,c);if(d){p.action=fe,p.acceptCharset="euc-kr";const f=p.querySelector('input[name="CharSet"]');f&&(f.value="euc-kr"),p.submit();return}window.nicepaySubmit=()=>{p.submit()};let re=!1;const ht=new Set(document.body.children),ie=(f,m)=>{if(re)return;re=!0;const P=[f,m].filter(Boolean).join(": ")||"nicepay-window-closed";ue({closeReportUrl:l.close_report_url,oid:n.order_number,price:Number(n.aLine truncated
//# sourceMappingURL=plugin.iife.js.map
@@ -1,83 +0,0 @@
import { afterEach, beforeEach, describe, expect, it } from 'vitest';
import {
resetCheckoutEasyPayInjectorForTests,
syncRenderedCheckoutEasyPayMethods,
} from '../checkoutEasyPayInjector';
function paymentButton(label: string, description: string): string {
return `
<button type="button">
<div class="flex items-center gap-3">
<i class="fas fa-wallet" role="img"></i>
<div>
<p>${label}</p>
<p>${description}</p>
</div>
</div>
</button>
`;
}
function plainText(element: Element | null | undefined): string {
return (element?.textContent ?? '').replace(/\u200B/g, '').replace(/\s+/g, ' ').trim();
}
describe('checkoutEasyPayInjector', () => {
beforeEach(() => {
document.documentElement.lang = 'ko';
window.history.pushState({}, '', '/shop/checkout');
document.body.innerHTML = `
${paymentButton('네이\u200B버페이 (나이스페이먼츠)', '네이\u200B버페이로 결제 (나이스페이먼츠)')}
${paymentButton('카카\u200B오페이 (나이스페이먼츠)', '카카\u200B오페이로 결제 (나이스페이먼츠)')}
${paymentButton('삼성\u200B페이 (나이스페이먼츠)', '삼성\u200B페이로 결제 (나이스페이먼츠)')}
${paymentButton('애플페이 (나이스페이먼츠)', '애플페이로 결제 (나이스페이먼츠)')}
${paymentButton('PAYCO (나이스페이먼츠)', 'PAYCO로 결제 (나이스페이먼츠)')}
${paymentButton('11pay (나이스페이먼츠)', '11pay로 결제 (나이스페이먼츠)')}
${paymentButton('SSG페이 (나이스페이먼츠)', 'SSG페이로 결제 (나이스페이먼츠)')}
${paymentButton('L.\u200Bpay (나이스페이먼츠)', 'L.\u200Bpay로 결제 (나이스페이먼츠)')}
`;
});
afterEach(() => {
resetCheckoutEasyPayInjectorForTests();
document.body.innerHTML = '';
});
it('나이스페이먼츠 간편결제를 NHN KCP처럼 아이콘과 텍스트가 있는 버튼으로 보정한다', async () => {
await syncRenderedCheckoutEasyPayMethods();
const buttons = Array.from(document.querySelectorAll<HTMLButtonElement>('button[data-nicepay-easy-pay-method]'));
expect(buttons.map((button) => button.dataset.nicepayEasyPayMethod)).toEqual([
'nicepay_naverpay',
'nicepay_kakaopay',
'nicepay_samsungpay',
'nicepay_applepay',
'nicepay_payco',
'nicepay_skpay',
'nicepay_ssgpay',
'nicepay_lpay',
]);
expect(buttons.map((button) => plainText(button))).toEqual([
'N 네이버페이 (나이스페이먼츠) 네이버페이로 결제 (나이스페이먼츠)',
'K 카카오페이 (나이스페이먼츠) 카카오페이로 결제 (나이스페이먼츠)',
'S 삼성페이 (나이스페이먼츠) 삼성페이로 결제 (나이스페이먼츠)',
'A 애플페이 (나이스페이먼츠) 애플페이로 결제 (나이스페이먼츠)',
'P PAYCO (나이스페이먼츠) PAYCO로 결제 (나이스페이먼츠)',
'11 11pay (나이스페이먼츠) 11pay로 결제 (나이스페이먼츠)',
'SSG SSG페이 (나이스페이먼츠) SSG페이로 결제 (나이스페이먼츠)',
'L L.pay (나이스페이먼츠) L.pay로 결제 (나이스페이먼츠)',
]);
for (const button of buttons) {
const row = button.querySelector<HTMLElement>('.flex.items-center');
expect(button.querySelector('[data-nicepay-easy-pay-mark="true"]')).not.toBeNull();
expect(button.style.textAlign).toBe('left');
expect(row?.style.justifyContent).toBe('flex-start');
expect(button.dataset.kginicisBrandPaymentMethod).toBeUndefined();
expect(button.dataset.nhnkcpEasyPayMethod).toBeUndefined();
}
});
});
@@ -1,480 +0,0 @@
const PLUGIN_ID = 'sirsoft-pay_nicepayments';
const FLAG = '__nicepayCheckoutEasyPayInjectorInstalled';
const CHECKOUT_RE = /^\/shop\/checkout\/?$/;
const LISTENER_FLAG = '__nicepayCheckoutEasyPaySyncListenerAttached';
const SYNC_RETRY_INTERVAL_MS = 200;
const SYNC_RETRY_ATTEMPTS = 120;
const LEGACY_CONTAINER_ID = 'nicepay_checkout_payment_section';
interface EasyPayCopy {
heading: string;
description: string;
title: string;
}
interface EasyPayDefinition {
id: string;
labels: string[];
ko: EasyPayCopy;
en: EasyPayCopy;
markText: string;
markClassName: string;
}
const EASY_PAY_DEFINITIONS: EasyPayDefinition[] = [
{
id: 'nicepay_naverpay',
labels: [
'네이버페이 (나이스페이먼츠)',
'네이버페이로 결제 (나이스페이먼츠)',
'Naver Pay (NicePayments)',
'Pay with Naver Pay (NicePayments)',
],
ko: {
heading: '네이버페이 (나이스페이먼츠)',
description: '네이버페이로 결제 (나이스페이먼츠)',
title: '네이버페이로 결제 (나이스페이먼츠)',
},
en: {
heading: 'Naver Pay (NicePayments)',
description: 'Pay with Naver Pay (NicePayments)',
title: 'Pay with Naver Pay (NicePayments)',
},
markText: 'N',
markClassName: 'bg-green-500 text-white',
},
{
id: 'nicepay_kakaopay',
labels: [
'카카오페이 (나이스페이먼츠)',
'카카오페이로 결제 (나이스페이먼츠)',
'Kakao Pay (NicePayments)',
'Pay with Kakao Pay (NicePayments)',
],
ko: {
heading: '카카오페이 (나이스페이먼츠)',
description: '카카오페이로 결제 (나이스페이먼츠)',
title: '카카오페이로 결제 (나이스페이먼츠)',
},
en: {
heading: 'Kakao Pay (NicePayments)',
description: 'Pay with Kakao Pay (NicePayments)',
title: 'Pay with Kakao Pay (NicePayments)',
},
markText: 'K',
markClassName: 'bg-yellow-400 text-gray-950',
},
{
id: 'nicepay_samsungpay',
labels: [
'삼성페이 (나이스페이먼츠)',
'삼성페이로 결제 (나이스페이먼츠)',
'Samsung Pay (NicePayments)',
'Pay with Samsung Pay (NicePayments)',
],
ko: {
heading: '삼성페이 (나이스페이먼츠)',
description: '삼성페이로 결제 (나이스페이먼츠)',
title: '삼성페이로 결제 (나이스페이먼츠)',
},
en: {
heading: 'Samsung Pay (NicePayments)',
description: 'Pay with Samsung Pay (NicePayments)',
title: 'Pay with Samsung Pay (NicePayments)',
},
markText: 'S',
markClassName: 'bg-blue-600 text-white',
},
{
id: 'nicepay_applepay',
labels: [
'애플페이 (나이스페이먼츠)',
'애플페이로 결제 (나이스페이먼츠)',
'Apple Pay (NicePayments)',
'Pay with Apple Pay (NicePayments)',
],
ko: {
heading: '애플페이 (나이스페이먼츠)',
description: '애플페이로 결제 (나이스페이먼츠)',
title: '애플페이로 결제 (나이스페이먼츠)',
},
en: {
heading: 'Apple Pay (NicePayments)',
description: 'Pay with Apple Pay (NicePayments)',
title: 'Pay with Apple Pay (NicePayments)',
},
markText: 'A',
markClassName: 'bg-gray-900 text-white',
},
{
id: 'nicepay_payco',
labels: [
'PAYCO (나이스페이먼츠)',
'PAYCO로 결제 (나이스페이먼츠)',
'PAYCO (NicePayments)',
'Pay with PAYCO (NicePayments)',
],
ko: {
heading: 'PAYCO (나이스페이먼츠)',
description: 'PAYCO로 결제 (나이스페이먼츠)',
title: 'PAYCO로 결제 (나이스페이먼츠)',
},
en: {
heading: 'PAYCO (NicePayments)',
description: 'Pay with PAYCO (NicePayments)',
title: 'Pay with PAYCO (NicePayments)',
},
markText: 'P',
markClassName: 'bg-red-500 text-white',
},
{
id: 'nicepay_skpay',
labels: [
'11pay (나이스페이먼츠)',
'11pay로 결제 (나이스페이먼츠)',
'11pay (NicePayments)',
'Pay with 11pay (NicePayments)',
],
ko: {
heading: '11pay (나이스페이먼츠)',
description: '11pay로 결제 (나이스페이먼츠)',
title: '11pay로 결제 (나이스페이먼츠)',
},
en: {
heading: '11pay (NicePayments)',
description: 'Pay with 11pay (NicePayments)',
title: 'Pay with 11pay (NicePayments)',
},
markText: '11',
markClassName: 'bg-orange-500 text-white',
},
{
id: 'nicepay_ssgpay',
labels: [
'SSG페이 (나이스페이먼츠)',
'SSG페이로 결제 (나이스페이먼츠)',
'SSG Pay (NicePayments)',
'Pay with SSG Pay (NicePayments)',
],
ko: {
heading: 'SSG페이 (나이스페이먼츠)',
description: 'SSG페이로 결제 (나이스페이먼츠)',
title: 'SSG페이로 결제 (나이스페이먼츠)',
},
en: {
heading: 'SSG Pay (NicePayments)',
description: 'Pay with SSG Pay (NicePayments)',
title: 'Pay with SSG Pay (NicePayments)',
},
markText: 'SSG',
markClassName: 'bg-red-700 text-white',
},
{
id: 'nicepay_lpay',
labels: [
'L.pay (나이스페이먼츠)',
'L.pay로 결제 (나이스페이먼츠)',
'L.pay (NicePayments)',
'Pay with L.pay (NicePayments)',
],
ko: {
heading: 'L.pay (나이스페이먼츠)',
description: 'L.pay로 결제 (나이스페이먼츠)',
title: 'L.pay로 결제 (나이스페이먼츠)',
},
en: {
heading: 'L.pay (NicePayments)',
description: 'Pay with L.pay (NicePayments)',
title: 'Pay with L.pay (NicePayments)',
},
markText: 'L',
markClassName: 'bg-purple-600 text-white',
},
];
let observer: MutationObserver | null = null;
let retryTimer: number | null = null;
let syncQueued = false;
function windowRecord(): Record<string, unknown> {
return window as unknown as Record<string, unknown>;
}
function isCheckoutPage(): boolean {
return CHECKOUT_RE.test(window.location.pathname);
}
function normalizedText(value: string | null | undefined): string {
return (value ?? '').replace(/\s+/g, ' ').trim();
}
function comparableText(value: string | null | undefined): string {
return normalizedText(value).replace(/\u200B/g, '');
}
function isKoreanPage(): boolean {
const lang = document.documentElement.lang || navigator.language || '';
return lang.toLowerCase().startsWith('ko');
}
function copyFor(definition: EasyPayDefinition): EasyPayCopy {
return isKoreanPage() ? definition.ko : definition.en;
}
function displayText(value: string): string {
return value
.replaceAll('네이버페이', '네이\u200B버페이')
.replaceAll('카카오페이', '카카\u200B오페이')
.replaceAll('삼성페이', '삼성\u200B페이')
.replaceAll('Naver Pay', 'Naver\u200B Pay')
.replaceAll('Kakao Pay', 'Kakao\u200B Pay')
.replaceAll('Samsung Pay', 'Samsung\u200B Pay')
.replaceAll('L.pay', 'L.\u200Bpay');
}
function findDefinitionById(id: string | undefined): EasyPayDefinition | null {
return EASY_PAY_DEFINITIONS.find((definition) => definition.id === id) ?? null;
}
function findDefinitionForButton(button: HTMLButtonElement): EasyPayDefinition | null {
const markedDefinition = findDefinitionById(button.dataset.nicepayEasyPayMethod);
if (markedDefinition) return markedDefinition;
const text = comparableText(button.textContent);
return EASY_PAY_DEFINITIONS.find((definition) => (
definition.labels.some((label) => text.includes(label))
)) ?? null;
}
function findPaymentRow(button: HTMLButtonElement): HTMLElement | null {
return button.querySelector<HTMLElement>('.flex.items-center.gap-2, .flex.items-center.gap-3')
?? button.querySelector<HTMLElement>('.flex.items-center');
}
function alignPaymentTextLeft(button: HTMLButtonElement, heading?: HTMLElement, description?: HTMLElement): void {
button.style.textAlign = 'left';
const row = findPaymentRow(button);
if (row) {
row.style.justifyContent = 'flex-start';
row.style.textAlign = 'left';
row.style.width = '100%';
}
const textContainer = heading?.parentElement ?? description?.parentElement;
if (textContainer instanceof HTMLElement) {
textContainer.style.textAlign = 'left';
textContainer.style.minWidth = '0';
}
}
function createMark(definition: EasyPayDefinition): HTMLSpanElement {
const mark = document.createElement('span');
mark.dataset.nicepayEasyPayMark = 'true';
mark.dataset.nicepayEasyPayMethod = definition.id;
mark.setAttribute('aria-hidden', 'true');
mark.className = `inline-flex items-center justify-center rounded-lg text-xs font-bold ${definition.markClassName}`;
mark.style.width = '32px';
mark.style.height = '32px';
mark.style.flex = '0 0 32px';
mark.textContent = definition.markText;
return mark;
}
function removeOtherPgArtifacts(button: HTMLButtonElement): void {
delete button.dataset.kginicisBrandPaymentButton;
delete button.dataset.kginicisBrandPaymentMethod;
delete button.dataset.kginicisNaverpayBrandButton;
delete button.dataset.nhnkcpEasyPayMethod;
delete button.dataset.nhnkcpEasyPayVisible;
delete button.dataset.nhnkcpEasyPayHidden;
button.querySelectorAll<HTMLElement>('[data-kginicis-brand-payment-mark="true"], [data-kginicis-naverpay-mark="true"], [data-nhnkcp-easy-pay-mark="true"]').forEach((element) => {
element.remove();
});
}
function findPaymentIcon(button: HTMLButtonElement): Element | null {
return button.querySelector('[data-nicepay-easy-pay-mark="true"]')
?? button.querySelector('[data-kginicis-brand-payment-mark="true"], [data-kginicis-naverpay-mark="true"], [data-nhnkcp-easy-pay-mark="true"]')
?? button.querySelector('svg')
?? button.querySelector('i[class*="fa-"], i[role="img"], i');
}
function ensureMark(button: HTMLButtonElement, definition: EasyPayDefinition): void {
const existingMark = button.querySelector<HTMLElement>('[data-nicepay-easy-pay-mark="true"]');
if (existingMark) {
existingMark.dataset.nicepayEasyPayMethod = definition.id;
existingMark.className = `inline-flex items-center justify-center rounded-lg text-xs font-bold ${definition.markClassName}`;
existingMark.textContent = definition.markText;
return;
}
const mark = createMark(definition);
const icon = findPaymentIcon(button);
if (icon && icon.parentElement) {
icon.replaceWith(mark);
return;
}
const row = findPaymentRow(button);
row?.prepend(mark);
}
function updatePaymentText(button: HTMLButtonElement, definition: EasyPayDefinition): void {
const paragraphs = Array.from(button.querySelectorAll<HTMLParagraphElement>('p'));
const copy = copyFor(definition);
const headingText = displayText(copy.heading);
const descriptionText = displayText(copy.description);
const heading = paragraphs[0];
const description = paragraphs[1];
if (heading && heading.textContent !== headingText) {
heading.textContent = headingText;
}
if (heading) {
heading.setAttribute('aria-label', copy.heading);
heading.style.textAlign = 'left';
heading.style.whiteSpace = 'normal';
heading.style.wordBreak = 'keep-all';
heading.style.overflowWrap = 'anywhere';
}
if (description && description.textContent !== descriptionText) {
description.textContent = descriptionText;
}
if (description) {
description.style.textAlign = 'left';
description.style.fontSize = '12px';
description.style.lineHeight = '1rem';
description.style.whiteSpace = 'normal';
description.style.wordBreak = 'keep-all';
description.style.overflowWrap = 'anywhere';
}
alignPaymentTextLeft(button, heading, description);
button.title = copy.title;
}
function showButton(button: HTMLButtonElement, definition: EasyPayDefinition): void {
if (button.hidden) button.hidden = false;
if (button.disabled) button.disabled = false;
if (button.style.display === 'none') button.style.removeProperty('display');
button.removeAttribute('aria-hidden');
button.dataset.nicepayEasyPayMethod = definition.id;
button.dataset.nicepayEasyPayVisible = 'true';
removeOtherPgArtifacts(button);
ensureMark(button, definition);
updatePaymentText(button, definition);
}
function removeLegacyInjectedSection(): boolean {
const legacySection = document.getElementById(LEGACY_CONTAINER_ID);
if (!legacySection) return false;
legacySection.remove();
return true;
}
export async function syncRenderedCheckoutEasyPayMethods(
root: ParentNode = document,
): Promise<boolean> {
if (typeof window === 'undefined' || typeof document === 'undefined') return false;
if (!isCheckoutPage()) return false;
let changed = removeLegacyInjectedSection();
root.querySelectorAll<HTMLButtonElement>('button').forEach((button) => {
const definition = findDefinitionForButton(button);
if (!definition) return;
showButton(button, definition);
changed = true;
});
return changed;
}
function queueSync(): void {
if (syncQueued) return;
syncQueued = true;
window.setTimeout(() => {
syncQueued = false;
void syncRenderedCheckoutEasyPayMethods();
}, 0);
}
function stopRetries(): void {
if (retryTimer === null) return;
window.clearInterval(retryTimer);
retryTimer = null;
}
function startSync(): void {
if (!isCheckoutPage()) return;
stopRetries();
void syncRenderedCheckoutEasyPayMethods();
let attempts = 0;
retryTimer = window.setInterval(() => {
attempts += 1;
void syncRenderedCheckoutEasyPayMethods();
if (attempts >= SYNC_RETRY_ATTEMPTS) {
stopRetries();
}
}, SYNC_RETRY_INTERVAL_MS);
const body = document.body as HTMLElement & Record<string, unknown>;
if (body[LISTENER_FLAG]) return;
body[LISTENER_FLAG] = true;
observer = new MutationObserver(() => queueSync());
observer.observe(document.body, { childList: true, subtree: true, characterData: true });
}
function onRouteChange(): void {
if (isCheckoutPage()) startSync();
}
export function installCheckoutEasyPayInjector(): void {
if (typeof window === 'undefined' || typeof document === 'undefined') return;
const w = windowRecord();
if (w[FLAG]) return;
w[FLAG] = true;
console.info(`[${PLUGIN_ID}] checkout easy pay method sync installed`);
if (document.readyState === 'loading') {
document.addEventListener('DOMContentLoaded', () => startSync());
} else {
startSync();
}
const origPush = history.pushState.bind(history);
history.pushState = (...args: Parameters<typeof history.pushState>) => {
origPush(...args);
window.setTimeout(() => onRouteChange(), 200);
};
window.addEventListener('popstate', () => window.setTimeout(() => onRouteChange(), 200));
}
export function resetCheckoutEasyPayInjectorForTests(): void {
observer?.disconnect();
observer = null;
stopRetries();
syncQueued = false;
delete windowRecord()[FLAG];
if (document.body) {
delete ((document.body as HTMLElement & Record<string, unknown>)[LISTENER_FLAG]);
}
}
@@ -1,7 +1,6 @@
import { handlerMap } from './handlers';
import { initEasyPayWatcher } from './handlers/setPaymentMethod';
import { installOrderResponseInterceptor } from './orderResponseInterceptor';
import { installCheckoutEasyPayInjector } from './checkoutEasyPayInjector';
import { installOrderCompleteReceiptInjector } from './orderCompleteReceiptInjector';
import { installMypageOrderShowInjector } from './mypageOrderShowInjector';
import { installAdminPaymentMethodBrandInjector } from './adminPaymentMethodBrandInjector';
@@ -50,7 +49,6 @@ function registerHandlers(): number {
function initPlugin(): void {
// fetch 인터셉터는 G7Core 초기화와 무관하게 즉시 설치
installOrderResponseInterceptor();
installCheckoutEasyPayInjector();
installOrderCompleteReceiptInjector();
installMypageOrderShowInjector();
installAdminPaymentMethodBrandInjector();
@@ -26,48 +26,58 @@ class RegisterEasyPayMethodsListener implements HookListenerInterface
'name_key' => 'sirsoft-pay_nicepayments::payment_methods.naverpay.name',
'description_key' => 'sirsoft-pay_nicepayments::payment_methods.naverpay.description',
'icon' => 'wallet',
'brand_mark' => ['text' => 'N', 'class' => 'bg-green-500 text-white'],
],
[
'id' => 'nicepay_kakaopay',
'name_key' => 'sirsoft-pay_nicepayments::payment_methods.kakaopay.name',
'description_key' => 'sirsoft-pay_nicepayments::payment_methods.kakaopay.description',
'icon' => 'message-circle',
'brand_mark' => ['text' => 'K', 'class' => 'bg-yellow-400 text-gray-950'],
],
[
'id' => 'nicepay_samsungpay',
'name_key' => 'sirsoft-pay_nicepayments::payment_methods.samsungpay.name',
'description_key' => 'sirsoft-pay_nicepayments::payment_methods.samsungpay.description',
'icon' => 'smartphone',
'brand_mark' => ['text' => 'S', 'class' => 'bg-blue-600 text-white'],
],
[
'id' => 'nicepay_applepay',
'name_key' => 'sirsoft-pay_nicepayments::payment_methods.applepay.name',
'description_key' => 'sirsoft-pay_nicepayments::payment_methods.applepay.description',
'icon' => 'smartphone',
'brand_mark' => ['text' => 'A', 'class' => 'bg-gray-900 text-white'],
// 애플페이는 iOS 기기에서만 노출(과거 injector iOS 게이팅 이관).
'requires_ios' => true,
],
[
'id' => 'nicepay_payco',
'name_key' => 'sirsoft-pay_nicepayments::payment_methods.payco.name',
'description_key' => 'sirsoft-pay_nicepayments::payment_methods.payco.description',
'icon' => 'wallet',
'brand_mark' => ['text' => 'P', 'class' => 'bg-red-500 text-white'],
],
[
'id' => 'nicepay_skpay',
'name_key' => 'sirsoft-pay_nicepayments::payment_methods.skpay.name',
'description_key' => 'sirsoft-pay_nicepayments::payment_methods.skpay.description',
'icon' => 'wallet-cards',
'brand_mark' => ['text' => '11', 'class' => 'bg-orange-500 text-white'],
],
[
'id' => 'nicepay_ssgpay',
'name_key' => 'sirsoft-pay_nicepayments::payment_methods.ssgpay.name',
'description_key' => 'sirsoft-pay_nicepayments::payment_methods.ssgpay.description',
'icon' => 'shopping-bag',
'brand_mark' => ['text' => 'SSG', 'class' => 'bg-red-700 text-white'],
],
[
'id' => 'nicepay_lpay',
'name_key' => 'sirsoft-pay_nicepayments::payment_methods.lpay.name',
'description_key' => 'sirsoft-pay_nicepayments::payment_methods.lpay.description',
'icon' => 'wallet',
'brand_mark' => ['text' => 'L', 'class' => 'bg-purple-600 text-white'],
],
];
@@ -102,6 +112,8 @@ class RegisterEasyPayMethodsListener implements HookListenerInterface
nameKey: $method['name_key'],
descriptionKey: $method['description_key'],
icon: $method['icon'],
brandMark: $method['brand_mark'] ?? null,
requiresIos: $method['requires_ios'] ?? false,
),
self::EASY_PAY_METHODS
);
@@ -157,9 +169,19 @@ class RegisterEasyPayMethodsListener implements HookListenerInterface
return $insertAfter;
}
private function buildEntry(string $id, string $nameKey, string $descriptionKey, string $icon): array
{
return [
/**
* @param array{text: string, class: string}|null $brandMark 배지 브랜드 마크(텍스트+색상 클래스)
* @param bool $requiresIos iOS 기기에서만 노출되는 수단 여부(애플페이)
*/
private function buildEntry(
string $id,
string $nameKey,
string $descriptionKey,
string $icon,
?array $brandMark = null,
bool $requiresIos = false,
): array {
$entry = [
'id' => $id,
'name' => [
'ko' => __($nameKey, [], 'ko'),
@@ -185,5 +207,18 @@ class RegisterEasyPayMethodsListener implements HookListenerInterface
'mileage_deduction_timing' => 'payment_complete',
],
];
// 브랜드 마크(색 배지) — 레이아웃 BrandMark 컴포넌트가 text+class 로 렌더한다.
// 과거 checkoutEasyPayInjector 가 DOM 후처리로 주입하던 markText/markClassName 이관.
if ($brandMark !== null) {
$entry['brand_mark'] = $brandMark;
}
// iOS 전용 수단(애플페이)은 비-iOS 기기에서 체크아웃 레이아웃이 렌더하지 않는다.
if ($requiresIos) {
$entry['requires_ios'] = true;
}
return $entry;
}
}
@@ -144,4 +144,45 @@ class RegisterEasyPayMethodsListenerTest extends TestCase
$this->assertStringNotContainsString('Samsung Pay', $joined);
$this->assertStringNotContainsString('L.pay', $joined);
}
/**
* @scenario mark_form=badge, requires_ios=false, device=ipados_desktop_ua
*
* @effects brand_mark_flows_to_cached, badge_renders_text_and_color
*/
public function test_easy_pay_methods_carry_badge_brand_mark(): void
{
// 브랜드 마크(색 배지)를 카탈로그로 편입 — 과거 checkoutEasyPayInjector 가
// DOM 후처리로 주입하던 markText/markClassName 을 등록 데이터로 이관.
$listener = new RegisterEasyPayMethodsListener;
$methods = collect($listener->injectEasyPayMethods([
['id' => 'phone'],
['id' => 'point'],
]))->keyBy('id');
$this->assertSame(
['text' => 'N', 'class' => 'bg-green-500 text-white'],
$methods->get('nicepay_naverpay')['brand_mark'] ?? null,
);
$this->assertSame(
['text' => 'SSG', 'class' => 'bg-red-700 text-white'],
$methods->get('nicepay_ssgpay')['brand_mark'] ?? null,
);
}
public function test_only_apple_pay_requires_ios(): void
{
// 애플페이만 iOS 전용 노출 플래그를 가진다.
$listener = new RegisterEasyPayMethodsListener;
$methods = collect($listener->injectEasyPayMethods([
['id' => 'phone'],
['id' => 'point'],
]))->keyBy('id');
$this->assertTrue($methods->get('nicepay_applepay')['requires_ios'] ?? false);
$this->assertArrayNotHasKey('requires_ios', $methods->get('nicepay_naverpay'));
$this->assertArrayNotHasKey('requires_ios', $methods->get('nicepay_samsungpay'));
}
}