cppay-sdk 0.0.2-beta.9 → 0.0.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/react.cjs CHANGED
@@ -1 +1 @@
1
- var e=Object.create,t=Object.defineProperty,n=Object.getOwnPropertyDescriptor,r=Object.getOwnPropertyNames,i=Object.getPrototypeOf,a=Object.prototype.hasOwnProperty,o=(e,i,o,s)=>{if(i&&typeof i==`object`||typeof i==`function`)for(var c=r(i),l=0,u=c.length,d;l<u;l++)d=c[l],!a.call(e,d)&&d!==o&&t(e,d,{get:(e=>i[e]).bind(null,d),enumerable:!(s=n(i,d))||s.enumerable});return e},s=(n,r,a)=>(a=n==null?{}:e(i(n)),o(r||!n||!n.__esModule?t(a,`default`,{value:n,enumerable:!0}):a,n));const c=require(`./cppay-D9NSpEr9.cjs`),l=require(`./inject-style-Dz7JsQxo.cjs`);let u=require(`react`);u=s(u);let d=require(`react/jsx-runtime`);var f=({open:e,onClose:t,apiKey:n,orderId:r,amount:i,onSuccess:a,onError:o})=>{let s=(0,u.useMemo)(()=>new c.t(n),[n]),[l,f]=(0,u.useState)(`select`),[p,m]=(0,u.useState)(!1),[h,g]=(0,u.useState)([]),[_,v]=(0,u.useState)(``),[y,b]=(0,u.useState)(``),[x,S]=(0,u.useState)(null),C=(0,u.useMemo)(()=>h.find(e=>e.chain===_),[h,_]),w=(0,u.useMemo)(()=>C?.tokens||[],[C]),T=(0,u.useMemo)(()=>w.find(e=>e.symbol===y),[w,y]),E=(0,u.useMemo)(()=>y?(parseFloat(i)/1).toFixed(6):`0`,[i,y,1]),D=async()=>{try{m(!0);let e=await s.getSupportedChains();g(e),e.length>0&&v(e[0].chain)}catch(e){o?.(e)}finally{m(!1)}},O=async()=>{if(!(!_||!y))try{m(!0);let e=await s.createPayment({paymentChain:_,paymentToken:y,orderId:r,amount:E});S({paymentId:e.paymentId,paymentAmount:e.paymentAmount,receiveAddress:T?.receiveAddresses[0]||``}),f(`payment`)}catch(e){o?.(e)}finally{m(!1)}},k=async()=>{if(x)try{m(!0),await s.checkPaymentStatus(x.paymentId),a?.(x.paymentId),j()}catch(e){o?.(e)}finally{m(!1)}},A=async()=>{x?.receiveAddress&&await navigator.clipboard.writeText(x.receiveAddress)},j=()=>{t(),setTimeout(()=>{f(`select`),S(null)},300)};return(0,u.useEffect)(()=>{e&&h.length===0&&D()},[e]),(0,u.useEffect)(()=>{w.length>0&&b(w[0].symbol)},[w]),e?(0,d.jsx)(`div`,{className:`_cppay-overlay`,onClick:e=>e.target===e.currentTarget&&j(),children:(0,d.jsxs)(`div`,{className:`_cppay-dialog`,children:[(0,d.jsxs)(`div`,{className:`_cppay-header`,children:[(0,d.jsx)(`h2`,{className:`_cppay-title`,children:l===`select`?`选择支付方式`:`完成支付`}),(0,d.jsx)(`button`,{onClick:j,disabled:p,className:`_cppay-close-btn`,children:(0,d.jsx)(`svg`,{fill:`none`,stroke:`currentColor`,viewBox:`0 0 24 24`,children:(0,d.jsx)(`path`,{strokeLinecap:`round`,strokeLinejoin:`round`,strokeWidth:2,d:`M6 18L18 6M6 6l12 12`})})})]}),(0,d.jsx)(`div`,{className:`_cppay-content`,children:l===`select`?(0,d.jsxs)(`div`,{children:[(0,d.jsxs)(`div`,{className:`_cppay-section`,children:[(0,d.jsx)(`label`,{className:`_cppay-label`,children:`支付网络`}),(0,d.jsx)(`div`,{className:`_cppay-grid`,children:h.map(e=>(0,d.jsxs)(`button`,{onClick:()=>v(e.chain),className:`_cppay-select-btn ${_===e.chain?`_cppay-selected`:``}`,children:[e.icon&&(0,d.jsx)(`img`,{src:e.icon,alt:e.chain}),(0,d.jsx)(`span`,{children:e.chain})]},e.chain))})]}),(0,d.jsxs)(`div`,{className:`_cppay-section`,children:[(0,d.jsx)(`label`,{className:`_cppay-label`,children:`支付代币`}),(0,d.jsx)(`div`,{className:`_cppay-grid`,children:w.map(e=>(0,d.jsxs)(`button`,{onClick:()=>b(e.symbol),className:`_cppay-select-btn ${y===e.symbol?`_cppay-selected`:``}`,children:[e.icon&&(0,d.jsx)(`img`,{src:e.icon,alt:e.symbol}),(0,d.jsx)(`span`,{children:e.symbol})]},e.symbol))})]}),(0,d.jsx)(`div`,{className:`_cppay-section`,children:(0,d.jsx)(`div`,{className:`_cppay-price-box`,children:(0,d.jsxs)(`div`,{className:`_cppay-price-row`,children:[(0,d.jsx)(`span`,{className:`_cppay-price-label`,children:`支付金额`}),(0,d.jsxs)(`div`,{className:`_cppay-price-amount`,children:[(0,d.jsxs)(`div`,{className:`_cppay-price-main`,children:[E,` `,y]}),(0,d.jsxs)(`div`,{className:`_cppay-price-sub`,children:[`≈ $`,i]})]})]})})}),(0,d.jsx)(`div`,{className:`_cppay-section`,children:(0,d.jsx)(`button`,{onClick:O,disabled:!_||!y||p,className:`_cppay-btn _cppay-btn-primary`,children:p?`处理中...`:`继续支付`})})]}):x&&(0,d.jsxs)(`div`,{children:[(0,d.jsx)(`div`,{className:`_cppay-qr-container`,children:(0,d.jsx)(`div`,{className:`_cppay-qr-placeholder`,children:(0,d.jsx)(`span`,{children:`扫码支付`})})}),(0,d.jsxs)(`div`,{className:`_cppay-section`,children:[(0,d.jsxs)(`div`,{className:`_cppay-info-box`,children:[(0,d.jsx)(`div`,{className:`_cppay-info-label`,children:`支付金额`}),(0,d.jsxs)(`div`,{className:`_cppay-info-value`,children:[x.paymentAmount,` `,y]})]}),(0,d.jsxs)(`div`,{className:`_cppay-info-box`,children:[(0,d.jsx)(`div`,{className:`_cppay-info-label`,children:`支付地址`}),(0,d.jsxs)(`div`,{className:`_cppay-address-row`,children:[(0,d.jsx)(`code`,{children:x.receiveAddress}),(0,d.jsx)(`button`,{onClick:A,className:`_cppay-copy-btn`,title:`复制地址`,children:(0,d.jsx)(`svg`,{fill:`none`,stroke:`currentColor`,viewBox:`0 0 24 24`,children:(0,d.jsx)(`path`,{strokeLinecap:`round`,strokeLinejoin:`round`,strokeWidth:2,d:`M8 16H6a2 2 0 01-2-2V6a2 2 0 012-2h8a2 2 0 012 2v2m-6 12h8a2 2 0 002-2v-8a2 2 0 00-2-2h-8a2 2 0 00-2 2v8a2 2 0 002 2z`})})})]})]})]}),(0,d.jsx)(`div`,{className:`_cppay-section`,children:(0,d.jsx)(`button`,{onClick:k,disabled:p,className:`_cppay-btn _cppay-btn-primary`,children:p?`检查支付状态...`:`我已完成支付`})}),(0,d.jsx)(`div`,{className:`_cppay-section`,children:(0,d.jsx)(`button`,{onClick:()=>f(`select`),disabled:p,className:`_cppay-btn _cppay-btn-secondary`,children:`更改支付方式`})})]})})]})}):null},p=u.default.memo(f);l.t(l.n),exports.PaymentDialog=p,exports.t=s;
1
+ const e=require(`./locales-BWWyDdfj.cjs`),t=require(`./cppay-DuOJqlpA.cjs`);let n=require(`qrcode`);n=e.i(n);let r=require(`rxjs`),i=require(`rxjs/operators`),a=require(`viem`),o=require(`viem/chains`),ee=require(`@reown/appkit`),te=require(`@reown/appkit-adapter-ethers`),s=require(`react`);s=e.i(s);let c=require(`react/jsx-runtime`);var l=({apikey:l,ott:u,plain:d,orderId:f,amount:p,intervalDays:m,remark:ne,locale:h,onSuccess:g,onExpired:re,onFailed:_,onError:v,Slots:y,onPaymentStepChange:ie})=>{let b=(0,s.useMemo)(()=>new t.t(l,u),[l,u]),x=(0,s.useMemo)(()=>e.t(h),[h]),[S,C]=(0,s.useState)(`select`),w=(0,s.useMemo)(()=>S===`checking`,[S]),[T,E]=(0,s.useState)(!1),[D,O]=(0,s.useState)(),[k,ae]=(0,s.useState)([]),[A,j]=(0,s.useState)(),[M,N]=(0,s.useState)(),[oe,se]=(0,s.useState)(),[P,F]=(0,s.useState)(),[ce,le]=(0,s.useState)(!1),[I,ue]=(0,s.useState)(),[de,fe]=(0,s.useState)(``),[L,R]=(0,s.useState)(!1),[pe,z]=(0,s.useState)(!1),[B,me]=(0,s.useState)(``),V=(0,s.useRef)(null),H=(0,s.useRef)(null),U=(0,s.useRef)(null),W=(0,s.useRef)(null),G=(0,s.useRef)(``);(0,s.useEffect)(()=>{typeof window<`u`&&!V.current&&(V.current=(0,ee.createAppKit)({debug:!1,enableNetworkSwitch:!1,adapters:[new te.EthersAdapter],projectId:`8d2e1854d3f1782e45aa15fbd8938894`,allowUnsupportedChain:!0,networks:[o.mainnet,o.bsc,o.polygon,o.arbitrum,o.optimism,o.base],metadata:{name:`Cppay`,description:`Cppay Payment Gateway`,url:window.location.origin,icons:[`https://cppay.com/icon.png`]},features:{analytics:!1}}),F(V.current.getAddress()),ue(V.current.getProvider(`eip155`)),V.current.subscribeAccount(e=>{e.isConnected?F(e.address):(F(void 0),ue(void 0))}),V.current.subscribeProviders(e=>{let t=e?.eip155;ue(t)}))},[]),(0,s.useEffect)(()=>{ie?.(S)},[S]);let he=async()=>{try{le(!0),O(void 0),V.current&&await V.current.open()}catch(e){console.error(`钱包连接失败:`,e),O(e instanceof Error?e.message:x.walletConnectionFailed),v?.(e)}finally{le(!1)}},K=(0,s.useMemo)(()=>k.find(e=>e.chain===A),[k,A]),q=(0,s.useMemo)(()=>K?.tokens||[],[K]),J=(0,s.useMemo)(()=>q.find(e=>e.symbol===M),[q,M]),Y=e=>[`USDT`,`USDC`,`BUSD`,`DAI`,`TUSD`,`USDD`,`FDUSD`].includes(e.toUpperCase())?2:6,X=(e,t)=>{let n=parseFloat(e);return isNaN(n)?`0`:n.toFixed(t).replace(/\.?0+$/,``)},ge=e=>{if(e<=0)return x.expired;let t=Math.floor(e/3600),n=Math.floor(e%3600/60),r=e%60,i=e=>e.toString().padStart(2,`0`);return t>0?`${t}:${i(n)}:${i(r)}`:`${n}:${i(r)}`},Z=e=>{U.current&&clearInterval(U.current);let t=()=>{if(S===`checking`){_e();return}let t=e-Math.floor(Date.now()/1e3);fe(ge(t)),t<=0&&_e()};t(),U.current=setInterval(t,1e3)},_e=()=>{U.current&&=(clearInterval(U.current),null)},ve=(0,s.useMemo)(()=>{if(!M||!J)return`0`;let e=parseFloat(J.price);if(isNaN(e)||e===0)return`0`;let t=Y(M);return X((parseFloat(p)/e).toFixed(t),t)},[p,M,J]),ye=async()=>{try{E(!0),O(void 0);let e=await b.getSupportedChains();ae(e),e.length>0&&j(e[0].chain)}catch(e){O(e instanceof Error?e.message:x.loadPaymentNetworkFailed),v?.(e)}finally{E(!1)}},be=async e=>{if(I)try{await I.request({method:`wallet_switchEthereumChain`,params:[{chainId:`0x${e.toString(16)}`}]})}catch(e){throw e.code===4902?Error(x.pleaseAddNetwork):e}},xe=async()=>{if(!(!P||!I||!W.current||!J||!K))try{E(!0);let e=W.current;await be(K.chainId);let t=(0,a.createWalletClient)({account:P,transport:(0,a.custom)(I)});if(J.address){let n=await t.writeContract({address:J.address,abi:[{name:`transfer`,type:`function`,stateMutability:`nonpayable`,inputs:[{name:`to`,type:`address`},{name:`amount`,type:`uint256`}],outputs:[{type:`bool`}]}],functionName:`transfer`,args:[e.receiveAddress,(0,a.parseUnits)(e.paymentAmount,J.decimals)],chain:null});console.log(`转账交易哈希:`,n),me(n),G.current=n}else{let n=await t.sendTransaction({to:e.receiveAddress,value:(0,a.parseUnits)(e.paymentAmount,J.decimals),chain:null});console.log(`转账交易哈希:`,n),me(n),G.current=n}E(!1),C(`checking`),Q({paymentId:e.paymentId})}catch(e){console.error(`钱包支付失败:`,e),O(e instanceof Error?e.message:x.walletPaymentFailed),v?.(e),E(!1)}},Se=async()=>{if(!(!P||!I||!W.current||!J||!K))try{E(!0);let e=W.current;await be(K.chainId);let t=(0,a.createWalletClient)({account:P,transport:(0,a.custom)(I)});if(!J.address)throw Error(x.subscriptionDoesNotSupportNative);let n=await t.writeContract({address:J.address,abi:[{name:`approve`,type:`function`,stateMutability:`nonpayable`,inputs:[{name:`spender`,type:`address`},{name:`amount`,type:`uint256`}],outputs:[{type:`bool`}]}],functionName:`approve`,args:[e.spenderAddress,(0,a.parseUnits)(e.approveAmount,J.decimals)],chain:null});console.log(`授权交易哈希:`,n),me(n),G.current=n,E(!1),C(`checking`),Q({subscriptionId:e.subscriptionId})}catch(e){console.error(`钱包授权失败:`,e),O(e instanceof Error?e.message:x.walletPaymentFailed),v?.(e),E(!1)}},Ce=async()=>{if(!P){let e=x.pleaseConnectWallet;O(e),v?.(Error(e));return}d===`instant`?await xe():d===`subscription`&&await Se()},we=async()=>{if(!(!A||!M))try{E(!0),O(void 0);let e=``;if(d===`instant`)W.current=await b.createOnetimePayment({paymentChain:A,paymentToken:M,orderId:f,amount:ve,remark:ne}),e=`${A.toLowerCase()}:${W.current.receiveAddress}?amount=${W.current.paymentAmount}`,Z(W.current.expireAt),Oe(W.current.paymentId,`instant`);else if(d===`subscription`){if(!m)throw Error(`Invalid Renewal Days: ${m??``}`);W.current=await b.createSubscriptionPayment({paymentChain:A,paymentToken:M,orderId:f,amountOfUsd:ve,intervalDays:m}),e=`${A.toLowerCase()}:${W.current.spenderAddress}?amount=${W.current.approveAmount}`,Z(W.current.expireAt),Oe(W.current.subscriptionId,`subscription`)}C(`payment`),se(await n.toDataURL(e,{width:200,margin:2,errorCorrectionLevel:`H`}))}catch(e){O(e instanceof Error?e.message:x.createPaymentFailed),v?.(e)}finally{E(!1)}},Te=()=>{W.current&&(C(`checking`),O(void 0),d===`instant`?Q({paymentId:W.current.paymentId}):d===`subscription`&&Q({subscriptionId:W.current.subscriptionId}))},Q=e=>{H.current?.unsubscribe();let t=()=>(0,r.defer)(()=>d===`subscription`?b.checkSubscriptionPaymentStatus(e):b.checkOnetimePaymentStatus(e)).pipe((0,i.timeout)(15e3),(0,i.retry)({delay:2e3}));H.current=t().pipe((0,i.expand)(e=>e.status===`pending`?(0,r.timer)(2e3).pipe((0,i.switchMap)(()=>t())):r.EMPTY),(0,i.tap)(e=>{if(!W.current&&d===`instant`){let t=e;W.current={paymentId:t.paymentId,orderId:t.orderId,paymentChain:t.chain,paymentToken:t.token,paymentAmount:t.payAmount,receiveAddress:t.receiveAddress,expireAt:t.expireAt},j(t.chain),N(t.token),Z(t.expireAt);let r=`${t.chain.toLowerCase()}:${t.receiveAddress}?amount=${t.payAmount}`;n.toDataURL(r,{width:200,margin:2,errorCorrectionLevel:`H`}).then(e=>{se(e),C(`payment`)}).catch(e=>{console.error(`生成二维码失败:`,e),C(`payment`)})}if(!W.current&&d===`subscription`){let t=e;W.current={subscriptionId:t.subscriptionId,orderId:t.orderId,paymentChain:t.chain,paymentToken:t.token,approveAmount:t.approveAmount,spenderAddress:t.approvedAddress,expireAt:t.expireAt,intervalDays:0,amountOfUsd:t.amountOfUsd},j(t.chain),N(t.token),Z(t.expireAt);let r=`${t.chain.toLowerCase()}:${t.approvedAddress}?amount=${t.approveAmount}`;n.toDataURL(r,{width:200,margin:2,errorCorrectionLevel:`H`}).then(e=>{se(e),C(`payment`)}).catch(e=>{console.error(`生成二维码失败:`,e),C(`payment`)})}(e.status===`paid`||e.status===`approved`)&&(C(`success`),$(),g?.(e)),e.status===`expired`&&(C(`expired`),$(),re?.(e)),e.status===`failed`&&(C(`failed`),$(),_?.(e))})).subscribe({error:e=>{if(W.current){let t=e instanceof Error?e.message:x.checkPaymentStatusFailed;C(`error`),O(t),v?.(e)}},complete:()=>{H.current?.unsubscribe()}})},Ee=async()=>{if(!W.current)return;let e=d===`subscription`?W.current.spenderAddress:W.current.receiveAddress;if(e)try{await navigator.clipboard.writeText(e),R(!0),setTimeout(()=>{R(!1)},2e3)}catch(e){console.error(`复制失败:`,e)}},De=async()=>{if(B)try{await navigator.clipboard.writeText(B),R(!0),setTimeout(()=>{R(!1)},2e3)}catch(e){console.error(`复制失败:`,e)}},Oe=(e,t)=>{if(!u||typeof window>`u`)return;let n=new URL(window.location.href),r=t===`subscription`?`subscriptionId`:`paymentId`;n.searchParams.set(r,e),window.history.replaceState({},``,n.toString())},$=()=>{if(typeof window>`u`)return;let e=new URL(window.location.href);e.searchParams.delete(`paymentId`),e.searchParams.delete(`subscriptionId`),window.history.replaceState({},``,e.toString())};return(0,s.useEffect)(()=>{k.length===0&&ye()},[]),(0,s.useEffect)(()=>{q.length>0&&N(q[0].symbol)},[q]),(0,s.useEffect)(()=>{if(typeof window>`u`)return;let e=new URL(window.location.href);if(d===`instant`){let t=e.searchParams.get(`paymentId`);t&&(C(`payment`),Q({paymentId:t}))}if(d===`subscription`){let t=e.searchParams.get(`subscriptionId`);t&&(C(`payment`),Q({subscriptionId:t}))}},[]),(0,s.useEffect)(()=>()=>{H.current?.unsubscribe(),_e()},[]),(0,c.jsx)(`div`,{className:`_cppay-content`,children:S===`success`?y?.Success?(0,c.jsx)(y.Success,{paymentInfo:W.current}):(0,c.jsxs)(`div`,{className:`_cppay-state-container`,children:[(0,c.jsx)(`div`,{className:`_cppay-state-success-bg`,children:(0,c.jsx)(`div`,{className:`_cppay-state-success-icon`,children:`✓`})}),(0,c.jsx)(`h3`,{className:`_cppay-state-title _cppay-state-title-success`,children:d===`subscription`?x.authorizationSuccess:x.paymentSuccess}),B&&(0,c.jsxs)(`div`,{className:`_cppay-state-hash-container`,children:[(0,c.jsx)(`div`,{className:`_cppay-state-label`,children:x.transactionHash}),(0,c.jsxs)(`div`,{className:`_cppay-hash-row`,children:[(0,c.jsx)(`code`,{className:`_cppay-state-hash`,children:B}),(0,c.jsx)(`button`,{onClick:De,className:`_cppay-state-copy-btn`,title:x.copyAddress,children:(0,c.jsxs)(`svg`,{viewBox:`0 0 24 24`,fill:`none`,stroke:`currentColor`,strokeWidth:`2`,children:[(0,c.jsx)(`path`,{d:`M16 4h2a2 2 0 0 1 2 2v14a2 2 0 0 1-2 2H6a2 2 0 0 1-2-2V6a2 2 0 0 1 2-2h2`}),(0,c.jsx)(`rect`,{x:`8`,y:`2`,width:`8`,height:`4`,rx:`1`,ry:`1`})]})})]})]}),W.current&&(0,c.jsxs)(`div`,{className:`_cppay-success-details`,children:[(0,c.jsxs)(`div`,{className:`_cppay-detail-item`,children:[(0,c.jsx)(`span`,{className:`_cppay-detail-label`,children:x.orderId}),(0,c.jsx)(`span`,{className:`_cppay-detail-value`,children:W.current.orderId})]}),(0,c.jsxs)(`div`,{className:`_cppay-detail-item`,children:[(0,c.jsx)(`span`,{className:`_cppay-detail-label`,children:d===`subscription`?x.authorizationAmount:x.paymentAmount}),(0,c.jsx)(`span`,{className:`_cppay-detail-value`,children:d===`subscription`?`${X(W.current.approveAmount,Y(M))} ${M}`:`${X(W.current.paymentAmount,Y(M))} ${M}`})]}),(0,c.jsxs)(`div`,{className:`_cppay-detail-item`,children:[(0,c.jsx)(`span`,{className:`_cppay-detail-label`,children:x.paymentNetwork}),(0,c.jsx)(`span`,{className:`_cppay-detail-value`,children:W.current.paymentChain})]}),(0,c.jsxs)(`div`,{className:`_cppay-detail-item`,children:[(0,c.jsx)(`span`,{className:`_cppay-detail-label`,children:x.paymentToken}),(0,c.jsx)(`span`,{className:`_cppay-detail-value`,children:W.current.paymentToken})]}),d===`subscription`&&(0,c.jsxs)(`div`,{className:`_cppay-detail-item`,children:[(0,c.jsx)(`span`,{className:`_cppay-detail-label`,children:x.renewalInterval}),(0,c.jsxs)(`span`,{className:`_cppay-detail-value`,children:[W.current.intervalDays,` `,x.days]})]}),(0,c.jsxs)(`div`,{className:`_cppay-detail-item`,children:[(0,c.jsx)(`span`,{className:`_cppay-detail-label`,children:d===`subscription`?x.subscriptionId:x.paymentId}),(0,c.jsx)(`span`,{className:`_cppay-detail-value _cppay-detail-id`,children:d===`subscription`?W.current.subscriptionId:W.current.paymentId})]})]})]}):S===`expired`?y?.Expired?(0,c.jsx)(y.Expired,{paymentInfo:W.current}):(0,c.jsxs)(`div`,{className:`_cppay-state-container`,children:[(0,c.jsx)(`div`,{className:`_cppay-state-expired-bg`,children:(0,c.jsx)(`div`,{className:`_cppay-state-expired-icon`,children:`⏰`})}),(0,c.jsx)(`h3`,{className:`_cppay-state-title _cppay-state-title-expired`,children:x.paymentExpired}),(0,c.jsx)(`p`,{className:`_cppay-state-message`,children:x.pleaseInitiatePaymentAgain}),(0,c.jsx)(`button`,{onClick:()=>{C(`select`),$()},disabled:T||w,className:`_cppay-btn _cppay-btn-primary _cppay-state-btn`,children:x.returnButton})]}):S===`error`?y?.Error?(0,c.jsx)(y.Error,{paymentInfo:W.current}):(0,c.jsxs)(`div`,{className:`_cppay-state-container`,children:[(0,c.jsx)(`div`,{className:`_cppay-state-error-bg`,children:(0,c.jsx)(`div`,{className:`_cppay-state-error-icon`,children:`!`})}),(0,c.jsx)(`h3`,{className:`_cppay-state-title _cppay-state-title-error`,children:D||x.error}),(0,c.jsx)(`p`,{className:`_cppay-state-message`,children:x.checkStatusFailed}),(0,c.jsx)(`button`,{onClick:()=>{C(`select`),$()},disabled:T||w,className:`_cppay-btn _cppay-btn-primary _cppay-state-btn`,children:x.returnButton})]}):S===`failed`?y?.Failed?(0,c.jsx)(y.Failed,{paymentInfo:W.current}):(0,c.jsxs)(`div`,{className:`_cppay-state-container`,children:[(0,c.jsx)(`div`,{className:`_cppay-state-failed-bg`,children:(0,c.jsx)(`div`,{className:`_cppay-state-failed-icon`,children:`✕`})}),(0,c.jsx)(`h3`,{className:`_cppay-state-title _cppay-state-title-failed`,children:x.paymentFailed}),(0,c.jsx)(`p`,{className:`_cppay-state-message`,children:x.pleaseInitiatePaymentAgain}),(0,c.jsx)(`button`,{onClick:()=>{C(`select`),$()},disabled:T||w,className:`_cppay-btn _cppay-btn-primary _cppay-state-btn`,children:x.returnButton})]}):S===`select`?(0,c.jsxs)(`div`,{children:[y?.ChooseTop,(0,c.jsxs)(`div`,{className:`_cppay-section`,children:[(0,c.jsx)(`label`,{className:`_cppay-label`,children:x.paymentNetwork}),(0,c.jsx)(`div`,{className:`_cppay-grid`,children:k.map(e=>(0,c.jsxs)(`button`,{onClick:()=>j(e.chain),className:`_cppay-select-btn ${A===e.chain?`_cppay-selected`:``}`,children:[e.icon&&(0,c.jsx)(`img`,{src:e.icon,alt:e.chain}),(0,c.jsx)(`span`,{children:e.chain})]},e.chain))})]}),(0,c.jsxs)(`div`,{className:`_cppay-section`,children:[(0,c.jsx)(`label`,{className:`_cppay-label`,children:x.paymentToken}),(0,c.jsx)(`div`,{className:`_cppay-grid`,children:q.map(e=>(0,c.jsxs)(`button`,{onClick:()=>N(e.symbol),className:`_cppay-select-btn ${M===e.symbol?`_cppay-selected`:``}`,children:[e.icon&&(0,c.jsx)(`img`,{src:e.icon,alt:e.symbol}),(0,c.jsx)(`span`,{children:e.symbol})]},e.symbol))})]}),y?.ChooseBottom,(0,c.jsx)(`div`,{className:`_cppay-section`,children:(0,c.jsx)(`div`,{className:`_cppay-price-box`,children:(0,c.jsxs)(`div`,{className:`_cppay-price-row`,children:[(0,c.jsx)(`span`,{className:`_cppay-price-label`,children:x.paymentAmount}),(0,c.jsxs)(`div`,{className:`_cppay-price-amount`,children:[(0,c.jsxs)(`div`,{className:`_cppay-price-main`,children:[ve??`-`,` `,M??``]}),(0,c.jsxs)(`div`,{className:`_cppay-price-sub`,children:[`≈ $`,p]})]})]})})}),(0,c.jsxs)(`div`,{className:`_cppay-section`,children:[D&&(0,c.jsxs)(`div`,{className:`_cppay-error-tooltip-wrapper`,onMouseEnter:()=>z(!0),onMouseLeave:()=>z(!1),children:[(0,c.jsxs)(`div`,{className:`_cppay-error-tooltip`,children:[(0,c.jsx)(`svg`,{viewBox:`0 0 20 20`,fill:`currentColor`,children:(0,c.jsx)(`path`,{fillRule:`evenodd`,d:`M10 18a8 8 0 100-16 8 8 0 000 16zM8.707 7.293a1 1 0 00-1.414 1.414L8.586 10l-1.293 1.293a1 1 0 101.414 1.414L10 11.414l1.293 1.293a1 1 0 001.414-1.414L11.414 10l1.293-1.293a1 1 0 00-1.414-1.414L10 8.586 8.707 7.293z`,clipRule:`evenodd`})}),(0,c.jsx)(`span`,{children:D})]}),pe&&(0,c.jsx)(`div`,{className:`_cppay-error-tooltip-full`,children:D})]}),(0,c.jsx)(`button`,{onClick:we,disabled:!A||!M||T,className:`_cppay-btn _cppay-btn-primary`,children:T?x.processing:x.continuePayment})]})]}):(0,c.jsxs)(`div`,{children:[(0,c.jsx)(`div`,{className:`_cppay-qr-container`,children:(0,c.jsx)(`div`,{className:`_cppay-qr-code`,children:oe&&(0,c.jsx)(`img`,{src:oe,alt:`Payment QR Code`,className:`_cppay-qr-image`})})}),(0,c.jsxs)(`div`,{className:`_cppay-section`,children:[J&&(0,c.jsx)(`div`,{className:`_cppay-info-box`,children:(0,c.jsx)(`div`,{className:`_cppay-info-flex-container`,children:(0,c.jsxs)(`div`,{className:`_cppay-info-flex-child`,children:[(0,c.jsx)(`div`,{className:`_cppay-info-label`,children:d===`subscription`?x.authorizationAmount:x.paymentAmount}),(0,c.jsxs)(`div`,{className:`_cppay-info-value _cppay-info-value-flex`,children:[W.current&&(0,c.jsx)(`span`,{children:d===`subscription`?`${X(W.current.approveAmount,Y(J.symbol))} ${J.symbol}`:`${X(W.current.paymentAmount,Y(J.symbol))} ${J.symbol}`}),(0,c.jsxs)(`span`,{children:[`≈ $`,p]})]})]})})}),(0,c.jsx)(`div`,{className:`_cppay-info-box`,children:(0,c.jsxs)(`div`,{className:`_cppay-info-flex-child`,children:[(0,c.jsxs)(`div`,{className:`_cppay-info-label _cppay-info-label-flex`,children:[(0,c.jsx)(`span`,{children:d===`subscription`?x.authorizationContractAddress:x.paymentAddress}),de&&(0,c.jsxs)(`span`,{className:`_cppay-countdown`,children:[`⏰ `,de]})]}),(0,c.jsxs)(`div`,{className:`_cppay-address-row`,children:[W.current&&(0,c.jsx)(`code`,{children:d===`subscription`?W.current.spenderAddress:W.current.receiveAddress}),(0,c.jsx)(`button`,{onClick:Ee,className:`_cppay-copy-btn ${L?`_cppay-copy-success`:``}`,title:L?x.copied:x.copyAddress,children:L?(0,c.jsx)(`svg`,{className:`_cppay-copy-icon`,viewBox:`0 0 24 24`,fill:`currentColor`,children:(0,c.jsx)(`path`,{d:`M9 16.17L4.83 12l-1.42 1.41L9 19 21 7l-1.41-1.41z`})}):(0,c.jsxs)(`svg`,{className:`_cppay-copy-icon`,viewBox:`0 0 24 24`,fill:`none`,stroke:`currentColor`,strokeWidth:`2`,children:[(0,c.jsx)(`path`,{d:`M16 4h2a2 2 0 0 1 2 2v14a2 2 0 0 1-2 2H6a2 2 0 0 1-2-2V6a2 2 0 0 1 2-2h2`}),(0,c.jsx)(`rect`,{x:`8`,y:`2`,width:`8`,height:`4`,rx:`1`,ry:`1`})]})})]})]})}),d===`subscription`&&(0,c.jsxs)(`div`,{className:`_cppay-info-box _cppay-subscription-box`,children:[(0,c.jsx)(`div`,{className:`_cppay-info-label _cppay-subscription-label`,children:x.subscriptionNotice}),(0,c.jsx)(`div`,{className:`_cppay-info-value _cppay-subscription-message`,children:x.subscriptionNoticeMessage})]})]}),D&&(0,c.jsxs)(`div`,{className:`_cppay-error-tooltip-wrapper`,onMouseEnter:()=>z(!0),onMouseLeave:()=>z(!1),children:[(0,c.jsxs)(`div`,{className:`_cppay-error-tooltip`,children:[(0,c.jsx)(`svg`,{viewBox:`0 0 20 20`,fill:`currentColor`,children:(0,c.jsx)(`path`,{fillRule:`evenodd`,d:`M10 18a8 8 0 100-16 8 8 0 000 16zM8.707 7.293a1 1 0 00-1.414 1.414L8.586 10l-1.293 1.293a1 1 0 101.414 1.414L10 11.414l1.293 1.293a1 1 0 001.414-1.414L11.414 10l1.293-1.293a1 1 0 00-1.414-1.414L10 8.586 8.707 7.293z`,clipRule:`evenodd`})}),(0,c.jsx)(`span`,{children:D})]}),pe&&(0,c.jsx)(`div`,{className:`_cppay-error-tooltip-full`,children:D})]}),!w&&(0,c.jsx)(`div`,{className:`_cppay-section`,children:P?(0,c.jsxs)(c.Fragment,{children:[(0,c.jsx)(`button`,{onClick:Ce,disabled:T,className:`_cppay-btn _cppay-btn-primary`,children:T?d===`subscription`?x.authorizing:x.processing:d===`subscription`?`💳 ${x.connectWallet}`:`💳 ${x.walletPay}`}),(0,c.jsxs)(`button`,{onClick:he,disabled:T,className:`_cppay-btn _cppay-wallet-address-btn`,title:x.clickToModifyWallet,children:[(0,c.jsxs)(`span`,{className:`_cppay-wallet-address-text`,children:[P.slice(0,10),`...`,P.slice(-4)]}),(0,c.jsx)(`svg`,{className:`_cppay-wallet-arrow`,viewBox:`0 0 24 24`,fill:`none`,stroke:`currentColor`,strokeWidth:`2`,children:(0,c.jsx)(`polyline`,{points:`6 9 12 15 18 9`})})]})]}):(0,c.jsx)(`button`,{onClick:he,disabled:ce,className:`_cppay-btn _cppay-btn-secondary _cppay-connect-wallet-btn`,children:(0,c.jsx)(`span`,{children:ce?x.processing:`💳 ${x.connectWallet}`})})}),(0,c.jsx)(`div`,{className:`_cppay-section`,children:(0,c.jsx)(`button`,{onClick:Te,disabled:w,className:`_cppay-btn _cppay-btn-primary`,children:w?(0,c.jsxs)(c.Fragment,{children:[(0,c.jsxs)(`svg`,{className:`_cppay-spinner`,viewBox:`0 0 24 24`,fill:`none`,xmlns:`http://www.w3.org/2000/svg`,children:[(0,c.jsx)(`circle`,{cx:`12`,cy:`12`,r:`10`,stroke:`currentColor`,strokeWidth:`3`,strokeOpacity:`0.25`}),(0,c.jsx)(`path`,{d:`M12 2a10 10 0 0 1 10 10`,stroke:`currentColor`,strokeWidth:`3`,strokeLinecap:`round`})]}),x.checking]}):x.completedPayment})}),(0,c.jsx)(`hr`,{className:`_cppay-divider`}),(0,c.jsx)(`div`,{className:`_cppay-section`,children:(0,c.jsx)(`button`,{onClick:()=>{C(`select`),$()},disabled:T||w,className:`_cppay-btn _cppay-btn-text`,children:x.changePaymentMethod})})]})})},u=l,d=({open:t,onClose:n,ott:r,apikey:i,plain:a,orderId:o,amount:ee,intervalDays:te,remark:l,locale:d,onExpired:f,onSuccess:p,onFailed:m,onError:ne,Slots:h})=>{let[g,re]=(0,s.useState)(`select`),_=(0,s.useMemo)(()=>g!==`checking`,[g]);(0,s.useEffect)(()=>{t||re(`select`)},[t]),(0,s.useEffect)(()=>{if(!t)return;let e=e=>{e.key===`Escape`&&_&&v()};return window.addEventListener(`keydown`,e),()=>window.removeEventListener(`keydown`,e)},[t,_]);let v=()=>{_&&n()},y=(0,s.useMemo)(()=>e.t(d),[d]);return t?(0,c.jsx)(`div`,{className:`_cppay-overlay`,onClick:e=>e.target===e.currentTarget&&v(),children:(0,c.jsxs)(`div`,{className:`_cppay-dialog`,children:[(0,c.jsxs)(`div`,{className:`_cppay-header`,children:[(0,c.jsx)(`h2`,{className:`_cppay-title`,children:(()=>{switch(g){case`success`:return y.paymentResult;case`expired`:return y.paymentExpired;case`failed`:return y.paymentFailed;case`error`:return y.error;case`payment`:case`checking`:return y.completePayment;default:return y.selectPaymentMethod}})()}),(0,c.jsx)(`button`,{onClick:v,disabled:!_,className:`_cppay-close-btn`,children:(0,c.jsx)(`svg`,{fill:`none`,stroke:`currentColor`,viewBox:`0 0 24 24`,children:(0,c.jsx)(`path`,{strokeLinecap:`round`,strokeLinejoin:`round`,strokeWidth:2,d:`M6 18L18 6M6 6l12 12`})})})]}),(0,c.jsx)(u,{apikey:i,ott:r,plain:a,orderId:o,amount:ee,intervalDays:te,remark:l,locale:d,onSuccess:p,onExpired:f,onFailed:m,onError:ne,Slots:h,onPaymentStepChange:re})]})}):null},f=d,p=(0,s.createContext)(null);const m=({children:e})=>{let[t,n]=(0,s.useState)(!1),[r,i]=(0,s.useState)(null),a=(0,s.useCallback)(e=>{i(e),n(!0)},[]),o=(0,s.useCallback)(()=>{n(!1)},[]),ee=(0,s.useCallback)(()=>{n(!1)},[]),te=(0,s.useCallback)(e=>{r?.onSuccess?.(e)},[r]),l=(0,s.useCallback)(e=>{r?.onExpired?.(e)},[r]),u=(0,s.useCallback)(e=>{r?.onFailed?.(e)},[r]),d=(0,s.useCallback)(e=>{r?.onError?.(e)},[r]);return(0,c.jsxs)(p.Provider,{value:{showPayment:a,closePayment:o},children:[e,r&&(0,c.jsx)(f,{open:t,onClose:ee,...r,onSuccess:te,onExpired:l,onFailed:u,onError:d})]})},ne=()=>{let e=(0,s.useContext)(p);if(!e)throw Error(`useCppayPayment must be used within CppayProvider`);return e};e.n(e.r),exports.CppayProvider=m,exports.PaymentContent=u,exports.PaymentDialog=f,exports.useCppayPayment=ne;
package/dist/react.d.ts CHANGED
@@ -1,15 +1,244 @@
1
1
  import { default as default_2 } from 'react';
2
+ import { ReactNode } from 'react';
2
3
 
3
- export declare const PaymentDialog: default_2.NamedExoticComponent<PaymentDialogProps>;
4
+ declare type Address = `0x${string}`;
5
+
6
+ /**
7
+ * CPPay 上下文值
8
+ */
9
+ declare interface CppayContextValue {
10
+ /** 显示支付对话框 */
11
+ showPayment: (options: PaymentOptions_2) => void;
12
+ /** 关闭支付对话框 */
13
+ closePayment: () => void;
14
+ }
15
+
16
+ /**
17
+ * CPPay Provider 组件
18
+ * 提供支付功能的上下文提供者
19
+ */
20
+ export declare const CppayProvider: default_2.FC<CppayProviderProps>;
21
+
22
+ declare interface CppayProviderProps {
23
+ /** API Key */
24
+ children: ReactNode;
25
+ }
26
+
27
+ export declare type Locale = "zh-CN" | "en-US";
28
+
29
+ declare type Numberic = `${number}.${number}` | `${number}`;
30
+
31
+ declare interface OnetimePaymentInfo {
32
+ orderId: string;
33
+ paymentId: string;
34
+ paymentAmount: Numberic;
35
+ paymentChain: string;
36
+ paymentToken: string;
37
+ receiveAddress: Address;
38
+ expireAt: number;
39
+ }
40
+
41
+ declare interface OnetimePaymentOrderStatus {
42
+ orderId: string;
43
+ paymentId: string;
44
+ chain: string;
45
+ token: string;
46
+ baseAmount: Numberic;
47
+ payAmount: Numberic;
48
+ receiveAddress: Address;
49
+ expireAt: number;
50
+ status: PaymentStatus;
51
+ }
52
+
53
+ /**
54
+ * PaymentContent - 支付内容组件(纯页面样式和逻辑)
55
+ *
56
+ * 这是一个独立的内容组件,包含所有支付相关的UI和业务逻辑。
57
+ * 可以单独使用,也可以被PaymentDialog弹框包装。
58
+ *
59
+ * @example
60
+ * ```tsx
61
+ * <PaymentContent
62
+ * apikey="your-api-key"
63
+ * plain="instant"
64
+ * orderId="order-123"
65
+ * amount="100"
66
+ * onSuccess={(order) => console.log('支付成功', order)}
67
+ * />
68
+ * ```
69
+ */
70
+ export declare const PaymentContent: default_2.FC<PaymentContentProps>;
71
+
72
+ declare interface PaymentContentProps {
73
+ /** API Key */
74
+ apikey?: string;
75
+ /** One-Time Token */
76
+ ott?: string;
77
+ /** 支付类型 */
78
+ plain: PaymentPlain;
79
+ /** 订单 ID */
80
+ orderId: string;
81
+ /** 支付金额(USD) */
82
+ amount: string;
83
+ /** 订阅间隔天数 */
84
+ intervalDays?: number;
85
+ /** 备注信息 */
86
+ remark?: string;
87
+ /** 语言设置 */
88
+ locale?: Locale;
89
+ /** 支付成功回调 */
90
+ onSuccess?: (order: SubscriptionPaymentOrderStatus | OnetimePaymentOrderStatus) => void;
91
+ /** 支付过期回调 */
92
+ onExpired?: (order: SubscriptionPaymentOrderStatus | OnetimePaymentOrderStatus) => void;
93
+ /** 支付失败回调 */
94
+ onFailed?: (order: SubscriptionPaymentOrderStatus | OnetimePaymentOrderStatus) => void;
95
+ /** 支付错误回调 */
96
+ onError?: (error: Error) => void;
97
+ /** 插槽,定义自己想要展示的内容 */
98
+ Slots?: Partial<{
99
+ ChooseTop: default_2.ReactNode;
100
+ ChooseBottom: default_2.ReactNode;
101
+ Success: default_2.FC<{
102
+ paymentInfo: OnetimePaymentInfo | SubscriptionPaymentInfo;
103
+ }>;
104
+ Expired: default_2.FC<{
105
+ paymentInfo: OnetimePaymentInfo | SubscriptionPaymentInfo;
106
+ }>;
107
+ Failed: default_2.FC<{
108
+ paymentInfo: OnetimePaymentInfo | SubscriptionPaymentInfo;
109
+ }>;
110
+ Error: default_2.FC<{
111
+ paymentInfo: OnetimePaymentInfo | SubscriptionPaymentInfo;
112
+ }>;
113
+ }>;
114
+ /** 支付步骤状态变化回调 */
115
+ onPaymentStepChange?: (step: PaymentStep) => void;
116
+ }
117
+
118
+ /**
119
+ * PaymentDialog - 支付弹框组件
120
+ *
121
+ * 这是一个纯弹框包装器,负责:
122
+ * - 管理弹框的打开/关闭状态和动画
123
+ * - 处理弹框的UI包装(背景遮罩、标题栏、关闭按钮)
124
+ * - 将 PaymentContent 内容组件嵌入弹框中
125
+ *
126
+ * 弹框关闭的自动重置逻辑:
127
+ * - 支付完成后 1000ms 自动关闭
128
+ * - 关闭后重置内部状态(支付步骤、错误等)
129
+ *
130
+ * @example
131
+ * ```tsx
132
+ * <PaymentDialog
133
+ * open={isOpen}
134
+ * onClose={() => setIsOpen(false)}
135
+ * apikey="your-api-key"
136
+ * plain="instant"
137
+ * orderId="order-123"
138
+ * amount="100"
139
+ * onSuccess={(order) => console.log('支付成功', order)}
140
+ * />
141
+ * ```
142
+ */
143
+ export declare const PaymentDialog: default_2.FC<PaymentDialogProps>;
4
144
 
5
145
  declare interface PaymentDialogProps {
146
+ /** 是否打开支付对话框 */
6
147
  open: boolean;
148
+ /** 关闭对话框回调 */
7
149
  onClose: () => void;
8
- apiKey: string;
150
+ /** API Key */
151
+ apikey?: string;
152
+ /** One-Time Token */
153
+ ott?: string;
154
+ /** 支付类型 */
155
+ plain: PaymentPlain;
156
+ /** 订单 ID */
9
157
  orderId: string;
158
+ /** 支付金额(USD) */
10
159
  amount: string;
11
- onSuccess?: (paymentId: string) => void;
160
+ /** 订阅间隔天数 */
161
+ intervalDays?: number;
162
+ /** 备注信息 */
163
+ remark?: string;
164
+ /** 语言设置 */
165
+ locale?: Locale;
166
+ /** 支付成功回调 */
167
+ onSuccess?: (order: SubscriptionPaymentOrderStatus | OnetimePaymentOrderStatus) => void;
168
+ /** 支付过期回调 */
169
+ onExpired?: (order: SubscriptionPaymentOrderStatus | OnetimePaymentOrderStatus) => void;
170
+ /** 支付失败回调 */
171
+ onFailed?: (order: SubscriptionPaymentOrderStatus | OnetimePaymentOrderStatus) => void;
172
+ /** 支付错误回调 */
12
173
  onError?: (error: Error) => void;
174
+ /** 插槽,定义自己想要展示的内容 */
175
+ Slots?: Partial<{
176
+ ChooseTop: default_2.ReactNode;
177
+ ChooseBottom: default_2.ReactNode;
178
+ Success: default_2.FC<{
179
+ paymentInfo: OnetimePaymentInfo | SubscriptionPaymentInfo;
180
+ }>;
181
+ Expired: default_2.FC<{
182
+ paymentInfo: OnetimePaymentInfo | SubscriptionPaymentInfo;
183
+ }>;
184
+ Failed: default_2.FC<{
185
+ paymentInfo: OnetimePaymentInfo | SubscriptionPaymentInfo;
186
+ }>;
187
+ Error: default_2.FC<{
188
+ paymentInfo: OnetimePaymentInfo | SubscriptionPaymentInfo;
189
+ }>;
190
+ }>;
191
+ }
192
+
193
+ declare type PaymentOptions_2 = Omit<PaymentDialogProps, "open" | "onClose">;
194
+
195
+ declare type PaymentPlain = "instant" | "subscription" | "x402";
196
+
197
+ declare type PaymentStatus = "pending" | "paid" | "expired" | "failed";
198
+
199
+ declare type PaymentStep = "select" | "payment" | "checking" | "success" | "failed" | "expired" | "error";
200
+
201
+ declare interface SubscriptionPaymentInfo {
202
+ subscriptionId: string;
203
+ approveAmount: Numberic;
204
+ spenderAddress: Address;
205
+ expireAt: number;
206
+ paymentChain: string;
207
+ paymentToken: string;
208
+ orderId: string;
209
+ amountOfUsd: Numberic;
210
+ intervalDays: number;
211
+ }
212
+
213
+ declare interface SubscriptionPaymentOrderStatus {
214
+ orderId: string;
215
+ subscriptionId: string;
216
+ chain: string;
217
+ token: string;
218
+ approvedAddress: string;
219
+ txHash: string;
220
+ approveAmount: string;
221
+ amountOfUsd: string;
222
+ expireAt: number;
223
+ status: SubscriptionPaymentStatus;
13
224
  }
14
225
 
226
+ declare type SubscriptionPaymentStatus = "pending" | "approved" | "expired" | "failed";
227
+
228
+ /**
229
+ * 使用 CPPay 支付钩子
230
+ * @throws {Error} 如果在 CppayProvider 外使用会抛出错误
231
+ */
232
+ export declare const useCppayPayment: () => CppayContextValue;
233
+
15
234
  export { }
235
+
236
+
237
+ declare module "@vue/runtime-core" {
238
+ interface ComponentCustomProperties {
239
+ /** 显示支付对话框的全局方法 */
240
+ $showPayment: typeof showPayment;
241
+ /** 关闭支付对话框的全局方法 */
242
+ $closePayment: typeof closePayment;
243
+ }
244
+ }