cppay-sdk 0.0.2-beta.20 → 0.0.2-beta.22
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/{cppay-LnYTnh4d.js → cppay-BcCDwXlg.js} +4 -2
- package/dist/cppay-DnxPUyM2.cjs +1 -0
- package/dist/cppay-sdk.css +1 -1
- package/dist/index.cjs +1 -1
- package/dist/index.d.ts +8 -0
- package/dist/index.js +1 -1
- package/dist/react.cjs +1 -1
- package/dist/react.d.ts +7 -0
- package/dist/react.js +400 -141
- package/dist/vue.cjs +1 -1
- package/dist/vue.d.ts +68 -8
- package/dist/vue.js +404 -123
- package/dist/walletconnect-B0L70Mgc.js +1239 -0
- package/dist/walletconnect-B_n5YF-h.cjs +8 -0
- package/package.json +8 -2
- package/dist/browser-B4fiRjvC.cjs +0 -8
- package/dist/browser-Dm8HHcNy.js +0 -1239
- package/dist/cppay-ClXaSwp8.cjs +0 -1
|
@@ -54,7 +54,8 @@ var BASE_URL = "http://192.168.0.162:8000", request = async (e, t, r) => {
|
|
|
54
54
|
chainId: e.chain_id,
|
|
55
55
|
tokenSymbol: e.token_symbol,
|
|
56
56
|
tokenDecimals: e.token_decimals,
|
|
57
|
-
tokenAddress: e.token_address
|
|
57
|
+
tokenAddress: e.token_address,
|
|
58
|
+
tokenPrice: e.token_price
|
|
58
59
|
}));
|
|
59
60
|
}
|
|
60
61
|
async createOnetimePayment(e, t, n, r) {
|
|
@@ -172,7 +173,8 @@ var BASE_URL = "http://192.168.0.162:8000", request = async (e, t, r) => {
|
|
|
172
173
|
symbol: r.tokenSymbol,
|
|
173
174
|
decimals: r.tokenDecimals,
|
|
174
175
|
address: r.tokenAddress,
|
|
175
|
-
icon: TOKEN_ICONS[r.tokenSymbol]
|
|
176
|
+
icon: TOKEN_ICONS[r.tokenSymbol],
|
|
177
|
+
price: r.tokenPrice
|
|
176
178
|
}), n[r.chain] = i, n;
|
|
177
179
|
}, {});
|
|
178
180
|
return Object.values(n);
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
const e={Ethereum:`https://raw.githubusercontent.com/trustwallet/assets/master/blockchains/ethereum/info/logo.png`,BSC:`https://raw.githubusercontent.com/trustwallet/assets/master/blockchains/binance/info/logo.png`,"bsc-testnet":`https://raw.githubusercontent.com/trustwallet/assets/master/blockchains/binance/info/logo.png`,Tron:`https://raw.githubusercontent.com/trustwallet/assets/master/blockchains/tron/info/logo.png`,Polygon:`https://raw.githubusercontent.com/trustwallet/assets/master/blockchains/polygon/info/logo.png`,Solana:`https://raw.githubusercontent.com/trustwallet/assets/master/blockchains/solana/info/logo.png`},t={USDT:`https://raw.githubusercontent.com/trustwallet/assets/master/blockchains/ethereum/assets/0xdAC17F958D2ee523a2206206994597C13D831ec7/logo.png`,USDC:`https://raw.githubusercontent.com/trustwallet/assets/master/blockchains/ethereum/assets/0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48/logo.png`,ETH:`https://raw.githubusercontent.com/trustwallet/assets/master/blockchains/ethereum/info/logo.png`,BNB:`https://raw.githubusercontent.com/trustwallet/assets/master/blockchains/binance/info/logo.png`,tBNB:`https://raw.githubusercontent.com/trustwallet/assets/master/blockchains/binance/info/logo.png`,TRX:`https://raw.githubusercontent.com/trustwallet/assets/master/blockchains/tron/info/logo.png`,SOL:`https://raw.githubusercontent.com/trustwallet/assets/master/blockchains/solana/info/logo.png`};var n=`http://192.168.0.162:8000`,r=async(e,t,r)=>{let i=Object.assign({timeout:15e3},r),a=new AbortController,o=setTimeout(()=>a.abort(),i.timeout);try{let r=await fetch(new URL(e,n),{signal:a.signal,...t});clearTimeout(o);let i=r.headers.get(`Content-Type`)??``;if(i.includes(`json`))return await r.json();try{return await r.json()}catch{throw Error(`URL: ${e}, Unsupport Content Type: ${i}`)}}catch(t){throw clearTimeout(o),t instanceof DOMException&&t.name===`AbortError`?Error(`URL: ${e}, Request timeout after ${i.timeout}ms`):t}},i=0,a=async(e,t)=>{let n=new URLSearchParams(t.params),a=await r(`${t.url}${n.size?`?${n.toString()}`:``}`,{method:t.method??`get`,headers:{Authorization:e,...t.headers},body:t.data?JSON.stringify(t.data):void 0});if(a.code!==i)throw Error(`Request ${t.url} Failed. ${a.message}`);return a.data},o=class{apikey;constructor(e){this.apikey=e}async getSupportedChains(){return(await a(this.apikey,{url:`/api/payment/token`})).map(e=>({chain:e.chain,chainId:e.chain_id,tokenSymbol:e.token_symbol,tokenDecimals:e.token_decimals,tokenAddress:e.token_address,tokenPrice:e.token_price}))}async createOnetimePayment(e,t,n,r){let i={chain:e,token:t,order_no:n,amount:r},o=await a(this.apikey,{url:`/api/payment/create`,method:`post`,data:i});return{paymentId:o.payment_id,paymentAmount:o.pay_amount,receiveAddress:o.receive_address,expireAt:o.expire_at}}async createSubscriptionPayment(e,t,n,r,i){let o={chain:e,token:t,order_no:n,amount_usd:r,renewal_days:i},s=await a(this.apikey,{url:`/api/subscription/create`,method:`post`,data:o});return{subscriptionId:s.subscription_id,approveAmount:s.approved_amount,spenderAddress:s.contract_address,expireAt:s.expire_at}}async createX402Payment(){throw Error(`Unsupported payment mode`)}async checkOnetimePaymentStatus(e){let t={payment_id:e},n=await a(this.apikey,{url:`/api/payment/query`,params:t});return{orderId:n.order_no,paymentId:n.payment_id,chain:n.chain,token:n.token,baseAmount:n.base_amount,payAmount:n.pay_amount,receiveAddress:n.receive_address,expireAt:n.expire_at,status:n.status}}async checkSubcriptionPaymentStatus(e){let t={subscription_id:e},n=await a(this.apikey,{url:`/api/subscription/query`,params:t});return{orderId:n.order_no,subscriptionId:n.subscription_id,chain:n.chain,token:n.token,approvedAddress:n.approved_contract_address,txHash:n.approved_tx_hash,approveAmount:n.approved_amount,amountOfUsd:n.amount_usd,expireAt:n.expire_at,status:n.subscription_status}}async getSubcriptionPayments(e){let t={subscription_id:e},n=await a(this.apikey,{url:`/api/subscription/payments`,params:t});return{total:n.total,payments:(n.payments??[]).map(e=>({orderId:e.order_no,subscriptionId:e.subscription_id,chain:e.chain,token:e.token,txHash:e.tx_hash,payAmount:e.pay_amount,receiveAddress:e.receive_address,status:e.status,errorMessage:e.error_message}))}}async checkX402PaymentStatus(){throw Error(`Unsupported payment mode`)}},s=class{api;constructor(e){this.api=new o(e)}async getSupportedChains(){let n=(await this.api.getSupportedChains()).reduce((n,r)=>{let i=n[r.chain]??{chain:r.chain,chainId:r.chainId,tokens:[],icon:e[r.chain]};return i.tokens.push({symbol:r.tokenSymbol,decimals:r.tokenDecimals,address:r.tokenAddress,icon:t[r.tokenSymbol],price:r.tokenPrice}),n[r.chain]=i,n},{});return Object.values(n)}async createPayment(e,t){switch(e){case`one-time`:return this.createOnetimePayment(t);case`subscription`:return this.createSubscriptionPayment(t)}}async checkPaymentStatus(e,t){switch(e){case`one-time`:return this.checkOnetimePaymentStatus(t);case`subscription`:return this.checkSubscriptionPaymentStatus(t)}}async createOnetimePayment(e){let t=await this.api.createOnetimePayment(e.paymentChain,e.paymentToken,e.orderId,e.amount);return{...e,...t}}async createSubscriptionPayment(e){let t=await this.api.createSubscriptionPayment(e.paymentChain,e.paymentToken,e.orderId,e.amountOfUsd,e.intervalDays);return{...e,...t}}async checkOnetimePaymentStatus(e){return{...await this.api.checkOnetimePaymentStatus(e.paymentId)}}async checkSubscriptionPaymentStatus(e){return{...await this.api.checkSubcriptionPaymentStatus(e.subscriptionId)}}async getSubcriptionPayments(e){return{...await this.api.getSubcriptionPayments(e.subscriptionId)}}},c=s;Object.defineProperty(exports,`n`,{enumerable:!0,get:function(){return e}}),Object.defineProperty(exports,`r`,{enumerable:!0,get:function(){return t}}),Object.defineProperty(exports,`t`,{enumerable:!0,get:function(){return c}});
|
package/dist/cppay-sdk.css
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
._cppay-fade-enter-active[data-v-
|
|
1
|
+
._cppay-fade-enter-active[data-v-1a5fedf2],._cppay-fade-leave-active[data-v-1a5fedf2]{transition:opacity .3s}._cppay-fade-enter-from[data-v-1a5fedf2],._cppay-fade-leave-to[data-v-1a5fedf2]{opacity:0}._cppay-fade-enter-active ._cppay-dialog[data-v-1a5fedf2]{animation:.3s _cppay-slideUp}
|
|
2
2
|
/*$vite$:1*/
|
package/dist/index.cjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
const e=require(`./cppay-
|
|
1
|
+
const e=require(`./cppay-DnxPUyM2.cjs`);exports.CHAIN_ICONS=e.n,exports.Cppay=e.t,exports.TOKEN_ICONS=e.r;
|
package/dist/index.d.ts
CHANGED
|
@@ -121,8 +121,16 @@ export declare const TOKEN_ICONS: Record<string, string>;
|
|
|
121
121
|
export declare interface TokenInfo {
|
|
122
122
|
icon?: string;
|
|
123
123
|
symbol: string;
|
|
124
|
+
price: Numberic;
|
|
124
125
|
decimals: number;
|
|
125
126
|
address: Address | "";
|
|
126
127
|
}
|
|
127
128
|
|
|
128
129
|
export { }
|
|
130
|
+
|
|
131
|
+
|
|
132
|
+
declare module "@vue/runtime-core" {
|
|
133
|
+
interface ComponentCustomProperties {
|
|
134
|
+
$showPayment: typeof showPayment;
|
|
135
|
+
}
|
|
136
|
+
}
|
package/dist/index.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import { n as CHAIN_ICONS, r as TOKEN_ICONS, t as cppay_default } from "./cppay-
|
|
1
|
+
import { n as CHAIN_ICONS, r as TOKEN_ICONS, t as cppay_default } from "./cppay-BcCDwXlg.js";
|
|
2
2
|
export { CHAIN_ICONS, cppay_default as Cppay, TOKEN_ICONS };
|
package/dist/react.cjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
const e=require(`./browser-B4fiRjvC.cjs`),t=require(`./cppay-ClXaSwp8.cjs`);let n=require(`rxjs`),r=require(`rxjs/operators`),i=require(`react`);i=e.i(i);let a=require(`react/jsx-runtime`);var o=e.i(e.t(),1),s=({open:e,onClose:s,apikey:c,plain:l,orderId:u,amount:d,intervalDays:f,onExpired:p,onSuccess:m,onFailed:h,onError:g})=>{let _=(0,i.useMemo)(()=>new t.t(c),[c]),[v,y]=(0,i.useState)(`select`),[b,x]=(0,i.useState)(!1),[S,C]=(0,i.useState)([]),[w,T]=(0,i.useState)(``),[E,D]=(0,i.useState)(``),[O,k]=(0,i.useState)(``),A=(0,i.useRef)(null),j=(0,i.useMemo)(()=>S.find(e=>e.chain===w),[S,w]),M=(0,i.useMemo)(()=>j?.tokens||[],[j]);(0,i.useMemo)(()=>M.find(e=>e.symbol===E),[M,E]);let N=e=>[`USDT`,`USDC`,`BUSD`,`DAI`,`TUSD`,`USDD`,`FDUSD`].includes(e.toUpperCase())?2:6,P=(e,t)=>{let n=parseFloat(e);return isNaN(n)?`0`:n.toFixed(t).replace(/\.?0+$/,``)},F=(0,i.useMemo)(()=>{if(!E)return`0`;let e=N(E);return P((parseFloat(d)/1).toFixed(e),e)},[d,E,1]),I=async()=>{try{x(!0);let e=await _.getSupportedChains();C(e),e.length>0&&T(e[0].chain)}catch(e){g?.(e)}finally{x(!1)}},L=(0,i.useRef)(null),R=async()=>{if(!(!w||!E))try{x(!0);let e=``;l===`one-time`?(L.current=await _.createOnetimePayment({paymentChain:w,paymentToken:E,orderId:u,amount:F}),e=`${w.toLowerCase()}:${L.current.receiveAddress}?amount=${L.current.paymentAmount}`):l===`subscription`&&(L.current=await _.createSubscriptionPayment({paymentChain:w,paymentToken:E,orderId:u,amountOfUsd:F,intervalDays:f||30}),e=`${w.toLowerCase()}:${L.current.spenderAddress}?amount=${L.current.approveAmount}`),y(`payment`),k(await o.toDataURL(e,{width:200,margin:2,errorCorrectionLevel:`H`}))}catch(e){g?.(e)}finally{x(!1)}},z=async()=>{if(L.current)try{x(!0),l===`one-time`&&B(L.current.subscriptionId),l===`subscription`&&B(L.current.paymentId)}catch(e){console.error(`支付状态检查错误:`,e),g?.(e)}finally{x(!1)}},B=e=>{let t=()=>(0,n.defer)(()=>l===`subscription`?_.checkSubscriptionPaymentStatus({subscriptionId:e}):_.checkOnetimePaymentStatus({paymentId:e})).pipe((0,r.timeout)(15e3),(0,r.retry)({count:3,delay:2e3}));A.current?.unsubscribe(),A.current=t().pipe((0,r.expand)(e=>e.status===`pending`?(0,n.timer)(2e3).pipe((0,r.switchMap)(()=>t())):n.EMPTY),(0,r.tap)(e=>{e.status===`expired`&&p?.(e),e.status===`paid`&&(m?.(e),H()),e.status===`failed`&&h?.(e),e.status===`approved`&&(m?.(e),H())})).subscribe({error:e=>{console.error(`支付状态检查错误:`,e),g?.(e)}})},V=async()=>{if(!L.current)return;let e=l===`subscription`?L.current.spenderAddress:L.current.receiveAddress;e&&await navigator.clipboard.writeText(e)},H=()=>{s(),setTimeout(()=>{y(`select`),L.current=null},300)};return(0,i.useEffect)(()=>{e&&S.length===0&&I()},[e]),(0,i.useEffect)(()=>{M.length>0&&D(M[0].symbol)},[M]),(0,i.useEffect)(()=>()=>{A.current?.unsubscribe()},[]),e?(0,a.jsx)(`div`,{className:`_cppay-overlay`,onClick:e=>e.target===e.currentTarget&&H(),children:(0,a.jsxs)(`div`,{className:`_cppay-dialog`,children:[(0,a.jsxs)(`div`,{className:`_cppay-header`,children:[(0,a.jsx)(`h2`,{className:`_cppay-title`,children:v===`select`?`选择支付方式`:`完成支付`}),(0,a.jsx)(`button`,{onClick:H,disabled:b,className:`_cppay-close-btn`,children:(0,a.jsx)(`svg`,{fill:`none`,stroke:`currentColor`,viewBox:`0 0 24 24`,children:(0,a.jsx)(`path`,{strokeLinecap:`round`,strokeLinejoin:`round`,strokeWidth:2,d:`M6 18L18 6M6 6l12 12`})})})]}),(0,a.jsx)(`div`,{className:`_cppay-content`,children:v===`select`?(0,a.jsxs)(`div`,{children:[(0,a.jsxs)(`div`,{className:`_cppay-section`,children:[(0,a.jsx)(`label`,{className:`_cppay-label`,children:`支付网络`}),(0,a.jsx)(`div`,{className:`_cppay-grid`,children:S.map(e=>(0,a.jsxs)(`button`,{onClick:()=>T(e.chain),className:`_cppay-select-btn ${w===e.chain?`_cppay-selected`:``}`,children:[e.icon&&(0,a.jsx)(`img`,{src:e.icon,alt:e.chain}),(0,a.jsx)(`span`,{children:e.chain})]},e.chain))})]}),(0,a.jsxs)(`div`,{className:`_cppay-section`,children:[(0,a.jsx)(`label`,{className:`_cppay-label`,children:`支付代币`}),(0,a.jsx)(`div`,{className:`_cppay-grid`,children:M.map(e=>(0,a.jsxs)(`button`,{onClick:()=>D(e.symbol),className:`_cppay-select-btn ${E===e.symbol?`_cppay-selected`:``}`,children:[e.icon&&(0,a.jsx)(`img`,{src:e.icon,alt:e.symbol}),(0,a.jsx)(`span`,{children:e.symbol})]},e.symbol))})]}),(0,a.jsx)(`div`,{className:`_cppay-section`,children:(0,a.jsx)(`div`,{className:`_cppay-price-box`,children:(0,a.jsxs)(`div`,{className:`_cppay-price-row`,children:[(0,a.jsx)(`span`,{className:`_cppay-price-label`,children:`支付金额`}),(0,a.jsxs)(`div`,{className:`_cppay-price-amount`,children:[(0,a.jsxs)(`div`,{className:`_cppay-price-main`,children:[F,` `,E]}),(0,a.jsxs)(`div`,{className:`_cppay-price-sub`,children:[`≈ $`,d]})]})]})})}),(0,a.jsx)(`div`,{className:`_cppay-section`,children:(0,a.jsx)(`button`,{onClick:R,disabled:!w||!E||b,className:`_cppay-btn _cppay-btn-primary`,children:b?`处理中...`:`继续支付`})})]}):(0,a.jsxs)(`div`,{children:[(0,a.jsx)(`div`,{className:`_cppay-qr-container`,children:(0,a.jsx)(`div`,{className:`_cppay-qr-code`,style:{background:`white`,padding:`16px`,borderRadius:`16px`},children:O&&(0,a.jsx)(`img`,{src:O,alt:`Payment QR Code`,style:{width:`200px`,height:`200px`}})})}),(0,a.jsxs)(`div`,{className:`_cppay-section`,children:[(0,a.jsxs)(`div`,{className:`_cppay-info-box`,children:[(0,a.jsx)(`div`,{className:`_cppay-info-label`,children:l===`subscription`?`授权金额`:`支付金额`}),(0,a.jsx)(`div`,{className:`_cppay-info-value`,children:l===`subscription`?`${P(L.current.approveAmount,N(E))} ${E}`:`${P(L.current.paymentAmount,N(E))} ${E}`})]}),(0,a.jsxs)(`div`,{className:`_cppay-info-box`,children:[(0,a.jsx)(`div`,{className:`_cppay-info-label`,children:l===`subscription`?`授权合约地址`:`支付地址`}),(0,a.jsxs)(`div`,{className:`_cppay-address-row`,children:[(0,a.jsx)(`code`,{children:l===`subscription`?L.current.spenderAddress:L.current.receiveAddress}),(0,a.jsx)(`button`,{onClick:V,className:`_cppay-copy-btn`,title:`复制地址`,children:(0,a.jsx)(`svg`,{fill:`none`,stroke:`currentColor`,viewBox:`0 0 24 24`,children:(0,a.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`})})})]})]}),l===`subscription`&&(0,a.jsxs)(`div`,{className:`_cppay-info-box`,style:{background:`#fff3cd`,borderColor:`#ffc107`},children:[(0,a.jsx)(`div`,{className:`_cppay-info-label`,style:{color:`#856404`},children:`📌 订阅说明`}),(0,a.jsx)(`div`,{className:`_cppay-info-value`,style:{fontSize:`12px`,color:`#856404`},children:`订阅支付需要授权代币给合约地址,系统将按周期自动扣款。授权后无需每次手动支付。`})]})]}),(0,a.jsx)(`div`,{className:`_cppay-section`,children:(0,a.jsx)(`button`,{onClick:z,disabled:b,className:`_cppay-btn _cppay-btn-primary`,children:b?`检查中...`:`我已完成支付`})}),(0,a.jsx)(`div`,{className:`_cppay-section`,children:(0,a.jsx)(`button`,{onClick:()=>y(`select`),disabled:b,className:`_cppay-btn _cppay-btn-secondary`,children:`更改支付方式`})})]})})]})}):null},c=i.default.memo(s),l=(0,i.createContext)(null);const u=({apikey:e,children:t})=>{let[n,r]=(0,i.useState)(!1),[o,s]=(0,i.useState)(null),u=(0,i.useCallback)(e=>{s(e),r(!0)},[]),d=(0,i.useCallback)(()=>{r(!1)},[]),f=(0,i.useCallback)(e=>{o?.onSuccess?.(e),r(!1)},[o]),p=(0,i.useCallback)(e=>{o?.onError?.(e)},[o]);return(0,a.jsxs)(l.Provider,{value:{showPayment:u},children:[t,o&&(0,a.jsx)(c,{open:n,onClose:d,apikey:e,plain:o.plain,orderId:o.orderId,amount:o.amount,intervalDays:o.intervalDays,onSuccess:f,onError:p})]})},d=()=>{let e=(0,i.useContext)(l);if(!e)throw Error(`useCppayPayment must be used within CppayProvider`);return e};e.n(e.r),exports.CppayProvider=u,exports.PaymentDialog=c,exports.useCppayPayment=d;
|
|
1
|
+
const e=require(`./walletconnect-B_n5YF-h.cjs`),t=require(`./cppay-DnxPUyM2.cjs`);let n=require(`rxjs`),r=require(`rxjs/operators`),i=require(`viem`),a=require(`viem/chains`),o=require(`@walletconnect/ethereum-provider`);o=e.o(o);let s=require(`react`);s=e.o(s);let c=require(`react/jsx-runtime`);var l=e.o(e.r(),1),u=({open:u,onClose:d,apikey:f,plain:p,orderId:m,amount:h,intervalDays:g,onExpired:_,onSuccess:v,onFailed:y,onError:b})=>{let x=(0,s.useMemo)(()=>new t.t(f),[f]),[S,C]=(0,s.useState)(`select`),[w,T]=(0,s.useState)(!1),[E,D]=(0,s.useState)([]),[O,k]=(0,s.useState)(``),[A,j]=(0,s.useState)(``),[M,N]=(0,s.useState)(``),[P,F]=(0,s.useState)(``),[I,L]=(0,s.useState)(!1),[R,z]=(0,s.useState)(null),B=(0,s.useRef)(null),V=(0,s.useRef)(null),H=(0,s.useMemo)(()=>E.find(e=>e.chain===O),[E,O]),U=(0,s.useMemo)(()=>H?.tokens||[],[H]),W=(0,s.useMemo)(()=>U.find(e=>e.symbol===A),[U,A]),G=e=>[`USDT`,`USDC`,`BUSD`,`DAI`,`TUSD`,`USDD`,`FDUSD`].includes(e.toUpperCase())?2:6,K=e=>({ETH:a.mainnet,BSC:a.bsc,Polygon:a.polygon,Arbitrum:a.arbitrum,Optimism:a.optimism,Base:a.base})[e]||a.mainnet,q=(e,t)=>{let n=parseFloat(e);return isNaN(n)?`0`:n.toFixed(t).replace(/\.?0+$/,``)},J=(0,s.useMemo)(()=>{if(!A||!W)return`0`;let e=parseFloat(W.price);if(isNaN(e)||e===0)return`0`;let t=G(A);return q((parseFloat(h)/e).toFixed(t),t)},[h,A,W]),ee=async()=>{try{T(!0);let e=await x.getSupportedChains();D(e),e.length>0&&k(e[0].chain)}catch(e){b?.(e)}finally{T(!1)}},Y=async e=>{try{if(L(!0),e===`metamask`){if(typeof window<`u`&&window.ethereum?.isMetaMask){let e=await window.ethereum.request({method:`eth_requestAccounts`});if(e&&e.length>0){F(e[0]),z(`metamask`);return}}throw Error(`请安装 MetaMask 扩展`)}if(e===`walletconnect`){let e=await o.default.init({projectId:`8d2e1854d3f1782e45aa15fbd8938894`,chains:[1],showQrModal:!0,optionalChains:[56,137,42161,10,8453],methods:[`eth_sendTransaction`,`eth_signTransaction`,`eth_sign`,`personal_sign`,`eth_signTypedData`],events:[`chainChanged`,`accountsChanged`],metadata:{name:`Cppay`,description:`Cppay Payment Gateway`,url:typeof window<`u`?window.location.origin:`https://cppay.com`,icons:[`https://cppay.com/icon.png`]},rpcMap:{1:`https://ethereum.publicnode.com`,56:`https://bsc-dataseed.binance.org`,137:`https://polygon-rpc.com`,42161:`https://arb1.arbitrum.io/rpc`,10:`https://mainnet.optimism.io`,8453:`https://mainnet.base.org`}});await e.enable();let t=await e.request({method:`eth_accounts`});t&&t.length>0&&(F(t[0]),z(`walletconnect`),B.current=e)}}catch(e){console.error(`钱包连接失败:`,e),b?.(e)}finally{L(!1)}},X=async e=>{let t;if(t=R===`walletconnect`?B.current:window.ethereum,t)try{await t.request({method:`wallet_switchEthereumChain`,params:[{chainId:`0x${e.toString(16)}`}]})}catch(e){throw e.code===4902?Error(`请在钱包中添加该网络`):e}},te=async()=>{if(!(!P||!Z.current||!W))try{T(!0);let e=Z.current,t=K(O);await X(H.chainId);let n=(0,i.createWalletClient)({account:P,chain:t,transport:(0,i.custom)(R===`walletconnect`?B.current:window.ethereum)});if(W.address){let t=await n.writeContract({address:W.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,i.parseUnits)(e.paymentAmount,W.decimals)],chain:null});console.log(`转账交易哈希:`,t)}else{let t=await n.sendTransaction({to:e.receiveAddress,value:(0,i.parseUnits)(e.paymentAmount,W.decimals),chain:null});console.log(`转账交易哈希:`,t)}Q(e.paymentId)}catch(e){console.error(`钱包支付失败:`,e),b?.(e)}finally{T(!1)}},ne=async()=>{if(!(!P||!Z.current||!W))try{T(!0);let e=Z.current,t=K(O);await X(H.chainId);let n=(0,i.createWalletClient)({account:P,chain:t,transport:(0,i.custom)(R===`walletconnect`?B.current:window.ethereum)});if(!W.address)throw Error(`订阅支付不支持原生代币`);let r=await n.writeContract({address:W.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,i.parseUnits)(e.approveAmount,W.decimals)],chain:null});console.log(`授权交易哈希:`,r),Q(e.subscriptionId)}catch(e){console.error(`钱包授权失败:`,e),b?.(e)}finally{T(!1)}},re=async()=>{if(!P){b?.(Error(`请先连接钱包`));return}p===`one-time`?await te():p===`subscription`&&await ne()},Z=(0,s.useRef)(null),ie=async()=>{if(!(!O||!A))try{T(!0);let e=``;p===`one-time`?(Z.current=await x.createOnetimePayment({paymentChain:O,paymentToken:A,orderId:m,amount:J}),e=`${O.toLowerCase()}:${Z.current.receiveAddress}?amount=${Z.current.paymentAmount}`):p===`subscription`&&(Z.current=await x.createSubscriptionPayment({paymentChain:O,paymentToken:A,orderId:m,amountOfUsd:J,intervalDays:g||30}),e=`${O.toLowerCase()}:${Z.current.spenderAddress}?amount=${Z.current.approveAmount}`),C(`payment`),N(await l.toDataURL(e,{width:200,margin:2,errorCorrectionLevel:`H`}))}catch(e){b?.(e)}finally{T(!1)}},ae=async()=>{if(Z.current)try{T(!0),p===`one-time`?Q(Z.current.paymentId):p===`subscription`&&Q(Z.current.subscriptionId)}catch(e){console.error(`支付状态检查错误:`,e),b?.(e),T(!1)}},Q=e=>{let t=()=>(0,n.defer)(()=>p===`subscription`?x.checkSubscriptionPaymentStatus({subscriptionId:e}):x.checkOnetimePaymentStatus({paymentId:e})).pipe((0,r.timeout)(15e3),(0,r.retry)({count:3,delay:2e3}));V.current?.unsubscribe(),V.current=t().pipe((0,r.expand)(e=>e.status===`pending`?(0,n.timer)(2e3).pipe((0,r.switchMap)(()=>t())):n.EMPTY),(0,r.tap)(e=>{e.status===`expired`&&(T(!1),_?.(e)),e.status===`paid`&&(T(!1),C(`success`),v?.(e)),e.status===`failed`&&(T(!1),y?.(e)),e.status===`approved`&&(T(!1),C(`success`),v?.(e))})).subscribe({error:e=>{console.error(`支付状态检查错误:`,e),T(!1),b?.(e)}})},oe=async()=>{if(!Z.current)return;let e=p===`subscription`?Z.current.spenderAddress:Z.current.receiveAddress;e&&await navigator.clipboard.writeText(e)},$=()=>{w||(d(),setTimeout(()=>{C(`select`),Z.current=null},300))};return(0,s.useEffect)(()=>{u&&E.length===0&&ee()},[u]),(0,s.useEffect)(()=>{U.length>0&&j(U[0].symbol)},[U]),(0,s.useEffect)(()=>()=>{V.current?.unsubscribe()},[]),u?(0,c.jsx)(`div`,{className:`_cppay-overlay`,onClick:e=>e.target===e.currentTarget&&!w&&$(),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:S===`select`?`选择支付方式`:`完成支付`}),(0,c.jsx)(`button`,{onClick:$,disabled:w,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)(`div`,{className:`_cppay-content`,children:S===`success`?(0,c.jsxs)(`div`,{style:{textAlign:`center`,padding:`2rem 0`},children:[(0,c.jsx)(`div`,{style:{fontSize:`64px`,marginBottom:`1rem`},children:`✅`}),(0,c.jsx)(`h3`,{style:{fontSize:`1.5rem`,fontWeight:600,color:`#10b981`,margin:`0 0 0.5rem 0`},children:p===`subscription`?`授权成功!`:`支付成功!`}),(0,c.jsx)(`p`,{style:{color:`#6b7280`,margin:0},children:p===`subscription`?`订阅已激活`:`交易已完成`})]}):S===`select`?(0,c.jsxs)(`div`,{children:[(0,c.jsxs)(`div`,{className:`_cppay-section`,children:[(0,c.jsx)(`label`,{className:`_cppay-label`,children:`支付网络`}),(0,c.jsx)(`div`,{className:`_cppay-grid`,children:E.map(e=>(0,c.jsxs)(`button`,{onClick:()=>k(e.chain),className:`_cppay-select-btn ${O===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:`支付代币`}),(0,c.jsx)(`div`,{className:`_cppay-grid`,children:U.map(e=>(0,c.jsxs)(`button`,{onClick:()=>j(e.symbol),className:`_cppay-select-btn ${A===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))})]}),(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:`支付金额`}),(0,c.jsxs)(`div`,{className:`_cppay-price-amount`,children:[(0,c.jsxs)(`div`,{className:`_cppay-price-main`,children:[J,` `,A]}),(0,c.jsxs)(`div`,{className:`_cppay-price-sub`,children:[`≈ $`,h]})]})]})})}),(0,c.jsx)(`div`,{className:`_cppay-section`,children:(0,c.jsx)(`button`,{onClick:ie,disabled:!O||!A||w,className:`_cppay-btn _cppay-btn-primary`,children:w?`处理中...`:`继续支付`})})]}):(0,c.jsxs)(`div`,{children:[(0,c.jsx)(`div`,{className:`_cppay-qr-container`,children:(0,c.jsx)(`div`,{className:`_cppay-qr-code`,children:M&&(0,c.jsx)(`img`,{src:M,alt:`Payment QR Code`,style:{width:`160px`,height:`160px`,display:`block`}})})}),(0,c.jsxs)(`div`,{className:`_cppay-section`,children:[(0,c.jsxs)(`div`,{className:`_cppay-info-box`,children:[(0,c.jsx)(`div`,{className:`_cppay-info-label`,children:p===`subscription`?`授权金额`:`支付金额`}),(0,c.jsx)(`div`,{className:`_cppay-info-value`,children:p===`subscription`?`${q(Z.current.approveAmount,G(A))} ${A}`:`${q(Z.current.paymentAmount,G(A))} ${A}`})]}),(0,c.jsxs)(`div`,{className:`_cppay-info-box`,children:[(0,c.jsx)(`div`,{className:`_cppay-info-label`,children:p===`subscription`?`授权合约地址`:`支付地址`}),(0,c.jsxs)(`div`,{className:`_cppay-address-row`,children:[(0,c.jsx)(`code`,{children:p===`subscription`?Z.current.spenderAddress:Z.current.receiveAddress}),(0,c.jsx)(`button`,{onClick:oe,className:`_cppay-copy-btn`,title:`复制地址`,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:`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`})})})]})]}),p===`subscription`&&(0,c.jsxs)(`div`,{className:`_cppay-info-box`,style:{background:`#fff3cd`,borderColor:`#ffc107`},children:[(0,c.jsx)(`div`,{className:`_cppay-info-label`,style:{color:`#856404`},children:`📌 订阅说明`}),(0,c.jsx)(`div`,{className:`_cppay-info-value`,style:{fontSize:`12px`,color:`#856404`},children:`订阅支付需要授权代币给合约地址,系统将按周期自动扣款。授权后无需每次手动支付。`})]})]}),(0,c.jsx)(`div`,{className:`_cppay-section`,children:P?(0,c.jsxs)(c.Fragment,{children:[(0,c.jsx)(`button`,{onClick:re,disabled:w,className:`_cppay-btn _cppay-btn-primary`,children:w?p===`subscription`?`授权中...`:`支付中...`:p===`subscription`?`💳 钱包授权`:`💳 钱包支付`}),(0,c.jsxs)(`div`,{style:{textAlign:`center`,marginTop:`8px`,fontSize:`12px`,color:`#666`},children:[`已连接: `,P.slice(0,6),`...`,P.slice(-4)]})]}):(0,c.jsxs)(`div`,{style:{display:`flex`,flexDirection:`row`,gap:`0.5rem`,justifyContent:`center`},children:[(0,c.jsxs)(`button`,{onClick:()=>Y(`metamask`),disabled:I,className:`_cppay-btn _cppay-btn-secondary`,style:{display:`flex`,alignItems:`center`,justifyContent:`center`,gap:`0.5rem`,padding:`0.5rem 1rem`,fontSize:`14px`,flex:`1`},children:[(0,c.jsx)(`img`,{src:e.n,alt:`MetaMask`,style:{width:`20px`,height:`20px`}}),(0,c.jsx)(`span`,{children:`MetaMask`})]}),(0,c.jsxs)(`button`,{onClick:()=>Y(`walletconnect`),disabled:I,className:`_cppay-btn _cppay-btn-secondary`,style:{display:`flex`,alignItems:`center`,justifyContent:`center`,gap:`0.5rem`,padding:`0.5rem 1rem`,fontSize:`14px`,flex:`1`},children:[(0,c.jsx)(`img`,{src:e.t,alt:`WalletConnect`,style:{width:`20px`,height:`20px`}}),(0,c.jsx)(`span`,{children:`WalletConnect`})]})]})}),(0,c.jsx)(`div`,{className:`_cppay-section`,children:(0,c.jsx)(`button`,{onClick:ae,disabled:w,className:`_cppay-btn _cppay-btn-primary`,children:w?`检查中...`:`我已完成支付`})}),(0,c.jsx)(`div`,{className:`_cppay-section`,children:(0,c.jsx)(`button`,{onClick:()=>C(`select`),disabled:w,className:`_cppay-btn _cppay-btn-text`,children:`更改支付方式`})})]})})]})}):null},d=s.default.memo(u),f=(0,s.createContext)(null);const p=({apikey:e,children:t})=>{let[n,r]=(0,s.useState)(!1),[i,a]=(0,s.useState)(null),o=(0,s.useCallback)(e=>{a(e),r(!0)},[]),l=(0,s.useCallback)(()=>{r(!1)},[]),u=(0,s.useCallback)(e=>{i?.onSuccess?.(e),r(!1)},[i]),p=(0,s.useCallback)(e=>{i?.onError?.(e)},[i]);return(0,c.jsxs)(f.Provider,{value:{showPayment:o},children:[t,i&&(0,c.jsx)(d,{open:n,onClose:l,apikey:e,plain:i.plain,orderId:i.orderId,amount:i.amount,intervalDays:i.intervalDays,onSuccess:u,onError:p})]})},m=()=>{let e=(0,s.useContext)(f);if(!e)throw Error(`useCppayPayment must be used within CppayProvider`);return e};e.i(e.a),exports.CppayProvider=p,exports.PaymentDialog=d,exports.useCppayPayment=m;
|
package/dist/react.d.ts
CHANGED
|
@@ -75,3 +75,10 @@ declare type SubscriptionPaymentStatus = "pending" | "approved" | "expired" | "f
|
|
|
75
75
|
export declare const useCppayPayment: () => CppayContextValue;
|
|
76
76
|
|
|
77
77
|
export { }
|
|
78
|
+
|
|
79
|
+
|
|
80
|
+
declare module "@vue/runtime-core" {
|
|
81
|
+
interface ComponentCustomProperties {
|
|
82
|
+
$showPayment: typeof showPayment;
|
|
83
|
+
}
|
|
84
|
+
}
|