3 lines
33 KiB
JavaScript
3 lines
33 KiB
JavaScript
(function(){"use strict";function Ie(e){return/^https?:\/\//i.test(e)||e.startsWith("/api/")?e:e.startsWith("/plugins/")?`/api${e}`:e.startsWith("plugins/")?`/api/${e}`:e}function Re(e){return e.trim().slice(0,160)}async function Oe(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:Re(t)||"nicepay-window-closed"};try{const a=window.G7Core?.api;if(typeof a?.post=="function"){await a.post(e.closeReportUrl,n);return}await fetch(Ie(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 De(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 $e="/plugins/sirsoft-pay_nicepayments/payment/callback",Ge="https://web.nicepay.co.kr/v3/v3Payment.jsp";function Be(){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 z(e,t){const{pgPaymentData:n,paymentMethod:a}=e.params??{},r=window.__templateApp?.globalState?._local,o=a??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 p=s.data,u=Be();if(!u&&(await De(p.sdk_url),typeof window.goPay!="function")){i?.toast?.error?.("나이스페이먼츠 SDK를 불러올 수 없습니다. 잠시 후 다시 시도해주세요."),i?.state?.setLocal?.({isSubmittingOrder:!1,paymentMethod:o});return}const v=window.location.origin+p.sign_data_url,K=typeof localStorage<"u"?localStorage.getItem("auth_token"):null,y={"Content-Type":"application/json","X-Requested-With":"XMLHttpRequest",Accept:"application/json"};K&&(y.Authorization=`Bearer ${K}`);const g=await fetch(v,{method:"POST",credentials:"include",headers:y,body:JSON.stringify({amt:n.amount,moid:n.order_number})});if(!g.ok)throw new Error("SignData 생성에 실패했습니다.");const h=await g.json(),L=window.location.origin+$e,m=typeof o=="string"&&o.startsWith("nicepay_"),b=m?"CARD":{card:"CARD",vbank:"VBANK",bank:"BANK",phone:"CELLPHONE"}[o??"card"]??"CARD",l={PayMethod:b,GoodsName:n.order_name,Amt:String(n.amount),MID:h.mid,Moid:n.order_number,BuyerName:n.customer_name??"",BuyerEmail:n.customer_email??"",BuyerTel:n.customer_phone??"",ReturnURL:L,EdiDate:h.ediDate,SignData:h.signData,CharSet:"utf-8",GoodsCl:"1",DirectShowOpt:"",DirectEasyPay:"",NicepayReserved:"",EasyPayMethod:""};b==="CELLPHONE"&&(l.GoodsCl=n.goods_cl??"1");const c=p.useEscrow&&!m;if(l.TransType=c?"1":"0",m)switch(l.DirectShowOpt="CARD",o){case"nicepay_naverpay":l.DirectEasyPay="E020",l.EasyPayMethod="E020=CARD";break;case"nicepay_kakaopay":l.NicepayReserved="DirectKakao=Y";break;case"nicepay_samsungpay":l.DirectEasyPay="E021";break;case"nicepay_applepay":l.DirectEasyPay="E025";break;case"nicepay_payco":l.NicepayReserved="DirectPayco=Y";break;case"nicepay_skpay":l.NicepayReserved="DirectPay11=Y";break;case"nicepay_ssgpay":l.DirectEasyPay="E007";break;case"nicepay_lpay":l.DirectEasyPay="E018";break}try{const w=(await i.api.get(`/modules/sirsoft-ecommerce/user/orders/${n.order_number}`))?.data;if(w){const T=Number(w.total_tax_amount??0),S=Number(w.total_vat_amount??0),Te=Number(w.total_tax_free_amount??0);(T>0||S>0||Te>0)&&(l.TaxAmt=String(T),l.VatAmt=String(S),l.TaxFreeAmt=String(Te))}}catch{}const d=Me(L,l);if(u){d.action=Ge,d.acceptCharset="euc-kr";const k=d.querySelector('input[name="CharSet"]');k&&(k.value="euc-kr"),d.submit();return}window.nicepaySubmit=()=>{d.submit()};let N=!1;const V=new Set(document.body.children),ve=(k,w)=>{if(N)return;N=!0;const T=[k,w].filter(Boolean).join(": ")||"nicepay-window-closed";Oe({closeReportUrl:p.close_report_url,oid:n.order_number,price:Number(n.amount),buyer_email:n.customer_email??"",buyer_phone:n.customer_phone??"",payment_method:o},T),window.removeEventListener("popstate",Le),Array.from(document.body.children).forEach(S=>{V.has(S)||S.remove()}),d.parentNode&&d.parentNode.removeChild(d),window.__sirsoftNicepayPaymentInProgress=!1,i?.state?.setLocal?.({isSubmittingOrder:!1,paymentMethod:o}),w&&i?.toast?.error?.(w)};window.nicepayClose=ve;const Le=()=>ve("","");window.history.pushState({nicepayOpen:!0},""),window.addEventListener("popstate",Le),window.goPay(d)}catch(s){console.error("[sirsoft-pay_nicepayments] requestPayment error",s),window.__sirsoftNicepayPaymentInProgress=!1,i?.state?.setLocal?.({isSubmittingOrder:!1,paymentMethod:o}),i?.toast?.error?.("결제 중 오류가 발생했습니다. 잠시 후 다시 시도해주세요.")}}const je={nicepay_naverpay:"네이버페이",nicepay_kakaopay:"카카오페이",nicepay_samsungpay:"삼성페이",nicepay_applepay:"애플페이",nicepay_payco:"PAYCO",nicepay_skpay:"11pay",nicepay_ssgpay:"SSG페이",nicepay_lpay:"L.pay"},Fe="0 0 0 2px #ffffff, 0 0 0 5px rgba(0,0,0,0.55)";function J(){const e=document.getElementById("nicepay_checkout_payment_section");if(!e)return null;const t=e.querySelectorAll("p");for(const n of t)if(n.textContent?.includes("간편결제"))return n.nextElementSibling;return null}function X(){const e=J();e&&e.querySelectorAll("button").forEach(t=>{t.style.boxShadow="",t.style.outline=""})}function Ye(e){const t=J();if(!t)return;const n=je[e];t.querySelectorAll("button").forEach(a=>{a.textContent?.trim()===n?(a.style.boxShadow=Fe,a.style.outline="none"):(a.style.boxShadow="",a.style.outline="")})}function qe(e){const t=e.params?.paymentMethod;if(!t)return;const n=typeof t=="string"&&t.indexOf("nicepay_")===0;window.G7Core?.state?.setLocal?.({paymentMethod:t,serverPaymentMethod:n?"card":t}),n?Ye(t):X()}function Q(){const e=window.__templateApp;typeof e?.onGlobalStateChange=="function"&&e.onGlobalStateChange(t=>{const n=t?._local?.paymentMethod;typeof n=="string"&&(n.startsWith("nicepay_")||X())})}const Z={requestPayment:z,setPaymentMethod:qe},ee="/user/orders",He="sirsoft-nicepayments",I="sirsoft-pay_nicepayments",te="__sirsoftNicepayFetchInterceptorInstalled",ne="/api/modules/sirsoft-ecommerce/checkout",R="__sirsoftNicepayPaymentInProgress",P="__sirsoftNicepayCheckoutCache",f={info:(...e)=>console.info(`[${I}]`,...e),warn:(...e)=>console.warn(`[${I}]`,...e),error:(...e)=>console.error(`[${I}]`,...e)};function Ue(){return window.location.pathname+window.location.search+window.location.hash}function Ke(e,t){if(t.toUpperCase()!=="POST")return!1;const n=(e??"").split("?")[0].split("#")[0];return n===ee||n.endsWith(ee)}function O(e,t){if(t.toUpperCase()!=="GET")return!1;const n=(e??"").split("?")[0].split("#")[0];return n===ne||n.endsWith(ne)}function We(e){if(!e)return;let t=null;if(typeof e=="string")try{t=JSON.parse(e)}catch{return}else typeof e=="object"&&(t=e);if(!t)return;const n=t.payment_method;return typeof n=="string"&&n.length>0?n:void 0}function Ve(e,t){try{const n=JSON.parse(e);if("payment_method"in n)return JSON.stringify({...n,payment_method:t})}catch{}return e}function ze(e){const t=[e.total_due_amount,e.total_amount];for(const n of t){const a=Number(n??0);if(Number.isFinite(a)&&a>0)return Math.floor(a)}return 0}function Je(){const e=window;if(e[te])return;e[te]=!0;const t="__sirsoftPgOriginalFetch";e[t]||(e[t]=window.fetch.bind(window));const n=e[t],a=window.fetch.bind(window);window.fetch=async(r,o)=>{const i=typeof r=="string"?r:r instanceof URL?r.href:r.url,s=o?.method??(r instanceof Request?r.method:"GET");if(O(i,s)){if(e[R]&&e[P])return f.info("payment in progress — serving cached checkout response"),new Response(e[P],{status:200,headers:{"Content-Type":"application/json"}});const c=await a(r,o);if(c.ok){const d=await c.text();return e[P]=d,new Response(d,{status:c.status,statusText:c.statusText,headers:c.headers})}return c}if(!Ke(i,s))return a(r,o);let p,u=!1,v=o;if(o?.body&&typeof o.body=="string"){const c=We(o.body);typeof c=="string"&&c.length>0&&(p=c,c.startsWith("nicepay_")&&(u=!0,v={...o,body:Ve(o.body,"card")},f.info(`easy pay detected: replacing payment_method '${c}' → 'card'`)))}const y=await(u?n:a)(r,v);if(!y.ok)return y;let g=null;try{g=await y.clone().json()}catch{return y}const h=g?.data??g;if(!h?.requires_pg_payment&&!u)return y;const L=h.pg_provider===He;if(!u&&!L)return y;let m=h.pg_payment_data;if(!m&&u){const c=h.order;if(c){const d=c.options,N=d?.[0]?.product_name??String(c.order_number??""),V=(d?.length??0)>1?`${N} 외 ${(d?.length??0)-1}건`:N;m={order_number:c.order_number,order_name:V,amount:ze(c),currency:"KRW",customer_name:c.orderer_name??null,customer_email:c.orderer_email??null,customer_phone:String(c.orderer_phone??"").replace(/[^0-9]/g,""),customer_key:c.user_id??null},f.info("pg_payment_data constructed from order (기본 PG 미설정)",{order_number:m.order_number,amount:m.amount})}}if(!m)return f.warn("nicepayments order detected but pg_payment_data missing"),y;const W=p??"card";f.info("intercepted order create response — opening PG popup",{paymentMethod:W}),z({params:{pgPaymentData:m,paymentMethod:W}}),e[R]=!0;const b={...h,requires_pg_payment:!1,redirect_url:Ue()},l=g?.data?{...g,data:b}:b;return new Response(JSON.stringify(l),{status:y.status,statusText:y.statusText,headers:y.headers})},f.info("fetch order interceptor installed"),re(e,15)}const ae="__sirsoftNicepayAxiosCheckoutInterceptorInstalled";function re(e,t){const n=window?.G7Core?.api?.client;if(!n?.interceptors){t>0&&setTimeout(()=>re(e,t-1),300);return}e[ae]||(e[ae]=!0,n.interceptors.response.use(a=>{const r=(a?.config?.method??"").toLowerCase(),o=String((a?.config?.baseURL??"")+(a?.config?.url??""));return r==="get"&&O(o,"GET")&&a?.status===200&&(e[P]=JSON.stringify(a.data),f.info("checkout response cached (axios)")),a}),n.interceptors.request.use(a=>{const r=(a?.method??"").toLowerCase(),o=String((a?.baseURL??"")+(a?.url??""));return r==="get"&&O(o,"GET")&&e[R]&&e[P]&&(f.info("payment in progress — serving cached checkout response (axios)"),a.adapter=()=>Promise.resolve({data:JSON.parse(e[P]),status:200,statusText:"OK (cached)",headers:{"content-type":"application/json"},config:a,request:{}})),a}),f.info("axios checkout interceptor installed"),e[P]||(async()=>{try{await window?.G7Core?.api?.get?.("/modules/sirsoft-ecommerce/checkout")}catch{}})())}const Xe="sirsoft-pay_nicepayments",oe="__nicepayCheckoutEasyPayInjectorInstalled",Qe=/^\/shop\/checkout\/?$/,ie="__nicepayCheckoutEasyPaySyncListenerAttached",Ze=200,et=120,tt="nicepay_checkout_payment_section",se=[{id:"nicepay_naverpay",labels:["네이버페이 (나이스페이먼츠)","네이버페이로 결제 (나이스페이먼츠)","Naver Pay (NicePayments)","Pay with Naver Pay (NicePayments)"],ko:{heading:"네이버페이 (나이스페이먼츠)",description:"네이버페이로 결제 (나이스페이먼츠)",title:"네이버페이로 결제 (나이스페이먼츠)"},en:{heading:"Naver Pay (NicePayments)",description:"Pay with Naver Pay (NicePayments)",title:"Pay with Naver Pay (NicePayments)"},markText:"N",markClassName:"bg-green-500 text-white"},{id:"nicepay_kakaopay",labels:["카카오페이 (나이스페이먼츠)","카카오페이로 결제 (나이스페이먼츠)","Kakao Pay (NicePayments)","Pay with Kakao Pay (NicePayments)"],ko:{heading:"카카오페이 (나이스페이먼츠)",description:"카카오페이로 결제 (나이스페이먼츠)",title:"카카오페이로 결제 (나이스페이먼츠)"},en:{heading:"Kakao Pay (NicePayments)",description:"Pay with Kakao Pay (NicePayments)",title:"Pay with Kakao Pay (NicePayments)"},markText:"K",markClassName:"bg-yellow-400 text-gray-950"},{id:"nicepay_samsungpay",labels:["삼성페이 (나이스페이먼츠)","삼성페이로 결제 (나이스페이먼츠)","Samsung Pay (NicePayments)","Pay with Samsung Pay (NicePayments)"],ko:{heading:"삼성페이 (나이스페이먼츠)",description:"삼성페이로 결제 (나이스페이먼츠)",title:"삼성페이로 결제 (나이스페이먼츠)"},en:{heading:"Samsung Pay (NicePayments)",description:"Pay with Samsung Pay (NicePayments)",title:"Pay with Samsung Pay (NicePayments)"},markText:"S",markClassName:"bg-blue-600 text-white"},{id:"nicepay_applepay",labels:["애플페이 (나이스페이먼츠)","애플페이로 결제 (나이스페이먼츠)","Apple Pay (NicePayments)","Pay with Apple Pay (NicePayments)"],ko:{heading:"애플페이 (나이스페이먼츠)",description:"애플페이로 결제 (나이스페이먼츠)",title:"애플페이로 결제 (나이스페이먼츠)"},en:{heading:"Apple Pay (NicePayments)",description:"Pay with Apple Pay (NicePayments)",title:"Pay with Apple Pay (NicePayments)"},markText:"A",markClassName:"bg-gray-900 text-white"},{id:"nicepay_payco",labels:["PAYCO (나이스페이먼츠)","PAYCO로 결제 (나이스페이먼츠)","PAYCO (NicePayments)","Pay with PAYCO (NicePayments)"],ko:{heading:"PAYCO (나이스페이먼츠)",description:"PAYCO로 결제 (나이스페이먼츠)",title:"PAYCO로 결제 (나이스페이먼츠)"},en:{heading:"PAYCO (NicePayments)",description:"Pay with PAYCO (NicePayments)",title:"Pay with PAYCO (NicePayments)"},markText:"P",markClassName:"bg-red-500 text-white"},{id:"nicepay_skpay",labels:["11pay (나이스페이먼츠)","11pay로 결제 (나이스페이먼츠)","11pay (NicePayments)","Pay with 11pay (NicePayments)"],ko:{heading:"11pay (나이스페이먼츠)",description:"11pay로 결제 (나이스페이먼츠)",title:"11pay로 결제 (나이스페이먼츠)"},en:{heading:"11pay (NicePayments)",description:"Pay with 11pay (NicePayments)",title:"Pay with 11pay (NicePayments)"},markText:"11",markClassName:"bg-orange-500 text-white"},{id:"nicepay_ssgpay",labels:["SSG페이 (나이스페이먼츠)","SSG페이로 결제 (나이스페이먼츠)","SSG Pay (NicePayments)","Pay with SSG Pay (NicePayments)"],ko:{heading:"SSG페이 (나이스페이먼츠)",description:"SSG페이로 결제 (나이스페이먼츠)",title:"SSG페이로 결제 (나이스페이먼츠)"},en:{heading:"SSG Pay (NicePayments)",description:"Pay with SSG Pay (NicePayments)",title:"Pay with SSG Pay (NicePayments)"},markText:"SSG",markClassName:"bg-red-700 text-white"},{id:"nicepay_lpay",labels:["L.pay (나이스페이먼츠)","L.pay로 결제 (나이스페이먼츠)","L.pay (NicePayments)","Pay with L.pay (NicePayments)"],ko:{heading:"L.pay (나이스페이먼츠)",description:"L.pay로 결제 (나이스페이먼츠)",title:"L.pay로 결제 (나이스페이먼츠)"},en:{heading:"L.pay (NicePayments)",description:"Pay with L.pay (NicePayments)",title:"Pay with L.pay (NicePayments)"},markText:"L",markClassName:"bg-purple-600 text-white"}];let ce=null,C=null,D=!1;function nt(){return window}function M(){return Qe.test(window.location.pathname)}function at(e){return(e??"").replace(/\s+/g," ").trim()}function rt(e){return at(e).replace(/\u200B/g,"")}function ot(){return(document.documentElement.lang||navigator.language||"").toLowerCase().startsWith("ko")}function it(e){return ot()?e.ko:e.en}function le(e){return e.replaceAll("네이버페이","네이버페이").replaceAll("카카오페이","카카오페이").replaceAll("삼성페이","삼성페이").replaceAll("Naver Pay","Naver Pay").replaceAll("Kakao Pay","Kakao Pay").replaceAll("Samsung Pay","Samsung Pay").replaceAll("L.pay","L.pay")}function st(e){return se.find(t=>t.id===e)??null}function ct(e){const t=st(e.dataset.nicepayEasyPayMethod);if(t)return t;const n=rt(e.textContent);return se.find(a=>a.labels.some(r=>n.includes(r)))??null}function de(e){return e.querySelector(".flex.items-center.gap-2, .flex.items-center.gap-3")??e.querySelector(".flex.items-center")}function lt(e,t,n){e.style.textAlign="left";const a=de(e);a&&(a.style.justifyContent="flex-start",a.style.textAlign="left",a.style.width="100%");const r=t?.parentElement??n?.parentElement;r instanceof HTMLElement&&(r.style.textAlign="left",r.style.minWidth="0")}function dt(e){const t=document.createElement("span");return t.dataset.nicepayEasyPayMark="true",t.dataset.nicepayEasyPayMethod=e.id,t.setAttribute("aria-hidden","true"),t.className=`inline-flex items-center justify-center rounded-lg text-xs font-bold ${e.markClassName}`,t.style.width="32px",t.style.height="32px",t.style.flex="0 0 32px",t.textContent=e.markText,t}function yt(e){delete e.dataset.kginicisBrandPaymentButton,delete e.dataset.kginicisBrandPaymentMethod,delete e.dataset.kginicisNaverpayBrandButton,delete e.dataset.nhnkcpEasyPayMethod,delete e.dataset.nhnkcpEasyPayVisible,delete e.dataset.nhnkcpEasyPayHidden,e.querySelectorAll('[data-kginicis-brand-payment-mark="true"], [data-kginicis-naverpay-mark="true"], [data-nhnkcp-easy-pay-mark="true"]').forEach(t=>{t.remove()})}function ut(e){return e.querySelector('[data-nicepay-easy-pay-mark="true"]')??e.querySelector('[data-kginicis-brand-payment-mark="true"], [data-kginicis-naverpay-mark="true"], [data-nhnkcp-easy-pay-mark="true"]')??e.querySelector("svg")??e.querySelector('i[class*="fa-"], i[role="img"], i')}function pt(e,t){const n=e.querySelector('[data-nicepay-easy-pay-mark="true"]');if(n){n.dataset.nicepayEasyPayMethod=t.id,n.className=`inline-flex items-center justify-center rounded-lg text-xs font-bold ${t.markClassName}`,n.textContent=t.markText;return}const a=dt(t),r=ut(e);if(r&&r.parentElement){r.replaceWith(a);return}de(e)?.prepend(a)}function mt(e,t){const n=Array.from(e.querySelectorAll("p")),a=it(t),r=le(a.heading),o=le(a.description),i=n[0],s=n[1];i&&i.textContent!==r&&(i.textContent=r),i&&(i.setAttribute("aria-label",a.heading),i.style.textAlign="left",i.style.whiteSpace="normal",i.style.wordBreak="keep-all",i.style.overflowWrap="anywhere"),s&&s.textContent!==o&&(s.textContent=o),s&&(s.style.textAlign="left",s.style.fontSize="12px",s.style.lineHeight="1rem",s.style.whiteSpace="normal",s.style.wordBreak="keep-all",s.style.overflowWrap="anywhere"),lt(e,i,s),e.title=a.title}function ft(e,t){e.hidden&&(e.hidden=!1),e.disabled&&(e.disabled=!1),e.style.display==="none"&&e.style.removeProperty("display"),e.removeAttribute("aria-hidden"),e.dataset.nicepayEasyPayMethod=t.id,e.dataset.nicepayEasyPayVisible="true",yt(e),pt(e,t),mt(e,t)}function ht(){const e=document.getElementById(tt);return e?(e.remove(),!0):!1}async function $(e=document){if(typeof window>"u"||typeof document>"u"||!M())return!1;let t=ht();return e.querySelectorAll("button").forEach(n=>{const a=ct(n);a&&(ft(n,a),t=!0)}),t}function gt(){D||(D=!0,window.setTimeout(()=>{D=!1,$()},0))}function ye(){C!==null&&(window.clearInterval(C),C=null)}function G(){if(!M())return;ye(),$();let e=0;C=window.setInterval(()=>{e+=1,$(),e>=et&&ye()},Ze);const t=document.body;t[ie]||(t[ie]=!0,ce=new MutationObserver(()=>gt()),ce.observe(document.body,{childList:!0,subtree:!0,characterData:!0}))}function ue(){M()&&G()}function wt(){if(typeof window>"u"||typeof document>"u")return;const e=nt();if(e[oe])return;e[oe]=!0,console.info(`[${Xe}] checkout easy pay method sync installed`),document.readyState==="loading"?document.addEventListener("DOMContentLoaded",()=>G()):G();const t=history.pushState.bind(history);history.pushState=(...n)=>{t(...n),window.setTimeout(()=>ue(),200)},window.addEventListener("popstate",()=>window.setTimeout(()=>ue(),200))}const B="sirsoft-pay_nicepayments",pe="__nicepayOcReceiptInjectorInstalled",me="nicepay-oc-receipt-btn",Pt=/^\/shop\/orders\/([^/]+)\/complete$/;function fe(){return localStorage.getItem("auth_token")}async function _t(e){const t=fe();if(!t)return null;try{const n=await fetch(`/api/modules/sirsoft-ecommerce/user/orders/${e}`,{headers:{Authorization:`Bearer ${t}`,Accept:"application/json"}});return n.ok?(await n.json())?.data?.payment??null:null}catch{return null}}async function bt(e){const t=fe();if(!t)return null;try{const n=await fetch(`/api/plugins/${B}/user/orders/${e}/receipt`,{headers:{Authorization:`Bearer ${t}`,Accept:"application/json"}});return n.ok?(await n.json()).receipt_url??null:null}catch{return null}}async function Nt(e){if(document.getElementById(me))return;const t=await _t(e);if(!t||t.pg_provider!=="nicepayments"||!t.transaction_id||!t.paid_at)return;const n=Array.from(document.querySelectorAll('button[type="button"]')).find(i=>i.className.includes("bg-blue-600"));if(!n?.parentElement)return;const a=n.parentElement,r=document.createElement("button");r.id=me,r.type="button",r.className=n.className.replace(/bg-blue-\d+/g,"bg-green-600").replace(/hover:bg-blue-\d+/g,"hover:bg-green-700"),r.textContent="영수증 조회",r.addEventListener("click",async()=>{r.disabled=!0,r.textContent="로딩 중...";const i=await bt(e);r.disabled=!1,r.textContent="영수증 조회",i&&window.open(i,"nicepay_receipt","width=800,height=600,scrollbars=yes,resizable=yes")});const o=a.lastElementChild;a.insertBefore(r,o),console.info(`[${B}] receipt button injected on order complete page`)}function kt(){const e=location.pathname.match(Pt);e&&Nt(e[1])}function St(){if(typeof window>"u")return;const e=window;if(e[pe])return;e[pe]=!0,console.info(`[${B}] order complete receipt injector installed`);const t=(a=1200)=>setTimeout(kt,a);document.readyState==="loading"?document.addEventListener("DOMContentLoaded",()=>t()):t();const n=history.pushState.bind(history);history.pushState=(...a)=>{n(...a),t()},window.addEventListener("popstate",()=>t(500))}const E="sirsoft-pay_nicepayments",he="__nicepayOrderShowInjectorInstalled",ge="nicepay-mp-receipt-row",we="nicepay-mp-vbank-info",Ct=/^\/mypage\/orders\/([^/]+)$/;function Et(e){try{const n=window.G7Core?.getState,o=n?.()?.currentDataContext?.order?.data;return!o||o.order_number!==e?null:o}catch{return null}}function xt(){return localStorage.getItem("auth_token")}async function At(e){const t=xt();if(!t)return null;try{const n=await fetch(`/api/plugins/${E}/user/orders/${e}/receipt`,{headers:{Authorization:`Bearer ${t}`,Accept:"application/json"}});return n.ok?(await n.json()).receipt_url??null:null}catch{return null}}function vt(){const e=document.getElementById("order_payment_info_panel");if(e)return Array.from(e.children).find(a=>a.className?.includes("space-y"))??e;const t=Array.from(document.querySelectorAll("h3")).find(a=>a.textContent?.includes("결제 정보"));if(!t)return null;const n=t.parentElement?.parentElement;return n?Array.from(n.children).find(a=>a.className?.includes("space-y"))??n:null}function Lt(e){const t=document.createElement("div");t.id=ge,t.className="flex items-center justify-between";const n=document.createElement("span");n.className="text-gray-500 dark:text-gray-400 text-sm",n.textContent="영수증";const a=document.createElement("button");return a.type="button",a.className="inline-flex items-center gap-1 text-sm text-blue-600 dark:text-blue-400 hover:underline disabled:opacity-50",a.textContent="영수증 조회",a.addEventListener("click",async()=>{a.disabled=!0,a.textContent="로딩 중...";const r=await At(e);a.disabled=!1,a.textContent="영수증 조회",r&&window.open(r,"nicepay_receipt","width=800,height=600,scrollbars=yes,resizable=yes")}),t.appendChild(n),t.appendChild(a),t}function Tt(e){if(!e)return"";try{const t=new Date(e);if(Number.isNaN(t.getTime()))return e;const n=a=>String(a).padStart(2,"0");return`${t.getFullYear()}-${n(t.getMonth()+1)}-${n(t.getDate())} ${n(t.getHours())}:${n(t.getMinutes())}:${n(t.getSeconds())}`}catch{return e}}function x(e,t,n="font-medium text-gray-900 dark:text-white"){const a=document.createElement("div");a.className="flex justify-between text-sm";const r=document.createElement("span");r.className="text-gray-600 dark:text-gray-400",r.textContent=e;const o=document.createElement("span");return o.className=n,o.textContent=t,a.appendChild(r),a.appendChild(o),a}function It(e){const t=e.payment??{},n=document.createElement("div");n.id=we,n.className="pt-4 mt-2 border-t border-gray-200 dark:border-gray-700";const a=document.createElement("div");a.className="bg-blue-50 dark:bg-blue-900/30 border border-blue-200 dark:border-blue-700 rounded-lg p-4";const r=document.createElement("h3");r.className="text-sm font-semibold text-blue-800 dark:text-blue-300 mb-3",r.textContent="가상계좌 입금 안내";const o=document.createElement("div");o.className="space-y-2",o.appendChild(x("은행",t.vbank_name??"")),o.appendChild(x("계좌번호",t.vbank_number??"","font-medium font-mono text-gray-900 dark:text-white")),o.appendChild(x("예금주",t.vbank_holder??"")),o.appendChild(x("입금 금액",e.total_amount_formatted??"","font-bold text-blue-600 dark:text-blue-400"));const i=t.vbank_due_at;if(i){const s=document.createElement("div");s.className="flex justify-between text-sm pt-2 border-t border-blue-200 dark:border-blue-700 mt-2";const p=document.createElement("span");p.className="text-gray-600 dark:text-gray-400",p.textContent="입금 기한";const u=document.createElement("span");u.className="font-medium text-red-600 dark:text-red-400",u.textContent=Tt(i),s.appendChild(p),s.appendChild(u),o.appendChild(s)}if(a.appendChild(r),a.appendChild(o),!t.paid_at){const s=document.createElement("p");s.className="text-xs text-blue-700 dark:text-blue-300 mt-3",s.textContent="입금 기한 내에 입금이 완료되지 않으면 주문이 자동 취소됩니다.",a.appendChild(s)}return n.appendChild(a),n}async function Rt(e){const t=Et(e);if(!t)return!1;const{payment:n}=t;if(!n||n.pg_provider!=="nicepayments")return!0;const a=vt();return a?(n.payment_method==="vbank"&&n.vbank_number&&!document.getElementById(we)&&(a.appendChild(It(t)),console.info(`[${E}] vbank info injected on mypage order show`)),!n.transaction_id||!n.paid_at||document.getElementById(ge)||(a.appendChild(Lt(e)),console.info(`[${E}] receipt button injected on mypage order show`)),!0):!1}function Ot(e){let t=0;const n=setInterval(()=>{t++,Rt(e).then(a=>{(a||t>=30)&&clearInterval(n)})},400)}function Dt(){const e=location.pathname.match(Ct);e&&Ot(e[1])}function Mt(){if(typeof window>"u")return;const e=window;if(e[he])return;e[he]=!0,console.info(`[${E}] mypage order show injector installed`);const t=(a=1500)=>setTimeout(Dt,a);document.readyState==="loading"?document.addEventListener("DOMContentLoaded",()=>t()):t();const n=history.pushState.bind(history);history.pushState=(...a)=>{n(...a),t(600)},window.addEventListener("popstate",()=>t(500))}const $t="sirsoft-pay_nicepayments",Pe="__nicepayAdminPaymentMethodBrandInjectorInstalled",_e="__nicepayAdminPaymentMethodBrandSyncListenerAttached",Gt=/^\/admin\/ecommerce\/settings\/?$/,be='[data-nicepay-admin-payment-brand-mark="true"]',Bt=200,jt=120,Ft=[{id:"nicepay_naverpay",labels:["네이버페이 (나이스페이먼츠)","네이버페이로 결제 (나이스페이먼츠)","Naver Pay (NicePayments)","Pay with Naver Pay (NicePayments)"],shortLabels:[],markLines:["N"],markClassName:"bg-green-500 text-white"},{id:"nicepay_kakaopay",labels:["카카오페이 (나이스페이먼츠)","카카오페이로 결제 (나이스페이먼츠)","Kakao Pay (NicePayments)","Pay with Kakao Pay (NicePayments)"],shortLabels:[],markLines:["K"],markClassName:"bg-yellow-400 text-gray-950"},{id:"nicepay_samsungpay",labels:["삼성페이 (나이스페이먼츠)","삼성페이로 결제 (나이스페이먼츠)","Samsung Pay (NicePayments)","Pay with Samsung Pay (NicePayments)"],shortLabels:[],markLines:["S"],markClassName:"bg-blue-600 text-white"},{id:"nicepay_applepay",labels:["애플페이 (나이스페이먼츠)","애플페이로 결제 (나이스페이먼츠)","Apple Pay (NicePayments)","Pay with Apple Pay (NicePayments)"],shortLabels:[],markLines:["A"],markClassName:"bg-gray-900 text-white"},{id:"nicepay_payco",labels:["PAYCO (나이스페이먼츠)","PAYCO로 결제 (나이스페이먼츠)","PAYCO (NicePayments)","Pay with PAYCO (NicePayments)"],shortLabels:[],markLines:["P"],markClassName:"bg-red-500 text-white"},{id:"nicepay_skpay",labels:["11pay (나이스페이먼츠)","11pay로 결제 (나이스페이먼츠)","11pay (NicePayments)","Pay with 11pay (NicePayments)"],shortLabels:[],markLines:["11"],markClassName:"bg-orange-500 text-white"},{id:"nicepay_ssgpay",labels:["SSG페이 (나이스페이먼츠)","SSG페이로 결제 (나이스페이먼츠)","SSG Pay (NicePayments)","Pay with SSG Pay (NicePayments)"],shortLabels:[],markLines:["SSG"],markClassName:"bg-red-700 text-white"},{id:"nicepay_lpay",labels:["L.pay (나이스페이먼츠)","L.pay로 결제 (나이스페이먼츠)","L.pay (NicePayments)","Pay with L.pay (NicePayments)"],shortLabels:[],markLines:["L"],markClassName:"bg-purple-600 text-white"}];let Ne=null,A=null,j=!1;function Yt(){return window}function F(){if(!Gt.test(window.location.pathname))return!1;const e=new URLSearchParams(window.location.search).get("tab");return e===null||e===""||e==="order_settings"}function qt(e){return e instanceof HTMLElement?e.className:""}function ke(e){return(e??"").replace(/\u200B/g,"").replace(/\s+/g," ").trim()}function Ht(e){const t=qt(e);return t.includes("excel-card")||t.includes("flex-center")&&t.includes("border")&&t.includes("gap-4")}function Se(e){return e.querySelector(".font-medium")}function Ut(e){const t=ke(Se(e)?.textContent),n=ke(e.textContent);return Ft.find(a=>a.shortLabels.some(r=>t===r)||a.labels.some(r=>n.includes(r)))??null}function Kt(e){return Array.from(e.querySelectorAll("div")).filter(Ht)}function Wt(e){return Array.from(e.querySelectorAll("svg, [data-icon], i")).find(n=>!n.closest("[data-drag-handle]")&&!n.closest(be)&&!n.closest('.row-stack, .excel-card-body, button, select, [role="switch"]'))??null}function Ce(e,t){e.dataset.nicepayAdminPaymentBrandMark="true",e.dataset.nicepayAdminPaymentMethod=t.id,e.setAttribute("aria-hidden","true"),e.className=`inline-flex items-center justify-center rounded-lg font-bold ${t.markClassName}`,e.style.width="32px",e.style.height="32px",e.style.flex="0 0 32px",e.style.lineHeight="1",e.style.fontSize=t.markLines.join("").length>2?"9px":"12px";const n=t.markLines.join("");e.textContent!==n&&(e.textContent=t.markLines[0]??"")}function Vt(e){const t=document.createElement("span");return Ce(t,e),t}function zt(e,t){const n=e.querySelector(be);if(n instanceof HTMLSpanElement)return e.dataset.nicepayAdminPaymentMethod=t.id,Ce(n,t),!0;const a=Vt(t),r=Wt(e);if(r&&r.parentElement)return e.dataset.nicepayAdminPaymentMethod=t.id,r.replaceWith(a),!0;const o=Se(e);return o&&o.parentElement?(e.dataset.nicepayAdminPaymentMethod=t.id,o.parentElement.insertBefore(a,o),!0):!1}function Y(e=document){if(typeof window>"u"||typeof document>"u"||!F())return!1;let t=!1;return Kt(e).forEach(n=>{const a=Ut(n);a&&zt(n,a)&&(t=!0)}),t}function Jt(){j||(j=!0,window.setTimeout(()=>{j=!1,Y()},0))}function q(){A!==null&&(window.clearInterval(A),A=null)}function H(){if(!F())return;q(),Y();let e=0;A=window.setInterval(()=>{e+=1,Y(),e>=jt&&q()},Bt);const t=document.body;t[_e]||(t[_e]=!0,Ne=new MutationObserver(()=>Jt()),Ne.observe(document.body,{childList:!0,subtree:!0,characterData:!0}))}function Ee(){if(F()){H();return}q()}function Xt(){if(typeof window>"u"||typeof document>"u")return;const e=Yt();if(e[Pe])return;e[Pe]=!0,console.info(`[${$t}] admin payment method brand sync installed`),document.readyState==="loading"?document.addEventListener("DOMContentLoaded",()=>H()):H();const t=history.pushState.bind(history);history.pushState=(...n)=>{t(...n),window.setTimeout(()=>Ee(),200)},window.addEventListener("popstate",()=>window.setTimeout(()=>Ee(),200))}const _="sirsoft-pay_nicepayments",U={info:(...e)=>console.info(`[${_}]`,...e),warn:(...e)=>console.warn(`[${_}]`,...e),error:(...e)=>console.error(`[${_}]`,...e)};function xe(){const e=window.G7Core;if(!e)return 0;const t=e.getActionDispatcher;if(typeof t!="function")return 0;const n=t();if(!n||typeof n.registerHandler!="function")return 0;let a=0;for(const[r,o]of Object.entries(Z)){const i=`${_}.${r}`;n.registerHandler(i,o,{category:"plugin",source:_}),a++}return a}function Ae(){Je(),wt(),St(),Mt(),Xt();const e=()=>{const t=xe();if(t>0){U.info(`${t} handler(s) registered`),Q();return}let n=0;const a=50,r=setInterval(()=>{n++;const o=xe();if(o>0){clearInterval(r),U.info(`${o} handler(s) registered (after ${n} retries)`),Q();return}n>=a&&(clearInterval(r),U.warn("ActionDispatcher not available after timeout"))},100)};document.readyState==="loading"?document.addEventListener("DOMContentLoaded",e):e()}Ae(),window.__SirsoftNicepayments={identifier:_,handlers:Object.keys(Z),initPlugin:Ae}})();
|
||
//# sourceMappingURL=plugin.iife.js.map
|