fix(tosspayments,pay_nicepayments,pay_nhnkcp,pay_kginicis): 토스 전환 누락 보완 + 탭 복귀 브랜드 배지 재주입
토스페이먼츠가 "확장 결제수단 1급화" 전환에서 통째로 빠져 있었다. 토스 결제수단은 그 전환 3일 전에 들어왔고, 전환 커밋은 nicepayments·nhnkcp·kginicis 만 건드렸다. 가 발견한 두 증상(브랜드 심벌 미노출 / PG 자유 선택)의 원인이 이 하나다. 토스페이먼츠 - 간편결제 5종에 brand_mark 를 선언한다. 같은 브랜드는 어느 PG 를 통하든 같은 배지여야 하므로 문자·색을 다른 PG 플러그인과 동일 값으로 맞췄다. 카드·가상계좌·계좌이체·휴대폰은 브랜드가 아니라 결제 형태이므로 키를 두지 않는다. - defaults 에 pg_provider·pg_locked·needs_pg·refund_method 를 선언한다. 기존에는 pg_provider 가 null 이라 관리자 화면이 "PG 고정" 배지 대신 선택지가 하나도 없는 PG 셀렉트를 그렸고(토스 PG 는 자기 결제수단 id 를 supported_methods 로 선언하지 않는다), 서버 쪽으로도 PG 없는 결제수단으로 오인될 수 있었다. - 관리자 브랜드 injector 를 신설한다. 관리자 레이아웃은 아이콘 열을 _cached_icon 하나로만 그리고 _cached_brand_mark 를 읽는 노드가 없어, 각 PG 플러그인이 자기 행의 아이콘을 배지로 치환하는 구조인데 토스에만 그 파일이 없었다. 4개 PG 플러그인 공통 - 환경설정 탭 전환은 pushState 가 아니라 replaceState 로 URL 만 바꾼다(탭 왕복 1회에 push 0 / replace 2 실측). pushState·popstate 만 후킹하던 injector 는 다른 탭에 갔다 돌아오면 행은 다시 렌더되는데 배지만 사라진 채 남았다. replaceState 후킹을 추가한다. 브라우저 실측(Chrome MCP 7대 축)으로 전 항목 확인했다. 탭 복귀 재주입은 수정 전 toss 0 / nicepay 0 / kginicis 0 → 수정 후 5 / 8 / 4 로 복원되는 것을 계측했다.
This commit is contained in:
1 parent
30ad72a3a1
commit
1b0be674aa
19 files changed
+747
-21
No files matched your search
@@ -22,6 +22,7 @@
|
||||
|
||||
### Fixed
|
||||
|
||||
- 이커머스 관리자 주문설정에서 다른 탭에 갔다 돌아오면 간편결제 항목의 브랜드 로고가 사라지고 회색 기본 아이콘으로 남던 문제를 수정했습니다. 화면을 새로고침해야만 다시 표시됐습니다.
|
||||
- 결제 취소 기록의 환불 금액에 원화 단위가 고정 표기되던 문제를 수정했습니다. 해외 결제(엔화 등) 취소도 실제 결제 통화로 표시됩니다.
|
||||
|
||||
- 쇼핑몰 주소를 기본값이 아닌 값으로 바꾸거나 주소 없이 운영하는 상점에서, 결제를 마치거나 결제에 실패한 구매자가 존재하지 않는 페이지로 이동하던 문제를 수정했습니다. 이동 주소가 기본 주소로 고정돼 있었기 때문이며, 이제 상점 주소 설정을 따라갑니다. 이미 운영 중인 사이트도 업데이트 시 자동으로 반영되며, 이동 주소를 직접 입력해 두었다면 그 값은 그대로 유지됩니다. (#85 @hwaryeon1234 님께서 제보해주셨습니다.)
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"$schema": "https://json-schema.org/draft/2020-12/schema",
|
||||
"identifier": "sirsoft-pay_kginicis",
|
||||
"version": "1.0.2",
|
||||
"version": "1.1.0",
|
||||
"components": {
|
||||
"basic": [],
|
||||
"composite": [],
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
(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
|
||||
(function(){"use strict";const x="kginicis_pay_form_",R="__sirsoftKginicisReloadStandardPaySdk",w="__sirsoftKginicisMobilePaymentReturnPending";function ie(){if(typeof document>"u")return 0;const e=document.querySelectorAll(`form[id^="${x}"]`);return e.forEach(t=>t.remove()),e.length}function qe(){typeof window>"u"||(window[R]=!0)}function We(){if(typeof window>"u")return!1;const e=window,t=e[R]===!0;return delete e[R],t}function Ve(e){typeof window>"u"||typeof document>"u"||(window.INIStdPay=void 0,document.querySelectorAll(`script[src="${e}"], script[src*="/INIStdPay_third-party.js"]`).forEach(t=>t.remove()))}function ze(e=Date.now()){if(!(typeof window>"u"))try{window.sessionStorage.setItem(w,String(e))}catch{window[w]=e}}function M(){if(!(typeof window>"u")){try{window.sessionStorage.removeItem(w)}catch{}delete window[w]}}function ae(e=Date.now()){if(typeof window>"u")return!1;let t=null;try{const n=window.sessionStorage.getItem(w);t=n?Number(n):null}catch{t=null}if(!Number.isFinite(t)){const n=window[w];t=typeof n=="number"?n:Number(n)}return!Number.isFinite(t)||e-t>18e5?(M(),!1):!0}const N="sirsoft-pay_kginicis",Xe=N,Ze="payment-window-closed",se="__sirsoftKginicisPaymentCloseListenerInstalled",L="__sirsoftKginicisActiveStandardPaymentCloseContext",ce=20,Qe=100,O={info:(...e)=>console.info(`[${N}]`,...e),warn:(...e)=>console.warn(`[${N}]`,...e)};function et(e){if(!e||typeof e!="object")return!1;const t=e;return t.source===Xe&&t.type===Ze}function $(){return/\/shop\/checkout\/?$/.test(window.location.pathname)}function P(){return window}function tt(){const e=P()[L];return!e||typeof e!="object"?null:e}function nt(e){return/^https?:\/\//i.test(e)||e.startsWith("/api/")?e:e.startsWith("/plugins/")?`/api${e}`:e.startsWith("plugins/")?`/api/${e}`:e}function rt(e){e.closeReportUrl&&(P()[L]={...e,reported:!1})}function de(){delete P()[L]}function le(){de()}async function ot(e="payment-window-closed"){const t=tt();if(!t||t.reported||!$())return;t.reported=!0;const n={oid:t.oid,price:t.price,buyer_email:t.buyer_email??"",buyer_phone:t.buyer_phone??"",payment_method:t.payment_method??"",reason:e};try{const r=window.G7Core?.api;typeof r?.post=="function"?await r.post(t.closeReportUrl,n):await fetch(nt(t.closeReportUrl),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(n),keepalive:!0})}catch(r){O.warn("failed to report KG payment window close",{reason:e,error:r})}finally{de()}}function ue(e="payment-window-closed",t=!0){if(!$())return!1;const r=window.G7Core?.state?.setLocal;return typeof r!="function"?(t&&O.warn("G7Core.state.setLocal not available while resetting payment submit state"),!1):(ie(),qe(),r({isSubmittingOrder:!1}),O.info("checkout submit state reset after KG payment close",{reason:e}),!0)}function it(e,t=!1){let n=0;const r=()=>{if(n++,!(t&&!ae())){if(ue(e,n>=ce)){t&&M();return}!$()||n>=ce||window.setTimeout(r,Qe)}};r()}function I(e){ae()&&it(e,!0)}function at(){if(typeof window>"u")return;const e=P();e[se]||(window.addEventListener("message",t=>{t.origin===window.location.origin&&et(t.data)&&(ot(t.data.reason),ue(t.data.reason))}),window.addEventListener("pagehide",()=>{le()}),window.addEventListener("beforeunload",()=>{le()}),window.addEventListener("pageshow",t=>{I(t.persisted?"mobile-payment-bfcache-return":"mobile-payment-page-show")}),window.addEventListener("focus",()=>{I("mobile-payment-window-focus")}),document.addEventListener("visibilitychange",()=>{document.visibilityState==="visible"&&I("mobile-payment-visibility-return")}),e[se]=!0,I("mobile-payment-listener-installed"))}function me(){if(typeof navigator>"u")return!1;const e=navigator;if(e.userAgentData?.mobile!==void 0)return e.userAgentData.mobile;const t=(e.userAgent||"").toLowerCase(),n=((e.userAgentData?.platform??e.platform)||"").toLowerCase();if(/android|iphone|ipad|ipod|windows phone|iemobile|blackberry|opera mini|mobile safari/.test(t)||/iphone|ipad|ipod|ios/.test(n))return!0;const r=e.maxTouchPoints??0;return/macintosh|mac os x/.test(t)&&r>1}function st(e){return new Promise((t,n)=>{if(document.querySelector(`script[src="${e}"]`)){t();return}const r=document.createElement("script");r.src=e,r.async=!0,r.onload=()=>t(),r.onerror=()=>n(new Error(`Failed to load script: ${e}`)),document.head.appendChild(r)})}function fe(e,t){if(!t.startsWith("kginicis_"))return e;const n=new URL(e,window.location.origin);return n.searchParams.set("selectedPaymentMethod",t),n.toString()}function ct(e){const t=(e??"").trim().toUpperCase();return t===""||t==="WON"?"KRW":t}function pe(e,t,n="utf-8",r){const o=document.createElement("form");r&&(o.id=r),o.method="POST",o.action=e,o.acceptCharset=n,o.style.display="none";for(const[i,s]of Object.entries(t)){const a=document.createElement("input");a.type="hidden",a.name=i,a.value=s,o.appendChild(a)}document.body.appendChild(o),o.submit()}const dt={card:"Card",vbank:"VBank",bank:"DirectBank",phone:"HPP",kginicis_samsung_pay:"onlyssp",kginicis_naverpay:"onlynaverpay",kginicis_lLine truncated
|
||||
<div class="row">
|
||||
<dt>${E(i.label)}</dt>
|
||||
<dd>${E(i.value)}</dd>
|
||||
@@ -87,5 +87,5 @@
|
||||
<div class="actions"><button type="button" onclick="window.print()">인쇄</button></div>
|
||||
</main>
|
||||
</body>
|
||||
</html>`),t.document.close()}function E(e){return e.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'")}const D="sirsoft-pay_kginicis",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
|
||||
</html>`),t.document.close()}function E(e){return e.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'")}const D="sirsoft-pay_kginicis",be="__kginicisOrderShowInjectorInstalled",K="kginicis-mp-receipt-row",ke=/^(?:\/mypage\/orders\/([^/]+)|\/shop\/guest\/orders\/([^/]+))$/,G=new Map;function Tt(e){try{const n=window.G7Core?.getState,i=n?.()?.currentDataContext?.order?.data;return i&&(i.order_number===e||i.id!==void 0&&String(i.id)===e)?i:null}catch{return null}}function xt(){const e=document.getElementById("order_payment_info_panel");if(e)return Array.from(e.children).find(r=>r.className?.includes("space-y"))??e;const t=Array.from(document.querySelectorAll("h3")).find(r=>{const o=r.textContent?.trim()??"";return o.includes("결제 정보")||/^Payment Information$/i.test(o)});if(!t)return null;const n=t.parentElement?.parentElement;return n?Array.from(n.children).find(r=>r.className?.includes("space-y"))??n:null}function Rt(e,t){if(!t)return!1;const n=Array.from(e.querySelectorAll("div"));for(const r of n){const o=Array.from(r.children).filter(a=>a instanceof HTMLElement&&a.tagName==="SPAN");if(o.length<2)continue;const i=o[0].textContent?.trim();if(i!=="결제 방법"&&i!=="결제수단"&&i!=="Payment Method")continue;const s=o[o.length-1];return s.textContent?.trim()===t?(r.dataset.kginicisPaymentMethodRow="true",!0):(s.textContent=t,s.dataset.kginicisPaymentMethodPatched="true",r.dataset.kginicisPaymentMethodRow="true",!0)}return!1}function Mt(e,t){const n=document.createElement("div");n.id=K,n.className="flex items-center justify-between",n.dataset.kginicisReceiptRow="mypage-order";const r=document.createElement("span");r.className="text-gray-500 dark:text-gray-400 text-sm",r.textContent=vt(t);const o=document.createElement("button");return o.type="button",o.dataset.kginicisReceiptButton="mypage-order",o.className="inline-flex items-center gap-1 text-sm text-blue-600 dark:text-blue-400 hover:underline disabled:opacity-50",o.textContent=A(t),o.addEventListener("click",async()=>{o.disabled=!0,o.textContent="로딩 중...";const i=await v(e);o.disabled=!1,o.textContent=A(i??t),C(i)&&we(i)}),n.appendChild(r),n.appendChild(o),n}async function Nt(e,t){const n=Tt(e),r=n?.payment;if(r&&(r.pg_provider!=="kginicis"||!r.transaction_id))return!0;const o=n?.order_number??(t?e:null);if(!o)return!1;if(!t&&n&&!r)return!0;const i=xt();if(!i)return!1;const{status:s,info:a}=await ge(o);if(!t&&s===404)return!0;const c=r?.payment_status==="paid",u=a?.receipt_type==="cbt_confirmation";if(r&&!c&&!u)return!0;if(!r&&!C(a))return!1;const d=Rt(i,a?.payment_method_display_label);return!document.getElementById(K)&&C(a)&&(i.appendChild(Mt(o,a)),console.info(`[${D}] receipt button injected on mypage order show`)),d&&console.info(`[${D}] payment method display patched on mypage order show`),!!(document.getElementById(K)||d)}function Lt(e,t){if(G.has(e))return;let n=0;const r=window.setInterval(()=>{n++,Nt(e,t).then(o=>{(o||n>=30)&&(window.clearInterval(r),G.delete(e))})},400);G.set(e,r)}function Ot(){const e=location.pathname.match(ke);if(e){const t=e[1],n=e[2],r=t??n;r&&Lt(r,n!==void 0)}}function $t(){if(typeof window>"u")return;const e=window;if(e[be])return;e[be]=!0,console.info(`[${D}] mypage order show injector installed`);let t=null;const n=(a=1500)=>{t!==null&&window.clearTimeout(t),t=window.setTimeout(()=>{t=null,Ot()},a)};document.readyState==="loading"?document.addEventListener("DOMContentLoaded",()=>n()):n();const r=history.pushState.bind(history);history.pushState=(...a)=>{r(...a),n(600)};const o=history.replaceState.bind(history);history.replaceState=(...a)=>{o(...a),n(600)},window.addEventListener("popstate",()=>n(500));const i=document.getElementById("app")??document.body;new MutationObserver(()=>{ke.test(location.pathname)&&n(250)}).observe(i,{childList:!0,subtree:!0})}const j="sirsoft-pay_kginicis",Ce="__kginicisAdminPaymentDisplayInjectorInstalled",Dt=/^\/admin\/ecommerce\/orders\/([^/]+)$/;function Kt(){return localStorage.getItem("auth_token")}async function Gt(e){const t=Kt();if(!t)return null;try{const n=await fetch(`/api/plugins/${j}/admin/orders/${e}/transaction-status`,{headers:{Authorization:`Bearer ${t}`,Accept:"application/json"}});if(!n.ok)return null;const r=await n.json();return("data"in r?r.data:r)??null}catch{return null}}function jt(e){return Array.from(e.children).filter(t=>t instanceof HTMLElement)}function Yt(e,t){let n=!1;const r=Array.from(e.querySelectorAll("div"));for(const o of r){const i=jt(o),s=i.findIndex(l=>l.textContent?.trim()==="결제수단");if(s<0)continue;const a=i.slice(s+1).find(l=>l.textContent?.trim()&&l.textContent.trim()!=="결제수단");if(!a)continue;const c=i.slice(s+2).find(l=>/^\(.+\)$/.test(l.textContent?.trim()??"")),u=c?.textContent?.trim().replace(/^\(|\)$/g,"")??"",d=u&&t.endsWith(")")?t.replace(/\)$/,`, ${u})`):t;a.textContent?.trim()!==d&&(a.textContent=d,a.dataset.kginicisPaymentMethodPatched="true"),o.dataLine truncated
|
||||
//# sourceMappingURL=plugin.iife.js.map
|
||||
@@ -265,6 +265,17 @@ export function installAdminPaymentMethodBrandInjector(): void {
|
||||
origPush(...args);
|
||||
window.setTimeout(() => onRouteChange(), 200);
|
||||
};
|
||||
|
||||
// replaceState 도 후킹한다 — 환경설정 화면의 탭 전환은 pushState 가 아니라
|
||||
// replaceState 로 URL 만 바꾼다(실측: 탭 왕복 1회에 push 0 / replace 2). pushState 만
|
||||
// 후킹하면 다른 탭에 갔다 돌아왔을 때 onRouteChange 가 발화하지 않아 배지가 사라진 채로
|
||||
// 남는다(행은 그대로 렌더되므로 화면상 아이콘만 회색으로 되돌아간다).
|
||||
const origReplace = history.replaceState.bind(history);
|
||||
history.replaceState = (...args: Parameters<typeof history.replaceState>) => {
|
||||
origReplace(...args);
|
||||
window.setTimeout(() => onRouteChange(), 200);
|
||||
};
|
||||
|
||||
window.addEventListener('popstate', () => window.setTimeout(() => onRouteChange(), 200));
|
||||
}
|
||||
|
||||
|
||||
@@ -12,6 +12,7 @@
|
||||
|
||||
### Fixed
|
||||
|
||||
- 이커머스 관리자 주문설정에서 다른 탭에 갔다 돌아오면 간편결제 항목의 브랜드 색상 배지가 사라지고 회색 기본 아이콘으로 남던 문제를 수정했습니다. 화면을 새로고침해야만 다시 표시됐습니다.
|
||||
- 관리자 주문 상세의 거래 조회에서 취소·환불 금액에 원화 단위가 고정 표기되던 문제를 수정했습니다. 이제 주문 시점 기준 통화로 표시됩니다.
|
||||
- 결제 취소 기록의 환불 금액 표기도 결제 통화를 따르도록 수정했습니다.
|
||||
- 쇼핑몰 주소를 기본값이 아닌 값으로 바꾸거나 주소 없이 운영하는 상점에서, 결제를 마치거나 결제에 실패한 구매자가 존재하지 않는 페이지로 이동하던 문제를 수정했습니다. 이동 주소가 기본 주소로 고정돼 있었기 때문이며, 이제 상점 주소 설정을 따라갑니다. 이미 운영 중인 사이트도 업데이트 시 자동으로 반영되며, 이동 주소를 직접 입력해 두었다면 그 값은 그대로 유지됩니다. (#85 @hwaryeon1234 님께서 제보해주셨습니다.)
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"$schema": "https://json-schema.org/draft/2020-12/schema",
|
||||
"identifier": "sirsoft-pay_nhnkcp",
|
||||
"version": "1.0.0",
|
||||
"version": "1.0.1",
|
||||
"components": {
|
||||
"basic": [],
|
||||
"composite": [],
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
(function(){"use strict";function Le(e){return/^https?:\/\//i.test(e)||e.startsWith("/api/")?e:e.startsWith("/plugins/")?`/api${e}`:e.startsWith("plugins/")?`/api/${e}`:e}function Oe(e){return e.trim().slice(0,160)}function Ke(e){if(e)return e.replace(/\/payment\/close-report$/,"/payment/retry")}async function 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
|
||||
(function(){"use strict";function Le(e){return/^https?:\/\//i.test(e)||e.startsWith("/api/")?e:e.startsWith("/plugins/")?`/api${e}`:e.startsWith("plugins/")?`/api/${e}`:e}function Oe(e){return e.trim().slice(0,160)}function Ke(e){if(e)return e.replace(/\/payment\/close-report$/,"/payment/retry")}async function te(e,t,n=!1){const o=window.G7Core?.api;if(typeof o?.post=="function"){await o.post(e,t);return}const r=await fetch(Le(e),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t),keepalive:n});if(!r.ok){let a=`NHN KCP payment request failed (${r.status})`;try{const s=await r.json(),i=Array.isArray(s?.errors?.message)?s.errors.message[0]:s?.error??s?.message;typeof i=="string"&&i.trim()!==""&&(a=i)}catch{}throw new Error(a)}}async function je(e){const t=Ke(e.closeReportUrl);t&&await te(t,{oid:e.oid,price:Number(e.price),buyer_email:e.buyer_email??"",buyer_phone:e.buyer_phone??"",payment_method:e.payment_method??""})}async function Be(e,t="kcp-window-closed"){if(!e.closeReportUrl)return;const n={oid:e.oid,price:Number(e.price),buyer_email:e.buyer_email??"",buyer_phone:e.buyer_phone??"",payment_method:e.payment_method??"",reason:Oe(t)||"kcp-window-closed"};try{await te(e.closeReportUrl,n,!0)}catch(o){console.warn("[sirsoft-pay_nhnkcp] failed to report payment window close",o)}}const De="nhnkcp_applepay";function S(e){return e===De}function x(){if(typeof navigator>"u")return!1;const e=navigator,t=(e.userAgent||"").toLowerCase(),n=((e.userAgentData?.platform??e.platform)||"").toLowerCase(),o=e.maxTouchPoints??0;return/iphone|ipad|ipod/.test(t)||/iphone|ipad|ipod|ios/.test(n)?!0:/macintosh|mac os x/.test(t)&&o>1}function M(){return((typeof document<"u"?document.documentElement.lang:"")||"").toLowerCase().startsWith("ko")?"애플페이는 IOS 기기에 모바일결제만 가능합니다.":"Apple Pay is available only for mobile payments on iOS devices."}function T(e){return(e??"KRW").trim().toUpperCase()||"KRW"}function He(e){return T(e)==="KRW"}function Fe(e){const t=T(e);return((typeof document<"u"?document.documentElement.lang:"")||"").toLowerCase().startsWith("ko")?`NHN KCP는 KRW 결제만 지원합니다. (${t})`:`NHN KCP supports KRW payments only. (${t})`}function qe(e){const t=Math.max(0,Math.round(Number(e.amount??0))),n=Math.min(Math.max(0,Math.round(Number(e.tax_free_amount??0))),t);if(n<=0)return{};const o=Math.max(0,Math.round(Number(e.tax_amount??0))),r=Math.max(0,Math.round(Number(e.vat_amount??0))),a=Math.max(0,t-n),s=a>0&&o>0&&r>0?Math.min(a,Math.round(a*(r/o))):0,i=a-s;return{tax_flag:"TG03",comm_tax_mny:String(i),comm_vat_mny:String(s),comm_free_mny:String(n)}}class R extends Error{constructor(t){super(t??"결제가 취소되었습니다."),this.name="KcpCancelledError"}}const Ue={card:"100000000000",bank_transfer:"010000000000",virtual_account:"001000000000",mobile:"000010000000",bank:"010000000000",vbank:"001000000000",phone:"000010000000"},ne={nhnkcp_payco:{payco_direct:"Y"},nhnkcp_naverpay:{naverpay_direct:"Y"},nhnkcp_naverpay_point:{naverpay_direct:"Y",naverpay_point_direct:"Y"},nhnkcp_kakaopay:{kakaopay_direct:"Y"},nhnkcp_applepay:{applepay_direct:"Y"}};function Ye(e,t){const n=e.toLowerCase();return!t||!Object.prototype.hasOwnProperty.call(ne,n)?{}:{param_opt_1:n,nhnkcp_easy_pay_method:n}}function Ge(e){if(!e.isConnected)return!0;const t=window.getComputedStyle(e);if(t.display==="none"||t.visibility==="hidden")return!0;const n=e.getBoundingClientRect();return n.width<=0||n.height<=0}function We(e,t){let n=!1,o,r;const a=()=>{n=!0,r&&(r.disconnect(),r=void 0),o!==void 0&&(window.clearInterval(o),o=void 0)},s=()=>{n||!Ge(e)||(a(),t())},i=document.body??document.documentElement;return i&&typeof MutationObserver<"u"&&(r=new MutationObserver(s),r.observe(i,{attributes:!0,attributeFilter:["class","hidden","style"],childList:!0,subtree:!0})),o=window.setInterval(s,300),a}function ze(){if(typeof navigator>"u")return!1;if(x())return!0;const e=navigator;if(e.userAgentData?.mobile!==void 0)return e.userAgentData.mobile;const t=(navigator.userAgent||"").toLowerCase();return!!(/android|iphone|ipod|windows phone|iemobile|blackberry|opera mini|mobile safari/.test(t)||(navigator.maxTouchPoints??0)>1&&!t.includes("windows")&&!t.includes("macintosh"))}async function Je(e,t){const{pgPaymentData:n,paymentMethod:o}=e.params||{};if(!n){console.error("[sirsoft-pay_nhnkcp] pgPaymentData is required");return}const r=o??n.payment_method??n.pay_method??"card",a=typeof r=="string"&&r.startsWith("nhnkcp_"),s=window.G7Core;let i=null;try{if(!He(n.currency)){const u=Fe(n.currency);s?.state?.setLocal?.({paymentErrorMessage:u,isSubmittingOrder:!1,paymentMethod:r}),s?.modal?.open?.("nhnkcp_payment_error_modal");return}if(S(r)&&!x()){const u=M();s?.state?.setLocal?.({paymentErrorMessage:u,isSubmittingOrder:!1,paymentMethod:r}),s?.modal?.open?.("nhnkcp_payment_error_modal");return}const c=await s.api.get("/modules/sirsoft-ecommerce/payments/client-config/nhnkcp");if(!c.data){console.error("[Line truncated
|
||||
<script src="${e.sdk_url}"><\/script>
|
||||
</head><body style="margin:0;padding:0;background:transparent;">
|
||||
<form name="order_info">${c}</form>
|
||||
@@ -14,4 +14,5 @@ try {
|
||||
window.__kcpFail && window.__kcpFail(e);
|
||||
}
|
||||
<\/script>
|
||||
</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
|
||||
</body></html>`),X.close(),y=window.setTimeout(()=>{N(new Error("KCP SDK load timeout"))},15e3),f.__kcpReady=()=>{y!==void 0&&(clearTimeout(y),y=void 0)}})}const Xe={nhnkcp_payco:"PAYCO",nhnkcp_naverpay:"네이버페이",nhnkcp_naverpay_point:"네이버페이 포인트",nhnkcp_kakaopay:"카카오페이",nhnkcp_applepay:"Apple Pay"},Ze="0 0 0 2px #ffffff, 0 0 0 5px rgba(0,0,0,0.55)";function oe(){return document.querySelector(".nhnkcp-easy-pay-btns")??null}function re(){const e=oe();e&&e.querySelectorAll("button").forEach(t=>{t.style.boxShadow="",t.style.outline=""})}function et(e){const t=oe();if(!t)return;const n=Xe[e];t.querySelectorAll("button").forEach(o=>{o.textContent?.trim()===n?(o.style.boxShadow=Ze,o.style.outline="none"):(o.style.boxShadow="",o.style.outline="")})}function tt(e){const t=e.params?.paymentMethod;if(!t)return;const n=window.G7Core;if(S(t)&&!x()){const r=M();n?.state?.setLocal?.({paymentErrorMessage:r,isSubmittingOrder:!1}),n?.modal?.open?.("nhnkcp_payment_error_modal"),re();return}const o=typeof t=="string"&&t.startsWith("nhnkcp_");n?.state?.setLocal?.({paymentMethod:t}),o?et(t):re()}function nt(e){const t=document.createElement("textarea");t.value=e,t.setAttribute("readonly","readonly"),t.style.position="fixed",t.style.left="-9999px",t.style.top="0",document.body.appendChild(t),t.select();try{document.execCommand("copy")}finally{t.remove()}}async function ot(e){const t=String(e.params?.text??"");if(t!==""){if(navigator.clipboard&&typeof navigator.clipboard.writeText=="function"){await navigator.clipboard.writeText(t);return}nt(t)}}const ae={requestPayment:Je,setPaymentMethod:tt,copyToClipboard:ot},se="/api/modules/sirsoft-ecommerce/user/orders",$="sirsoft-pay_nhnkcp",ie={info:(...e)=>console.info(`[${$}]`,...e),warn:(...e)=>console.warn(`[${$}]`,...e),error:(...e)=>console.error(`[${$}]`,...e)};function rt(e){return typeof e=="string"?e:e instanceof URL?e.toString():typeof Request<"u"&&e instanceof Request?e.url:String(e)}function at(e,t){return t?.method?t.method.toUpperCase():typeof Request<"u"&&e instanceof Request?e.method.toUpperCase():"GET"}function st(e,t){if(t!=="POST")return!1;const n=e.split("?")[0].split("#")[0];return n===se||n.endsWith(se)}function it(e){try{return JSON.parse(e).payment_method}catch{return}}function ct(e){return new Response(JSON.stringify({success:!1,message:e,error:e,errors:{payment_method:[e]}}),{status:422,statusText:"Unprocessable Content",headers:{"Content-Type":"application/json"}})}function dt(){if(typeof window>"u"||typeof window.fetch!="function")return;const e="__sirsoftNhnkcpInterceptorInstalled",t=window;if(t[e])return;t[e]=!0;const n=window.fetch.bind(window);window.fetch=async function(r,a){const s=rt(r),i=at(r,a);if(!st(s,i))return n(r,a);let c;if(a?.body&&typeof a.body=="string"&&(c=it(a.body)),S(c)&&!x()){const d=M();return ie.warn(d),ct(d)}return n(r,a)},ie.info("order request interceptor installed (Apple Pay device guard)")}const L="sirsoft-pay_nhnkcp",ce="__kcpOcReceiptInjectorInstalled",de="kcp-oc-receipt-btn",lt=/^\/shop\/orders\/([^/]+)\/complete$/;function le(){return localStorage.getItem("auth_token")}async function ut(e){const t=le();if(!t)return null;try{const n=await fetch(`/api/modules/sirsoft-ecommerce/user/orders/${e}`,{headers:{Authorization:`Bearer ${t}`,Accept:"application/json"}});return n.ok?(await n.json())?.data?.payment??null:null}catch{return null}}async function O(e){const t=le();if(!t)return null;try{const n=await fetch(`/api/plugins/${L}/user/orders/${e}/receipt`,{headers:{Authorization:`Bearer ${t}`,Accept:"application/json"}});return n.ok?await n.json():null}catch{return null}}function ue(e,t,n){const o=document.createElement("button");return o.type="button",o.className=t,o.textContent=e,o.addEventListener("click",()=>n(o)),o}function pt(e){if(!e)return!1;const t=Array.from(document.querySelectorAll("div"));for(const n of t){const o=Array.from(n.children).filter(s=>s instanceof HTMLElement&&s.tagName==="SPAN");if(o.length<2)continue;const r=o[0].textContent?.trim();if(r!=="결제 방법"&&r!=="결제수단"&&r!=="결제 방식")continue;const a=o[o.length-1];return a.textContent?.trim()===e?(n.dataset.nhnkcpPaymentMethodRow="true",!0):(a.textContent=e,a.dataset.nhnkcpPaymentMethodPatched="true",n.dataset.nhnkcpPaymentMethodRow="true",!0)}return!1}async function mt(e){if(document.getElementById(de))return;const t=await ut(e);if(!t||t.pg_provider!=="nhnkcp"||!t.transaction_id||!t.paid_at)return;const n=Array.from(document.querySelectorAll('button[type="button"]')).find(c=>c.className.includes("bg-blue-600"));if(!n?.parentElement)return;const o=await O(e);pt(o?.payment_method_display_label);const r=n.parentElement,a=ue("영수증 조회",n.className.replace(/bg-blue-\d+/g,"bg-green-600").replace(/hover:bg-blue-\d+/g,"hover:bg-green-700"),async c=>{c.disabled=!0,c.textContent="로딩 중...";const d=await O(e);if(c.disabled=!1,c.textContent="영수증 조회",d){const l=window.KcpReceiptPopup;l&&new l({url:d.reLine truncated
|
||||
//# sourceMappingURL=plugin.iife.js.map
|
||||
@@ -263,6 +263,17 @@ export function installAdminPaymentMethodBrandInjector(): void {
|
||||
origPush(...args);
|
||||
window.setTimeout(() => onRouteChange(), 200);
|
||||
};
|
||||
|
||||
// replaceState 도 후킹한다 — 환경설정 화면의 탭 전환은 pushState 가 아니라
|
||||
// replaceState 로 URL 만 바꾼다(실측: 탭 왕복 1회에 push 0 / replace 2). pushState 만
|
||||
// 후킹하면 다른 탭에 갔다 돌아왔을 때 onRouteChange 가 발화하지 않아 배지가 사라진 채로
|
||||
// 남는다(행은 그대로 렌더되므로 화면상 아이콘만 회색으로 되돌아간다).
|
||||
const origReplace = history.replaceState.bind(history);
|
||||
history.replaceState = (...args: Parameters<typeof history.replaceState>) => {
|
||||
origReplace(...args);
|
||||
window.setTimeout(() => onRouteChange(), 200);
|
||||
};
|
||||
|
||||
window.addEventListener('popstate', () => window.setTimeout(() => onRouteChange(), 200));
|
||||
}
|
||||
|
||||
|
||||
@@ -12,6 +12,7 @@
|
||||
|
||||
### Fixed
|
||||
|
||||
- 이커머스 관리자 주문설정에서 다른 탭에 갔다 돌아오면 간편결제 항목의 브랜드 색상 배지가 사라지고 회색 기본 아이콘으로 남던 문제를 수정했습니다. 화면을 새로고침해야만 다시 표시됐습니다.
|
||||
- 결제 취소 기록과 환불 금액 오류 안내에 원화 단위가 고정 표기되던 문제를 수정했습니다. 이제 실제 결제 통화로 표시됩니다.
|
||||
- 쇼핑몰 주소를 기본값이 아닌 값으로 바꾸거나 주소 없이 운영하는 상점에서, 결제를 마치거나 결제에 실패한 구매자가 존재하지 않는 페이지로 이동하던 문제를 수정했습니다. 이동 주소가 기본 주소로 고정돼 있었기 때문이며, 이제 상점 주소 설정을 따라갑니다. 이미 운영 중인 사이트도 업데이트 시 자동으로 반영되며, 이동 주소를 직접 입력해 두었다면 그 값은 그대로 유지됩니다. (#85 @hwaryeon1234 님께서 제보해주셨습니다.)
|
||||
- 이 플러그인이 설치된 사이트에서 관리자 주문 목록의 '일부취소' 표시와 적립예정 포인트·마일리지 사용 금액, 주문상품의 추가옵션 요약이 보이지 않던 문제를 수정했습니다. 결제 정보 칸에 테스트결제 표시를 덧붙이는 과정에서 목록 표 구성 전체를 옛 버전으로 되돌려 놓고 있었습니다.
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"$schema": "https://json-schema.org/draft/2020-12/schema",
|
||||
"identifier": "sirsoft-pay_nicepayments",
|
||||
"version": "1.0.0",
|
||||
"version": "1.0.1",
|
||||
"components": {
|
||||
"basic": [],
|
||||
"composite": [],
|
||||
|
||||
@@ -1 +1,2 @@
|
||||
(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
|
||||
(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 _=window.location.origin+l.sign_data_url,u=typeof localStorage<"u"?localStorage.getItem("auth_token"):null,te={"Content-Type":"application/json","X-Requested-With":"XMLHttpRequest",Accept:"application/json"};u&&(te.Authorization=`Bearer ${u}`);const ne=await fetch(_,{method:"POST",credentials:"include",headers:te,body:JSON.stringify({amt:n.amount,moid:n.order_number,buyer_email:n.customer_email??"",buyer_phone:n.customer_phone??""})});if(!ne.ok)throw new Error("SignData 생성에 실패했습니다.");const L=await ne.json(),ae=window.location.origin+ye,M=typeof o=="string"&&o.startsWith("nicepay_"),oe=M?"CARD":{card:"CARD",vbank:"VBANK",bank:"BANK",phone:"CELLPHONE"}[o??"card"]??"CARD",c={PayMethod:oe,GoodsName:n.order_name,Amt:String(n.amount),MID:L.mid,Moid:n.order_number,BuyerName:n.customer_name??"",BuyerEmail:n.customer_email??"",BuyerTel:n.customer_phone??"",ReturnURL:ae,EdiDate:L.ediDate,SignData:L.signData,CharSet:"utf-8",GoodsCl:"1",DirectShowOpt:"",DirectEasyPay:"",NicepayReserved:"",EasyPayMethod:"",MallReserved:"",MallReserved1:""};oe==="CELLPHONE"&&(c.GoodsCl=n.goods_cl??"1");const ft=l.useEscrow&&!M;if(c.TransType=ft?"1":"0",M)switch(c.DirectShowOpt="CARD",c.MallReserved=`nicepay_easy_pay_method=${encodeURIComponent(o)}`,c.MallReserved1=o,o){case"nicepay_naverpay":c.DirectEasyPay="E020",c.EasyPayMethod="E020=CARD";break;case"nicepay_kakaopay":c.NicepayReserved="DirectKakao=Y";break;case"nicepay_samsungpay":c.DirectEasyPay="E021";break;case"nicepay_applepay":c.DirectEasyPay="E025";break;case"nicepay_payco":c.NicepayReserved="DirectPayco=Y";break;case"nicepay_skpay":c.NicepayReserved="DirectPay11=Y";break;case"nicepay_ssgpay":c.DirectEasyPay="E007";break;case"nicepay_lpay":c.DirectEasyPay="E018";break}try{const m=(await i.api.get(`/modules/sirsoft-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
|
||||
+11
@@ -272,6 +272,17 @@ export function installAdminPaymentMethodBrandInjector(): void {
|
||||
origPush(...args);
|
||||
window.setTimeout(() => onRouteChange(), 200);
|
||||
};
|
||||
|
||||
// replaceState 도 후킹한다 — 환경설정 화면의 탭 전환은 pushState 가 아니라
|
||||
// replaceState 로 URL 만 바꾼다(실측: 탭 왕복 1회에 push 0 / replace 2). pushState 만
|
||||
// 후킹하면 다른 탭에 갔다 돌아왔을 때 onRouteChange 가 발화하지 않아 배지가 사라진 채로
|
||||
// 남는다(행은 그대로 렌더되므로 화면상 아이콘만 회색으로 되돌아간다).
|
||||
const origReplace = history.replaceState.bind(history);
|
||||
history.replaceState = (...args: Parameters<typeof history.replaceState>) => {
|
||||
origReplace(...args);
|
||||
window.setTimeout(() => onRouteChange(), 200);
|
||||
};
|
||||
|
||||
window.addEventListener('popstate', () => window.setTimeout(() => onRouteChange(), 200));
|
||||
}
|
||||
|
||||
|
||||
@@ -1,2 +1,2 @@
|
||||
(function(){"use strict";function b(t){return new Promise((r,o)=>{if(document.querySelector(`script[src="${t}"]`)){r();return}const e=document.createElement("script");e.src=t,e.async=!0,e.onload=()=>r(),e.onerror=()=>o(new Error(`Failed to load script: ${t}`)),document.head.appendChild(e)})}function C(t,r){if(!t.order_sheet_mode||!r)return{method:"CARD",easyPay:null};const o=(t.enabled_methods??[]).find(e=>e.id===r);return o?{method:o.method,easyPay:o.easy_pay_provider}:{method:"CARD",easyPay:null}}function p(t){if(t==="on")return!0;if(t==="off")return!1}function E(t,r){const o={validHours:t.vbank?.valid_hours??24},e=t.vbank?.cash_receipt_type??"";e&&(o.cashReceipt={type:e});const s=p(t.use_escrow);return s!==void 0&&(o.useEscrow=s),o}function w(t,r,o){if(r.use_escrow==="off")return;const e=o.escrow_products??[];e.length>0&&(t.escrowProducts=e)}async function R(t,r){const o=t.params||{},{pgPaymentData:e}=o;if(!e){console.error("[sirsoft-tosspayments] pgPaymentData is required");return}const s=window.G7Core,l=o.paymentMethod??s?.state?.getLocal?.()?.paymentMethod;try{const n=await s.api.get("/modules/sirsoft-ecommerce/payments/client-config/tosspayments");if(!n.data){console.error("[sirsoft-tosspayments] Failed to fetch client config",n);return}const a=n.data;if(window.TossPayments||await b(a.sdk_url),window.TossPayments||await new Promise(u=>setTimeout(u,100)),!window.TossPayments){console.error("[sirsoft-tosspayments] TossPayments SDK not available");return}const T=window.TossPayments(a.client_key).payment({customerKey:e.customer_key??window.TossPayments.ANONYMOUS}),f=e.currency??"KRW",{method:d,easyPay:y}=C(a,l);if(f!=="KRW"&&(d!=="CARD"||y!==null)){console.warn("[sirsoft-tosspayments] non-KRW currency supports card only",{currency:f,method:d}),s?.state?.setLocal?.({paymentErrorMessage:s?.t?.("sirsoft-tosspayments.errors.non_krw_method")??"This payment method is available for KRW only.",isSubmittingOrder:!1}),s?.modal?.open?.("tosspayments_payment_error_modal");return}const v=window.location.origin,c={method:d,amount:{currency:f,value:e.amount},orderId:e.order_number,orderName:e.order_name,successUrl:v+a.callback_urls.success,failUrl:v+a.callback_urls.fail,customerEmail:e.customer_email??void 0,customerName:e.customer_name??void 0,customerMobilePhone:e.customer_phone??void 0};if(d==="CARD")c.card={flowMode:"DEFAULT",useCardPoint:!1,useAppCardOnly:!1},y&&(c.card.flowMode="DIRECT",c.card.easyPay=y);else if(d==="VIRTUAL_ACCOUNT")c.virtualAccount=E(a,e),w(c,a,e);else if(d==="TRANSFER"){const u=p(a.use_escrow);u!==void 0&&(c.transfer={useEscrow:u}),w(c,a,e)}await T.requestPayment(c)}catch(n){if(console.error("[sirsoft-tosspayments] requestPayment error",n),n?.code==="USER_CANCEL"){console.info("[sirsoft-tosspayments] Payment cancelled by user");try{await s.api.post(`/modules/sirsoft-ecommerce/orders/${e.order_number}/cancel-payment`,{cancel_code:n.code,cancel_message:n.message})}catch(P){console.warn("[sirsoft-tosspayments] Failed to record cancellation",P)}s?.state?.setLocal?.({isSubmittingOrder:!1}),s?.modal?.open?.("tosspayments_payment_cancel_modal");return}const a=n?.message??"Unknown error";s?.state?.setLocal?.({paymentErrorMessage:a,isSubmittingOrder:!1}),s?.modal?.open?.("tosspayments_payment_error_modal")}}const _={requestPayment:R},i="sirsoft-tosspayments",m={info:(...t)=>console.info(`[${i}]`,...t),warn:(...t)=>console.warn(`[${i}]`,...t),error:(...t)=>console.error(`[${i}]`,...t)};function h(){const t=window.G7Core;if(!t)return 0;const r=t.getActionDispatcher;if(typeof r!="function")return 0;const o=r();if(!o||typeof o.registerHandler!="function")return 0;let e=0;for(const[s,l]of Object.entries(_)){const n=`${i}.${s}`;o.registerHandler(n,l,{category:"plugin",source:i}),e++}return e}function g(){const t=()=>{const r=h();if(r>0){m.info(`${r} handler(s) registered`);return}let o=0;const e=50,s=setInterval(()=>{o++;const l=h();if(l>0){clearInterval(s),m.info(`${l} handler(s) registered (after ${o} retries)`);return}o>=e&&(clearInterval(s),m.warn("ActionDispatcher not available after timeout"))},100)};document.readyState==="loading"?document.addEventListener("DOMContentLoaded",t):t()}g(),window.__SirsoftTosspayments={identifier:i,handlers:Object.keys(_),initPlugin:g}})();
|
||||
(function(){"use strict";function O(e){return new Promise((t,s)=>{if(document.querySelector(`script[src="${e}"]`)){t();return}const n=document.createElement("script");n.src=e,n.async=!0,n.onload=()=>t(),n.onerror=()=>s(new Error(`Failed to load script: ${e}`)),document.head.appendChild(n)})}function $(e,t){if(!e.order_sheet_mode||!t)return{method:"CARD",easyPay:null};const s=(e.enabled_methods??[]).find(n=>n.id===t);return s?{method:s.method,easyPay:s.easy_pay_provider}:{method:"CARD",easyPay:null}}function T(e){if(e==="on")return!0;if(e==="off")return!1}function q(e,t){const s={validHours:e.vbank?.valid_hours??24},n=e.vbank?.cash_receipt_type??"";n&&(s.cashReceipt={type:n});const o=T(e.use_escrow);return o!==void 0&&(s.useEscrow=o),s}function A(e,t,s){if(t.use_escrow==="off")return;const n=s.escrow_products??[];n.length>0&&(e.escrowProducts=n)}async function F(e,t){const s=e.params||{},{pgPaymentData:n}=s;if(!n){console.error("[sirsoft-tosspayments] pgPaymentData is required");return}const o=window.G7Core,r=s.paymentMethod??o?.state?.getLocal?.()?.paymentMethod;try{const a=await o.api.get("/modules/sirsoft-ecommerce/payments/client-config/tosspayments");if(!a.data){console.error("[sirsoft-tosspayments] Failed to fetch client config",a);return}const i=a.data;if(window.TossPayments||await O(i.sdk_url),window.TossPayments||await new Promise(m=>setTimeout(m,100)),!window.TossPayments){console.error("[sirsoft-tosspayments] TossPayments SDK not available");return}const te=window.TossPayments(i.client_key).payment({customerKey:n.customer_key??window.TossPayments.ANONYMOUS}),g=n.currency??"KRW",{method:d,easyPay:b}=$(i,r);if(g!=="KRW"&&(d!=="CARD"||b!==null)){console.warn("[sirsoft-tosspayments] non-KRW currency supports card only",{currency:g,method:d}),o?.state?.setLocal?.({paymentErrorMessage:o?.t?.("sirsoft-tosspayments.errors.non_krw_method")??"This payment method is available for KRW only.",isSubmittingOrder:!1}),o?.modal?.open?.("tosspayments_payment_error_modal");return}const D=window.location.origin,c={method:d,amount:{currency:g,value:n.amount},orderId:n.order_number,orderName:n.order_name,successUrl:D+i.callback_urls.success,failUrl:D+i.callback_urls.fail,customerEmail:n.customer_email??void 0,customerName:n.customer_name??void 0,customerMobilePhone:n.customer_phone??void 0};if(d==="CARD")c.card={flowMode:"DEFAULT",useCardPoint:!1,useAppCardOnly:!1},b&&(c.card.flowMode="DIRECT",c.card.easyPay=b);else if(d==="VIRTUAL_ACCOUNT")c.virtualAccount=q(i,n),A(c,i,n);else if(d==="TRANSFER"){const m=T(i.use_escrow);m!==void 0&&(c.transfer={useEscrow:m}),A(c,i,n)}await te.requestPayment(c)}catch(a){if(console.error("[sirsoft-tosspayments] requestPayment error",a),a?.code==="USER_CANCEL"){console.info("[sirsoft-tosspayments] Payment cancelled by user");try{await o.api.post(`/modules/sirsoft-ecommerce/orders/${n.order_number}/cancel-payment`,{cancel_code:a.code,cancel_message:a.message})}catch(x){console.warn("[sirsoft-tosspayments] Failed to record cancellation",x)}o?.state?.setLocal?.({isSubmittingOrder:!1}),o?.modal?.open?.("tosspayments_payment_cancel_modal");return}const i=a?.message??"Unknown error";o?.state?.setLocal?.({paymentErrorMessage:i,isSubmittingOrder:!1}),o?.modal?.open?.("tosspayments_payment_error_modal")}}const v={requestPayment:F},U="sirsoft-tosspayments",E="__tossAdminPaymentMethodBrandInjectorInstalled",S="__tossAdminPaymentMethodBrandSyncListenerAttached",B=/^\/admin\/ecommerce\/settings\/?$/,L='[data-toss-admin-payment-brand-mark="true"]',K=200,G=120,H=[{id:"toss_tosspay",labels:["토스페이 (토스페이먼츠)","토스페이 간편결제 — 토스페이먼츠를 통해 처리","TossPay (TossPayments)","TossPay easy payment — processed via TossPayments"],shortLabels:[],markLines:["T"],markClassName:"bg-blue-500 text-white"},{id:"toss_kakaopay",labels:["카카오페이 (토스페이먼츠)","카카오페이 간편결제 — 토스페이먼츠를 통해 처리","KakaoPay (TossPayments)","KakaoPay easy payment — processed via TossPayments"],shortLabels:[],markLines:["K"],markClassName:"bg-yellow-400 text-gray-950"},{id:"toss_naverpay",labels:["네이버페이 (토스페이먼츠)","네이버페이 간편결제 — 토스페이먼츠를 통해 처리","NaverPay (TossPayments)","NaverPay easy payment — processed via TossPayments"],shortLabels:[],markLines:["N"],markClassName:"bg-green-500 text-white"},{id:"toss_payco",labels:["페이코 (토스페이먼츠)","페이코 간편결제 — 토스페이먼츠를 통해 처리","PAYCO (TossPayments)","PAYCO easy payment — processed via TossPayments"],shortLabels:[],markLines:["P"],markClassName:"bg-red-500 text-white"},{id:"toss_samsungpay",labels:["삼성페이 (토스페이먼츠)","삼성페이 간편결제 — 토스페이먼츠를 통해 처리","Samsung Pay (TossPayments)","Samsung Pay easy payment — processed via TossPayments"],shortLabels:[],markLines:["S"],markClassName:"bg-blue-600 text-white"}];let M=null,u=null,y=!1;function Y(Line truncated
|
||||
//# sourceMappingURL=plugin.iife.js.map
|
||||
+138
@@ -0,0 +1,138 @@
|
||||
/**
|
||||
* 관리자 주문설정 브랜드 마크 주입 회귀.
|
||||
*
|
||||
* 배경: #475 "확장 결제수단 1급화" 가 nicepayments·nhnkcp·kginicis 에 관리자 브랜드
|
||||
* injector 를 도입할 때 토스는 전환 대상에서 빠졌다(그 커밋에 tosspayments 파일 0건).
|
||||
* 관리자 레이아웃은 아이콘 열을 `Icon name={{$method._cached_icon}}` 하나로만 그리므로,
|
||||
* injector 가 없는 플러그인의 결제수단은 브랜드 배지 없이 회색 기본 아이콘으로 남는다.
|
||||
*/
|
||||
import { afterEach, beforeEach, describe, expect, it } from 'vitest';
|
||||
import {
|
||||
installAdminPaymentMethodBrandInjector,
|
||||
resetAdminPaymentMethodBrandInjectorForTests,
|
||||
syncRenderedAdminPaymentMethodBrands,
|
||||
} from '../adminPaymentMethodBrandInjector';
|
||||
|
||||
function desktopItem(testId: string, title: string, description: string): string {
|
||||
return `
|
||||
<div class="flex-center border rounded-lg p-3 gap-4" data-test-item="${testId}">
|
||||
<div data-drag-handle="true"><svg data-drag-icon="true"></svg></div>
|
||||
<svg data-original-icon="true"></svg>
|
||||
<div class="flex-1 min-w-0">
|
||||
<div class="flex-center gap-2">
|
||||
<span class="font-medium text-gray-900 dark:text-gray-100">${title}</span>
|
||||
</div>
|
||||
<span class="text-label-subtle">${description}</span>
|
||||
</div>
|
||||
<div class="row-stack">
|
||||
<span>PG사</span>
|
||||
<select></select>
|
||||
</div>
|
||||
</div>
|
||||
`;
|
||||
}
|
||||
|
||||
function mobileItem(testId: string, title: string): string {
|
||||
return `
|
||||
<div class="excel-card" data-test-item="${testId}">
|
||||
<div class="excel-card-header">
|
||||
<div class="flex-center gap-3 flex-1 min-w-0">
|
||||
<div data-drag-handle="true"><svg data-drag-icon="true"></svg></div>
|
||||
<svg data-original-icon="true"></svg>
|
||||
<span class="font-medium text-gray-900 dark:text-gray-100 truncate">${title}</span>
|
||||
</div>
|
||||
</div>
|
||||
<div class="excel-card-body">
|
||||
<div class="row-stack"><label>PG사</label><select></select></div>
|
||||
</div>
|
||||
</div>
|
||||
`;
|
||||
}
|
||||
|
||||
describe('adminPaymentMethodBrandInjector (tosspayments)', () => {
|
||||
beforeEach(() => {
|
||||
document.documentElement.lang = 'ko';
|
||||
window.history.pushState({}, '', '/admin/ecommerce/settings?tab=order_settings');
|
||||
document.body.innerHTML = `
|
||||
${desktopItem('toss-naverpay', '네이버페이 (토스페이먼츠)', '네이버페이 간편결제 — 토스페이먼츠를 통해 처리')}
|
||||
${mobileItem('toss-kakaopay', '카카오페이 (토스페이먼츠)')}
|
||||
${desktopItem('nice-naverpay', '네이버페이 (나이스페이먼츠)', '네이버페이로 결제 (나이스페이먼츠)')}
|
||||
${desktopItem('toss-card', '신용카드 (토스페이먼츠)', '신용·체크카드로 결제 — 토스페이먼츠를 통해 처리')}
|
||||
`;
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
resetAdminPaymentMethodBrandInjectorForTests();
|
||||
document.body.innerHTML = '';
|
||||
});
|
||||
|
||||
it('토스 간편결제 행의 기본 아이콘을 브랜드 배지로 바꾼다', () => {
|
||||
expect(syncRenderedAdminPaymentMethodBrands()).toBe(true);
|
||||
|
||||
const naverpay = document.querySelector<HTMLElement>('[data-test-item="toss-naverpay"]');
|
||||
expect(naverpay?.dataset.tossAdminPaymentMethod).toBe('toss_naverpay');
|
||||
expect(naverpay?.querySelector('[data-toss-admin-payment-brand-mark="true"]')?.textContent).toBe('N');
|
||||
// 원래 아이콘은 치환되고, 드래그 핸들 아이콘은 남아야 한다
|
||||
expect(naverpay?.querySelector('[data-original-icon="true"]')).toBeNull();
|
||||
expect(naverpay?.querySelector('[data-drag-icon="true"]')).not.toBeNull();
|
||||
});
|
||||
|
||||
it('모바일 카드 뷰에서도 동일하게 주입한다', () => {
|
||||
expect(syncRenderedAdminPaymentMethodBrands()).toBe(true);
|
||||
|
||||
const kakaopay = document.querySelector<HTMLElement>('[data-test-item="toss-kakaopay"]');
|
||||
expect(kakaopay?.dataset.tossAdminPaymentMethod).toBe('toss_kakaopay');
|
||||
expect(kakaopay?.querySelector('[data-toss-admin-payment-brand-mark="true"]')?.textContent).toBe('K');
|
||||
});
|
||||
|
||||
it('다른 PG 의 같은 브랜드 행은 건드리지 않는다 (플러그인 간 침범 금지)', () => {
|
||||
syncRenderedAdminPaymentMethodBrands();
|
||||
|
||||
const nice = document.querySelector<HTMLElement>('[data-test-item="nice-naverpay"]');
|
||||
expect(nice?.dataset.tossAdminPaymentMethod).toBeUndefined();
|
||||
expect(nice?.querySelector('[data-original-icon="true"]')).not.toBeNull();
|
||||
});
|
||||
|
||||
it('브랜드가 아닌 수단(카드)은 기본 아이콘을 유지한다', () => {
|
||||
syncRenderedAdminPaymentMethodBrands();
|
||||
|
||||
const card = document.querySelector<HTMLElement>('[data-test-item="toss-card"]');
|
||||
expect(card?.dataset.tossAdminPaymentMethod).toBeUndefined();
|
||||
expect(card?.querySelector('[data-original-icon="true"]')).not.toBeNull();
|
||||
});
|
||||
|
||||
it('주문설정 화면이 아니면 아무것도 바꾸지 않는다', () => {
|
||||
window.history.pushState({}, '', '/admin/ecommerce/settings?tab=shipping');
|
||||
|
||||
expect(syncRenderedAdminPaymentMethodBrands()).toBe(false);
|
||||
expect(document.querySelector('[data-toss-admin-payment-brand-mark="true"]')).toBeNull();
|
||||
});
|
||||
|
||||
/**
|
||||
* 탭 전환 후 복귀 시 배지 재주입 (브라우저 실측으로 발견한 회귀).
|
||||
*
|
||||
* 환경설정 화면의 탭 전환은 pushState 가 아니라 **replaceState** 로 URL 만 바꾼다
|
||||
* (탭 왕복 1회에 push 0 / replace 2 실측). pushState/popstate 만 후킹하던 기존 구현은
|
||||
* 다른 탭에 갔다 돌아왔을 때 onRouteChange 가 발화하지 않아, 행은 다시 렌더되는데
|
||||
* 배지만 사라진 채로 남았다 — 사용자에게는 아이콘이 회색으로 되돌아간 것으로 보인다.
|
||||
*/
|
||||
it('replaceState 로 탭을 전환했다 돌아와도 배지를 재주입한다', async () => {
|
||||
installAdminPaymentMethodBrandInjector();
|
||||
expect(document.querySelectorAll('[data-toss-admin-payment-brand-mark="true"]').length).toBeGreaterThan(0);
|
||||
|
||||
// 다른 탭으로 이동 (replaceState) — 화면이 갈아끼워지며 배지가 사라진 상태를 재현
|
||||
window.history.replaceState({}, '', '/admin/ecommerce/settings?tab=shipping');
|
||||
document.body.innerHTML = '';
|
||||
await new Promise((r) => setTimeout(r, 300));
|
||||
|
||||
// 주문설정으로 복귀 (replaceState) + 행 재렌더
|
||||
document.body.innerHTML = desktopItem('toss-naverpay', '네이버페이 (토스페이먼츠)', '네이버페이 간편결제 — 토스페이먼츠를 통해 처리');
|
||||
window.history.replaceState({}, '', '/admin/ecommerce/settings?tab=order_settings');
|
||||
await new Promise((r) => setTimeout(r, 600));
|
||||
|
||||
expect(
|
||||
document.querySelectorAll('[data-toss-admin-payment-brand-mark="true"]').length,
|
||||
'replaceState 복귀 후 배지가 재주입되지 않았다',
|
||||
).toBeGreaterThan(0);
|
||||
});
|
||||
});
|
||||
+291
@@ -0,0 +1,291 @@
|
||||
/**
|
||||
* 관리자 주문설정 결제수단 목록의 브랜드 마크 주입.
|
||||
*
|
||||
* 관리자 레이아웃(`_payment_methods_list.json` / `_payment_methods_cards.json`)은 결제수단
|
||||
* 아이콘 열을 `Icon name={{$method._cached_icon}}` 하나로만 그린다 — 카탈로그의
|
||||
* `_cached_brand_mark` 를 읽는 노드가 없다(그 값을 렌더하는 곳은 사용자 템플릿 체크아웃뿐).
|
||||
* 그래서 각 PG 플러그인이 자기 결제수단 행의 아이콘을 브랜드 배지로 치환하는 관리자 전용
|
||||
* injector 를 직접 싣는다. 토스에만 이 파일이 없어 간편결제가 회색 기본 아이콘으로 보였다.
|
||||
*
|
||||
* 구조는 다른 PG 플러그인(nicepayments·kginicis)의 동명 파일과 동일하게 맞춘다 — 행 판별은
|
||||
* 라벨 텍스트, 치환 대상은 드래그 핸들/컨트롤을 제외한 첫 아이콘, 재적용은 MutationObserver
|
||||
* + 폴링이다. 배지 색·문자는 같은 브랜드가 어느 PG 를 통하든 같아야 하므로 서버측
|
||||
* `RegisterTossPaymentMethodsListener::METHOD_PRESENTATION` 의 `brand_mark` 와 값을 맞춘다.
|
||||
*/
|
||||
const PLUGIN_ID = 'sirsoft-tosspayments';
|
||||
const FLAG = '__tossAdminPaymentMethodBrandInjectorInstalled';
|
||||
const LISTENER_FLAG = '__tossAdminPaymentMethodBrandSyncListenerAttached';
|
||||
const ADMIN_SETTINGS_RE = /^\/admin\/ecommerce\/settings\/?$/;
|
||||
const MARK_SELECTOR = '[data-toss-admin-payment-brand-mark="true"]';
|
||||
const SYNC_RETRY_INTERVAL_MS = 200;
|
||||
const SYNC_RETRY_ATTEMPTS = 120;
|
||||
|
||||
interface AdminPaymentBrandDefinition {
|
||||
id: string;
|
||||
labels: string[];
|
||||
shortLabels: string[];
|
||||
markLines: string[];
|
||||
markClassName: string;
|
||||
}
|
||||
|
||||
const ADMIN_PAYMENT_BRAND_DEFINITIONS: AdminPaymentBrandDefinition[] = [
|
||||
{
|
||||
id: 'toss_tosspay',
|
||||
labels: ['토스페이 (토스페이먼츠)', '토스페이 간편결제 — 토스페이먼츠를 통해 처리', 'TossPay (TossPayments)', 'TossPay easy payment — processed via TossPayments'],
|
||||
shortLabels: [],
|
||||
markLines: ['T'],
|
||||
markClassName: 'bg-blue-500 text-white',
|
||||
},
|
||||
{
|
||||
id: 'toss_kakaopay',
|
||||
labels: ['카카오페이 (토스페이먼츠)', '카카오페이 간편결제 — 토스페이먼츠를 통해 처리', 'KakaoPay (TossPayments)', 'KakaoPay easy payment — processed via TossPayments'],
|
||||
shortLabels: [],
|
||||
markLines: ['K'],
|
||||
markClassName: 'bg-yellow-400 text-gray-950',
|
||||
},
|
||||
{
|
||||
id: 'toss_naverpay',
|
||||
labels: ['네이버페이 (토스페이먼츠)', '네이버페이 간편결제 — 토스페이먼츠를 통해 처리', 'NaverPay (TossPayments)', 'NaverPay easy payment — processed via TossPayments'],
|
||||
shortLabels: [],
|
||||
markLines: ['N'],
|
||||
markClassName: 'bg-green-500 text-white',
|
||||
},
|
||||
{
|
||||
id: 'toss_payco',
|
||||
labels: ['페이코 (토스페이먼츠)', '페이코 간편결제 — 토스페이먼츠를 통해 처리', 'PAYCO (TossPayments)', 'PAYCO easy payment — processed via TossPayments'],
|
||||
shortLabels: [],
|
||||
markLines: ['P'],
|
||||
markClassName: 'bg-red-500 text-white',
|
||||
},
|
||||
{
|
||||
id: 'toss_samsungpay',
|
||||
labels: ['삼성페이 (토스페이먼츠)', '삼성페이 간편결제 — 토스페이먼츠를 통해 처리', 'Samsung Pay (TossPayments)', 'Samsung Pay easy payment — processed via TossPayments'],
|
||||
shortLabels: [],
|
||||
markLines: ['S'],
|
||||
markClassName: 'bg-blue-600 text-white',
|
||||
},
|
||||
];
|
||||
|
||||
let 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 isOrderSettingsPage(): boolean {
|
||||
if (!ADMIN_SETTINGS_RE.test(window.location.pathname)) return false;
|
||||
|
||||
const tab = new URLSearchParams(window.location.search).get('tab');
|
||||
return tab === null || tab === '' || tab === 'order_settings';
|
||||
}
|
||||
|
||||
function classNameOf(element: Element): string {
|
||||
return element instanceof HTMLElement ? element.className : '';
|
||||
}
|
||||
|
||||
function comparableText(value: string | null | undefined): string {
|
||||
return (value ?? '')
|
||||
.replace(//g, '')
|
||||
.replace(/\s+/g, ' ')
|
||||
.trim();
|
||||
}
|
||||
|
||||
function isPaymentMethodItem(element: HTMLElement): boolean {
|
||||
const className = classNameOf(element);
|
||||
|
||||
return className.includes('excel-card')
|
||||
|| (className.includes('flex-center') && className.includes('border') && className.includes('gap-4'));
|
||||
}
|
||||
|
||||
function findTitleElement(item: HTMLElement): HTMLElement | null {
|
||||
return item.querySelector<HTMLElement>('.font-medium');
|
||||
}
|
||||
|
||||
function findDefinitionForItem(item: HTMLElement): AdminPaymentBrandDefinition | null {
|
||||
const title = comparableText(findTitleElement(item)?.textContent);
|
||||
const text = comparableText(item.textContent);
|
||||
|
||||
return ADMIN_PAYMENT_BRAND_DEFINITIONS.find((definition) => (
|
||||
definition.shortLabels.some((label) => title === label)
|
||||
|| definition.labels.some((label) => text.includes(label))
|
||||
)) ?? null;
|
||||
}
|
||||
|
||||
function findPaymentMethodItems(root: ParentNode): HTMLElement[] {
|
||||
return Array.from(root.querySelectorAll<HTMLElement>('div'))
|
||||
.filter(isPaymentMethodItem);
|
||||
}
|
||||
|
||||
function findPaymentIcon(item: HTMLElement): Element | null {
|
||||
const icons = Array.from(item.querySelectorAll<Element>('svg, [data-icon], i'));
|
||||
|
||||
return icons.find((element) => (
|
||||
!element.closest('[data-drag-handle]')
|
||||
&& !element.closest(MARK_SELECTOR)
|
||||
&& !element.closest('.row-stack, .excel-card-body, button, select, [role="switch"]')
|
||||
)) ?? null;
|
||||
}
|
||||
|
||||
function applyBrandMarkContent(mark: HTMLSpanElement, definition: AdminPaymentBrandDefinition): void {
|
||||
mark.dataset.tossAdminPaymentBrandMark = 'true';
|
||||
mark.dataset.tossAdminPaymentMethod = definition.id;
|
||||
mark.setAttribute('aria-hidden', 'true');
|
||||
mark.className = `inline-flex items-center justify-center rounded-lg font-bold ${definition.markClassName}`;
|
||||
mark.style.width = '32px';
|
||||
mark.style.height = '32px';
|
||||
mark.style.flex = '0 0 32px';
|
||||
mark.style.lineHeight = '1';
|
||||
mark.style.fontSize = definition.markLines.join('').length > 2 ? '9px' : '12px';
|
||||
|
||||
const expectedText = definition.markLines.join('');
|
||||
if (mark.textContent !== expectedText) {
|
||||
mark.textContent = definition.markLines[0] ?? '';
|
||||
}
|
||||
}
|
||||
|
||||
function createBrandMark(definition: AdminPaymentBrandDefinition): HTMLSpanElement {
|
||||
const mark = document.createElement('span');
|
||||
applyBrandMarkContent(mark, definition);
|
||||
|
||||
return mark;
|
||||
}
|
||||
|
||||
function syncBrandMark(item: HTMLElement, definition: AdminPaymentBrandDefinition): boolean {
|
||||
const existing = item.querySelector<HTMLElement>(MARK_SELECTOR);
|
||||
if (existing instanceof HTMLSpanElement) {
|
||||
item.dataset.tossAdminPaymentMethod = definition.id;
|
||||
applyBrandMarkContent(existing, definition);
|
||||
return true;
|
||||
}
|
||||
|
||||
const mark = createBrandMark(definition);
|
||||
const icon = findPaymentIcon(item);
|
||||
if (icon && icon.parentElement) {
|
||||
item.dataset.tossAdminPaymentMethod = definition.id;
|
||||
icon.replaceWith(mark);
|
||||
return true;
|
||||
}
|
||||
|
||||
const title = findTitleElement(item);
|
||||
if (title && title.parentElement) {
|
||||
item.dataset.tossAdminPaymentMethod = definition.id;
|
||||
title.parentElement.insertBefore(mark, title);
|
||||
return true;
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
export function syncRenderedAdminPaymentMethodBrands(root: ParentNode = document): boolean {
|
||||
if (typeof window === 'undefined' || typeof document === 'undefined') return false;
|
||||
if (!isOrderSettingsPage()) return false;
|
||||
|
||||
let matched = false;
|
||||
|
||||
findPaymentMethodItems(root).forEach((item) => {
|
||||
const definition = findDefinitionForItem(item);
|
||||
if (!definition) return;
|
||||
|
||||
if (syncBrandMark(item, definition)) {
|
||||
matched = true;
|
||||
}
|
||||
});
|
||||
|
||||
return matched;
|
||||
}
|
||||
|
||||
function queueSync(): void {
|
||||
if (syncQueued) return;
|
||||
syncQueued = true;
|
||||
|
||||
window.setTimeout(() => {
|
||||
syncQueued = false;
|
||||
syncRenderedAdminPaymentMethodBrands();
|
||||
}, 0);
|
||||
}
|
||||
|
||||
function stopRetries(): void {
|
||||
if (retryTimer === null) return;
|
||||
|
||||
window.clearInterval(retryTimer);
|
||||
retryTimer = null;
|
||||
}
|
||||
|
||||
function startSync(): void {
|
||||
if (!isOrderSettingsPage()) return;
|
||||
|
||||
stopRetries();
|
||||
syncRenderedAdminPaymentMethodBrands();
|
||||
|
||||
let attempts = 0;
|
||||
retryTimer = window.setInterval(() => {
|
||||
attempts += 1;
|
||||
syncRenderedAdminPaymentMethodBrands();
|
||||
|
||||
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 (isOrderSettingsPage()) {
|
||||
startSync();
|
||||
return;
|
||||
}
|
||||
|
||||
stopRetries();
|
||||
}
|
||||
|
||||
export function installAdminPaymentMethodBrandInjector(): void {
|
||||
if (typeof window === 'undefined' || typeof document === 'undefined') return;
|
||||
const w = windowRecord();
|
||||
if (w[FLAG]) return;
|
||||
w[FLAG] = true;
|
||||
|
||||
console.info(`[${PLUGIN_ID}] admin payment method brand 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);
|
||||
};
|
||||
|
||||
// replaceState 도 후킹한다 — 환경설정 화면의 탭 전환은 pushState 가 아니라
|
||||
// replaceState 로 URL 만 바꾼다(실측: 탭 왕복 1회에 push 0 / replace 2). pushState 만
|
||||
// 후킹하면 다른 탭에 갔다 돌아왔을 때 onRouteChange 가 발화하지 않아 배지가 사라진 채로
|
||||
// 남는다(행은 그대로 렌더되므로 화면상 아이콘만 회색으로 되돌아간다).
|
||||
const origReplace = history.replaceState.bind(history);
|
||||
history.replaceState = (...args: Parameters<typeof history.replaceState>) => {
|
||||
origReplace(...args);
|
||||
window.setTimeout(() => onRouteChange(), 200);
|
||||
};
|
||||
|
||||
window.addEventListener('popstate', () => window.setTimeout(() => onRouteChange(), 200));
|
||||
}
|
||||
|
||||
export function resetAdminPaymentMethodBrandInjectorForTests(): void {
|
||||
observer?.disconnect();
|
||||
observer = null;
|
||||
stopRetries();
|
||||
syncQueued = false;
|
||||
delete windowRecord()[FLAG];
|
||||
if (document.body) {
|
||||
delete ((document.body as HTMLElement & Record<string, unknown>)[LISTENER_FLAG]);
|
||||
}
|
||||
}
|
||||
@@ -6,6 +6,7 @@
|
||||
*/
|
||||
|
||||
import { handlerMap } from './handlers';
|
||||
import { installAdminPaymentMethodBrandInjector } from './adminPaymentMethodBrandInjector';
|
||||
|
||||
const PLUGIN_IDENTIFIER = 'sirsoft-tosspayments';
|
||||
|
||||
@@ -62,6 +63,10 @@ function registerHandlers(): number {
|
||||
* ActionDispatcher가 아직 준비되지 않았으면 최대 5초간 재시도합니다.
|
||||
*/
|
||||
function initPlugin(): void {
|
||||
// 관리자 주문설정의 브랜드 마크 주입 — 핸들러 등록 성공 여부와 무관하게 설치한다
|
||||
// (관리자 화면은 결제 핸들러를 쓰지 않으므로 ActionDispatcher 준비를 기다릴 이유가 없다).
|
||||
installAdminPaymentMethodBrandInjector();
|
||||
|
||||
const doInit = () => {
|
||||
const count = registerHandlers();
|
||||
|
||||
|
||||
+52
-10
@@ -23,21 +23,47 @@ class RegisterTossPaymentMethodsListener implements HookListenerInterface
|
||||
|
||||
private const PLUGIN_IDENTIFIER = 'sirsoft-tosspayments';
|
||||
|
||||
/** RegisterPgProviderListener 가 등록하는 PG 제공자 id 와 동일해야 한다. */
|
||||
private const PG_PROVIDER_ID = 'tosspayments';
|
||||
|
||||
/**
|
||||
* toss_* id → 아이콘·다국어 키.
|
||||
* toss_* id → 아이콘·브랜드 마크.
|
||||
*
|
||||
* @var array<string, array{icon:string}>
|
||||
* 간편결제 수단은 brand_mark 로 브랜드 색상 배지를 노출한다. 같은 브랜드는 어느 PG 를
|
||||
* 통하든 같은 배지로 보여야 하므로 text/class 값을 다른 PG 플러그인과 동일하게 맞춘다
|
||||
* (naverpay N/녹색, kakaopay K/노랑, samsungpay S/파랑, payco P/빨강). 미선언 시
|
||||
* 이커머스가 `_cached_brand_mark` 를 null 로 채워 회색 기본 아이콘만 표시된다.
|
||||
*
|
||||
* 카드·가상계좌·계좌이체·휴대폰은 브랜드가 아니라 결제 형태이므로 코어 빌트인 수단과
|
||||
* 동일하게 아이콘만 둔다.
|
||||
*
|
||||
* @var array<string, array{icon:string, brand_mark?:array{text:string, class:string}}>
|
||||
*/
|
||||
private const METHOD_PRESENTATION = [
|
||||
'toss_card' => ['icon' => 'credit-card'],
|
||||
'toss_virtual_account' => ['icon' => 'building-columns'],
|
||||
'toss_transfer' => ['icon' => 'money-bill-transfer'],
|
||||
'toss_mobile_phone' => ['icon' => 'mobile-screen-button'],
|
||||
'toss_tosspay' => ['icon' => 'wallet'],
|
||||
'toss_kakaopay' => ['icon' => 'wallet'],
|
||||
'toss_naverpay' => ['icon' => 'wallet'],
|
||||
'toss_payco' => ['icon' => 'wallet'],
|
||||
'toss_samsungpay' => ['icon' => 'mobile-screen-button'],
|
||||
'toss_tosspay' => [
|
||||
'icon' => 'wallet',
|
||||
'brand_mark' => ['text' => 'T', 'class' => 'bg-blue-500 text-white'],
|
||||
],
|
||||
'toss_kakaopay' => [
|
||||
'icon' => 'wallet',
|
||||
'brand_mark' => ['text' => 'K', 'class' => 'bg-yellow-400 text-gray-950'],
|
||||
],
|
||||
'toss_naverpay' => [
|
||||
'icon' => 'wallet',
|
||||
'brand_mark' => ['text' => 'N', 'class' => 'bg-green-500 text-white'],
|
||||
],
|
||||
'toss_payco' => [
|
||||
'icon' => 'wallet',
|
||||
'brand_mark' => ['text' => 'P', 'class' => 'bg-red-500 text-white'],
|
||||
],
|
||||
'toss_samsungpay' => [
|
||||
'icon' => 'mobile-screen-button',
|
||||
'brand_mark' => ['text' => 'S', 'class' => 'bg-blue-600 text-white'],
|
||||
],
|
||||
];
|
||||
|
||||
/**
|
||||
@@ -118,7 +144,7 @@ class RegisterTossPaymentMethodsListener implements HookListenerInterface
|
||||
$nameKey = "sirsoft-tosspayments::payment_methods.{$id}.name";
|
||||
$descriptionKey = "sirsoft-tosspayments::payment_methods.{$id}.description";
|
||||
|
||||
return [
|
||||
$entry = [
|
||||
'id' => $id,
|
||||
'name' => [
|
||||
'ko' => __($nameKey, [], 'ko'),
|
||||
@@ -131,8 +157,15 @@ class RegisterTossPaymentMethodsListener implements HookListenerInterface
|
||||
'icon' => self::METHOD_PRESENTATION[$id]['icon'] ?? 'credit-card',
|
||||
'source' => 'plugin:sirsoft-tosspayments',
|
||||
'defaults' => [
|
||||
// PG 선택 불필요 — payment_handler 정공법으로 토스 결제 흐름이 발화한다.
|
||||
'pg_provider' => null,
|
||||
// 토스 결제수단은 토스 결제창을 통해서만 처리되므로 PG 를 자기 자신으로 고정한다.
|
||||
// null 로 두면 코어가 PG 없는 결제수단으로 오인해 결제 실패 주문에 관리자 알림이
|
||||
// 발송되고 임시주문이 삭제되어 재결제가 막힌다(#475). 또한 관리자 화면이 "PG 고정"
|
||||
// 배지 대신 선택지가 비어 있는 PG 셀렉트를 그린다 — 토스 PG 는 자기 결제수단 id 를
|
||||
// supported_methods 로 선언하지 않으므로 고를 수 있는 항목이 하나도 없다.
|
||||
'pg_provider' => self::PG_PROVIDER_ID,
|
||||
'pg_locked' => true,
|
||||
'needs_pg' => true,
|
||||
'refund_method' => 'pg',
|
||||
'is_active' => false,
|
||||
'min_order_amount' => 0,
|
||||
'stock_deduction_timing' => 'payment_complete',
|
||||
@@ -141,6 +174,15 @@ class RegisterTossPaymentMethodsListener implements HookListenerInterface
|
||||
'core_payment_method' => self::TOSS_METHOD_MAP[$id]['core'],
|
||||
],
|
||||
];
|
||||
|
||||
// 브랜드 마크는 간편결제 수단에만 있다. 없는 수단에 null 키를 남기지 않는다 —
|
||||
// 이커머스 병합부가 `$definition['brand_mark'] ?? null` 로 읽으므로 결과는 같지만,
|
||||
// 키 유무가 곧 "브랜드 수단인가" 의 선언이라 다른 PG 플러그인과 형식을 맞춘다.
|
||||
if (isset(self::METHOD_PRESENTATION[$id]['brand_mark'])) {
|
||||
$entry['brand_mark'] = self::METHOD_PRESENTATION[$id]['brand_mark'];
|
||||
}
|
||||
|
||||
return $entry;
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
+106
-2
@@ -128,8 +128,9 @@ class RegisterTossPaymentMethodsListenerTest extends PluginTestCase
|
||||
// 가상계좌 → vbank, 간편결제 → card
|
||||
$this->assertSame('vbank', $byId['toss_virtual_account']['defaults']['core_payment_method']);
|
||||
$this->assertSame('card', $byId['toss_kakaopay']['defaults']['core_payment_method']);
|
||||
// PG 선택 불필요
|
||||
$this->assertNull($byId['toss_virtual_account']['defaults']['pg_provider']);
|
||||
// PG 는 토스로 고정된다 (#475 전환). 과거에는 null 이었고 그것이 관리자 화면의
|
||||
// 빈 PG 셀렉트와 서버측 "PG 없는 결제수단" 오인의 원인이었다.
|
||||
$this->assertSame('tosspayments', $byId['toss_virtual_account']['defaults']['pg_provider']);
|
||||
}
|
||||
|
||||
public function test_all_toggles_off_injects_nothing(): void
|
||||
@@ -140,4 +141,107 @@ class RegisterTossPaymentMethodsListenerTest extends PluginTestCase
|
||||
|
||||
$this->assertCount(3, $result);
|
||||
}
|
||||
|
||||
/**
|
||||
* 모든 토스 결제수단은 PG 를 자기 자신으로 고정 선언해야 한다 (#475 전환 누락 회귀).
|
||||
*
|
||||
* 배경: #475 가 확장 결제수단에 pg_locked/needs_pg/refund_method 선언을 도입할 때
|
||||
* 토스는 3일 먼저 들어와 있었음에도 전환 대상에서 빠졌다. 그 결과 pg_provider 가 null 인
|
||||
* 채로 needs_pg 만 참이 되어, 관리자 화면이 "PG 고정" 배지 대신 **선택지가 하나도 없는**
|
||||
* PG 셀렉트를 그렸다(토스 PG 는 toss_* id 를 supported_methods 로 선언하지 않는다).
|
||||
* 서버 쪽으로도 PG 없는 결제수단으로 오인되어 결제 실패 시 임시주문이 삭제될 수 있었다.
|
||||
*/
|
||||
public function test_all_methods_declare_pg_locked_to_self(): void
|
||||
{
|
||||
$this->mockSettings([
|
||||
'order_sheet_mode' => true,
|
||||
'method_card' => true,
|
||||
'method_virtual_account' => true,
|
||||
'method_transfer' => true,
|
||||
'method_mobile_phone' => true,
|
||||
'method_tosspay' => true,
|
||||
'method_kakaopay' => true,
|
||||
'method_naverpay' => true,
|
||||
'method_payco' => true,
|
||||
'method_samsungpay' => true,
|
||||
]);
|
||||
|
||||
$injected = collect($this->listener->injectTossMethods($this->builtinMethods()))
|
||||
->filter(fn ($m) => str_starts_with($m['id'] ?? '', 'toss_'));
|
||||
|
||||
$this->assertGreaterThan(0, $injected->count(), '토스 결제수단이 주입되지 않았다');
|
||||
|
||||
foreach ($injected as $method) {
|
||||
$defaults = $method['defaults'] ?? [];
|
||||
$id = $method['id'];
|
||||
|
||||
$this->assertSame('tosspayments', $defaults['pg_provider'] ?? null, "{$id}: PG 미고정");
|
||||
$this->assertTrue($defaults['pg_locked'] ?? false, "{$id}: pg_locked 미선언 — 관리자가 다른 PG 로 바꿀 수 있게 된다");
|
||||
$this->assertTrue($defaults['needs_pg'] ?? false, "{$id}: needs_pg 미선언");
|
||||
$this->assertSame('pg', $defaults['refund_method'] ?? null, "{$id}: refund_method 미선언");
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 간편결제 수단은 브랜드 마크를 선언해야 한다.
|
||||
*
|
||||
* 회귀 배경: 토스 수단만 brand_mark 를 선언하지 않아, 이커머스 병합부가
|
||||
* `_cached_brand_mark` 를 null 로 채우고 관리자·체크아웃 화면이 브랜드 배지 대신
|
||||
* 회색 기본 아이콘을 그렸다. 같은 브랜드가 다른 PG 를 통할 때와 다르게 보였다.
|
||||
*
|
||||
* 같은 브랜드는 어느 PG 를 통하든 같은 배지여야 하므로 text/class 를 함께 고정한다.
|
||||
*/
|
||||
public function test_easy_pay_methods_declare_brand_mark_consistent_with_other_pg(): void
|
||||
{
|
||||
$this->mockSettings([
|
||||
'order_sheet_mode' => true,
|
||||
'method_tosspay' => true,
|
||||
'method_kakaopay' => true,
|
||||
'method_naverpay' => true,
|
||||
'method_payco' => true,
|
||||
'method_samsungpay' => true,
|
||||
]);
|
||||
|
||||
$byId = collect($this->listener->injectTossMethods($this->builtinMethods()))->keyBy('id');
|
||||
|
||||
// 다른 PG 플러그인(nicepayments·nhnkcp)이 같은 브랜드에 쓰는 값과 동일해야 한다.
|
||||
$expected = [
|
||||
'toss_naverpay' => ['text' => 'N', 'class' => 'bg-green-500 text-white'],
|
||||
'toss_kakaopay' => ['text' => 'K', 'class' => 'bg-yellow-400 text-gray-950'],
|
||||
'toss_samsungpay' => ['text' => 'S', 'class' => 'bg-blue-600 text-white'],
|
||||
'toss_payco' => ['text' => 'P', 'class' => 'bg-red-500 text-white'],
|
||||
'toss_tosspay' => ['text' => 'T', 'class' => 'bg-blue-500 text-white'],
|
||||
];
|
||||
|
||||
foreach ($expected as $id => $mark) {
|
||||
$this->assertArrayHasKey($id, $byId, "{$id} 가 주입되지 않았다");
|
||||
$this->assertSame(
|
||||
$mark,
|
||||
$byId[$id]['brand_mark'] ?? null,
|
||||
"{$id} 의 브랜드 마크가 다른 PG 와 다르다 — 같은 브랜드가 PG 마다 달라 보인다"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 카드·가상계좌·계좌이체·휴대폰은 브랜드가 아니라 결제 형태이므로 마크를 두지 않는다.
|
||||
* (코어 빌트인 수단과 동일한 표현)
|
||||
*/
|
||||
public function test_non_brand_methods_have_no_brand_mark(): void
|
||||
{
|
||||
$this->mockSettings([
|
||||
'order_sheet_mode' => true,
|
||||
'method_card' => true,
|
||||
'method_virtual_account' => true,
|
||||
'method_transfer' => true,
|
||||
'method_mobile_phone' => true,
|
||||
]);
|
||||
|
||||
$byId = collect($this->listener->injectTossMethods($this->builtinMethods()))->keyBy('id');
|
||||
|
||||
foreach (['toss_card', 'toss_virtual_account', 'toss_transfer', 'toss_mobile_phone'] as $id) {
|
||||
$this->assertArrayHasKey($id, $byId, "{$id} 가 주입되지 않았다");
|
||||
$this->assertArrayNotHasKey('brand_mark', $byId[$id], "{$id} 는 브랜드 수단이 아니다");
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user