recur-tw 0.4.2 → 0.4.4
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/README.md +31 -27
- package/dist/index.cjs +10 -7
- package/dist/index.d.cts +8 -3
- package/dist/index.d.ts +8 -3
- package/dist/index.js +10 -7
- package/dist/recur.umd.js +9 -6
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -85,7 +85,6 @@ function SubscriptionPage() {
|
|
|
85
85
|
planId: plan.id,
|
|
86
86
|
customerEmail: 'user@example.com',
|
|
87
87
|
customerName: 'John Doe',
|
|
88
|
-
customerPhone: '+886912345678',
|
|
89
88
|
})}
|
|
90
89
|
disabled={isCheckingOut}
|
|
91
90
|
>
|
|
@@ -196,7 +195,6 @@ await checkout({
|
|
|
196
195
|
planId: 'plan_xxx',
|
|
197
196
|
customerEmail: 'user@example.com',
|
|
198
197
|
customerName: 'John Doe',
|
|
199
|
-
customerPhone: '+886912345678',
|
|
200
198
|
// mode: 'embedded' is default when containerElementId is configured
|
|
201
199
|
});
|
|
202
200
|
```
|
|
@@ -398,12 +396,11 @@ interface CheckoutOptions {
|
|
|
398
396
|
// Required: Plan ID to subscribe to
|
|
399
397
|
planId: string;
|
|
400
398
|
|
|
401
|
-
// Customer information
|
|
402
|
-
customerEmail
|
|
399
|
+
// Customer information (email is required)
|
|
400
|
+
customerEmail: string; // Required: primary customer identifier
|
|
403
401
|
customerName?: string;
|
|
404
|
-
customerPhone?: string;
|
|
405
402
|
|
|
406
|
-
// External customer ID - link to your existing users
|
|
403
|
+
// External customer ID - link to your existing users (optional, immutable once set)
|
|
407
404
|
externalCustomerId?: string;
|
|
408
405
|
|
|
409
406
|
// Checkout mode
|
|
@@ -423,7 +420,12 @@ interface CheckoutOptions {
|
|
|
423
420
|
|
|
424
421
|
### Customer Identification
|
|
425
422
|
|
|
426
|
-
The SDK
|
|
423
|
+
The SDK uses email as the primary customer identifier, with optional external ID support.
|
|
424
|
+
|
|
425
|
+
#### Required Fields
|
|
426
|
+
|
|
427
|
+
- `customerEmail` - **Required**. Customer's email address (primary identifier)
|
|
428
|
+
- `externalCustomerId` - Optional. Your system's user ID
|
|
427
429
|
|
|
428
430
|
#### Using External Customer ID
|
|
429
431
|
|
|
@@ -433,15 +435,15 @@ The `externalCustomerId` parameter allows you to link Recur subscriptions to you
|
|
|
433
435
|
// React
|
|
434
436
|
await checkout({
|
|
435
437
|
planId: 'plan_xxx',
|
|
436
|
-
customerEmail: 'user@example.com',
|
|
438
|
+
customerEmail: 'user@example.com', // Required
|
|
437
439
|
customerName: 'John Doe',
|
|
438
|
-
externalCustomerId: 'user_12345',
|
|
440
|
+
externalCustomerId: 'user_12345', // Optional: Your system's user ID
|
|
439
441
|
});
|
|
440
442
|
|
|
441
443
|
// Vanilla JS
|
|
442
444
|
await recur.checkout({
|
|
443
445
|
planId: 'plan_xxx',
|
|
444
|
-
customerEmail: 'user@example.com',
|
|
446
|
+
customerEmail: 'user@example.com', // Required
|
|
445
447
|
externalCustomerId: 'cus_abc456',
|
|
446
448
|
});
|
|
447
449
|
|
|
@@ -450,28 +452,31 @@ await recur.redirectToCheckout({
|
|
|
450
452
|
productId: 'prod_xxx',
|
|
451
453
|
successUrl: '/success',
|
|
452
454
|
cancelUrl: '/cancel',
|
|
453
|
-
customerEmail: 'user@example.com',
|
|
455
|
+
customerEmail: 'user@example.com', // Required
|
|
454
456
|
externalCustomerId: 'user_12345',
|
|
455
457
|
});
|
|
456
458
|
```
|
|
457
459
|
|
|
458
|
-
####
|
|
459
|
-
|
|
460
|
-
For customer identification, **at least one** of the following must be provided:
|
|
461
|
-
- `customerEmail` - Customer's email address
|
|
462
|
-
- `externalCustomerId` - Your system's user ID
|
|
460
|
+
#### Customer Resolution Rules
|
|
463
461
|
|
|
464
|
-
|
|
462
|
+
When processing a checkout:
|
|
465
463
|
|
|
466
|
-
|
|
464
|
+
1. **externalCustomerId provided** - Looks up customer by external ID first
|
|
465
|
+
- If found, verifies email matches (throws error if mismatch)
|
|
466
|
+
- If not found, checks if email already exists
|
|
467
|
+
2. **Email lookup** - If external ID not found or not provided
|
|
468
|
+
- If email exists and external ID was provided → Error (cannot add external ID to existing customer)
|
|
469
|
+
- If email exists without external ID → Returns existing customer
|
|
470
|
+
3. **Create new** - Creates a new customer if neither found
|
|
467
471
|
|
|
468
|
-
|
|
472
|
+
#### Important: External ID is Immutable
|
|
469
473
|
|
|
470
|
-
|
|
471
|
-
|
|
472
|
-
|
|
474
|
+
The `externalCustomerId` can only be set when **creating** a customer. Once set:
|
|
475
|
+
- It cannot be changed
|
|
476
|
+
- It cannot be added to an existing customer
|
|
477
|
+
- It cannot be transferred to another customer
|
|
473
478
|
|
|
474
|
-
|
|
479
|
+
This design ensures data consistency and prevents accidental customer merges.
|
|
475
480
|
|
|
476
481
|
#### Retrieving Customer by External ID
|
|
477
482
|
|
|
@@ -481,13 +486,12 @@ Use the API to retrieve customers by their external ID:
|
|
|
481
486
|
GET /api/v1/subscribers/external/{externalCustomerId}
|
|
482
487
|
```
|
|
483
488
|
|
|
484
|
-
This allows you to query subscription status and details using your own user identifiers.
|
|
485
|
-
|
|
486
489
|
#### Best Practices
|
|
487
490
|
|
|
491
|
+
- **Always provide email**: Email is required for all checkout operations
|
|
492
|
+
- **Set external ID early**: Include `externalCustomerId` in the initial checkout request when creating customers
|
|
488
493
|
- **Use consistent IDs**: Use your database primary key or UUID as the external ID
|
|
489
|
-
- **
|
|
490
|
-
- **Provide both when possible**: Although only one is required, providing both email and external ID ensures maximum flexibility
|
|
494
|
+
- **Plan ahead**: Decide whether to use external IDs before your first customer signup
|
|
491
495
|
|
|
492
496
|
---
|
|
493
497
|
|
package/dist/index.cjs
CHANGED
|
@@ -1461,7 +1461,7 @@ var init_payment_form = __esm({
|
|
|
1461
1461
|
section.className = "customer-info-section";
|
|
1462
1462
|
const customerName = this.getAttribute("customer-name");
|
|
1463
1463
|
const customerEmail = this.getAttribute("customer-email");
|
|
1464
|
-
if (
|
|
1464
|
+
if (customerEmail) {
|
|
1465
1465
|
section.innerHTML = `
|
|
1466
1466
|
<style>
|
|
1467
1467
|
.recur-info-display {
|
|
@@ -1497,10 +1497,12 @@ var init_payment_form = __esm({
|
|
|
1497
1497
|
</style>
|
|
1498
1498
|
|
|
1499
1499
|
<div class="recur-info-display">
|
|
1500
|
-
|
|
1501
|
-
<
|
|
1502
|
-
|
|
1503
|
-
|
|
1500
|
+
${customerName ? `
|
|
1501
|
+
<div class="recur-info-row">
|
|
1502
|
+
<span class="recur-info-label">\u5BA2\u6236\u59D3\u540D\uFF1A</span>
|
|
1503
|
+
<span class="recur-info-value">${customerName}</span>
|
|
1504
|
+
</div>
|
|
1505
|
+
` : ""}
|
|
1504
1506
|
<div class="recur-info-row">
|
|
1505
1507
|
<span class="recur-info-label">\u96FB\u5B50\u90F5\u4EF6\uFF1A</span>
|
|
1506
1508
|
<span class="recur-info-value">${customerEmail}</span>
|
|
@@ -1563,6 +1565,7 @@ var init_payment_form = __esm({
|
|
|
1563
1565
|
id="${this.containerId}-name"
|
|
1564
1566
|
class="recur-form-input"
|
|
1565
1567
|
placeholder="\u738B\u5C0F\u660E"
|
|
1568
|
+
value="${customerName || ""}"
|
|
1566
1569
|
required
|
|
1567
1570
|
/>
|
|
1568
1571
|
</div>
|
|
@@ -2338,8 +2341,8 @@ function RecurProvider({ children, config: initialConfig = {} }) {
|
|
|
2338
2341
|
if (!options.customerName) {
|
|
2339
2342
|
throw new Error("customerName is required");
|
|
2340
2343
|
}
|
|
2341
|
-
if (!options.customerEmail
|
|
2342
|
-
throw new Error("
|
|
2344
|
+
if (!options.customerEmail) {
|
|
2345
|
+
throw new Error("customerEmail is required");
|
|
2343
2346
|
}
|
|
2344
2347
|
const baseUrl = config.baseUrl || "https://api.recur.tw";
|
|
2345
2348
|
console.log("[Recur SDK] Base URL:", baseUrl);
|
package/dist/index.d.cts
CHANGED
|
@@ -212,10 +212,15 @@ interface CheckoutOptions {
|
|
|
212
212
|
* Customer information
|
|
213
213
|
*/
|
|
214
214
|
customerName?: string;
|
|
215
|
-
customerEmail?: string;
|
|
216
215
|
/**
|
|
217
|
-
*
|
|
218
|
-
*
|
|
216
|
+
* Customer email address (required)
|
|
217
|
+
* Used as the primary identifier for the customer
|
|
218
|
+
*/
|
|
219
|
+
customerEmail: string;
|
|
220
|
+
/**
|
|
221
|
+
* External customer ID from your system (optional)
|
|
222
|
+
* Use this to link Recur subscriptions to your existing users.
|
|
223
|
+
* Once set during customer creation, this cannot be changed.
|
|
219
224
|
*
|
|
220
225
|
* @example 'user_123', 'cus_abc456'
|
|
221
226
|
*/
|
package/dist/index.d.ts
CHANGED
|
@@ -212,10 +212,15 @@ interface CheckoutOptions {
|
|
|
212
212
|
* Customer information
|
|
213
213
|
*/
|
|
214
214
|
customerName?: string;
|
|
215
|
-
customerEmail?: string;
|
|
216
215
|
/**
|
|
217
|
-
*
|
|
218
|
-
*
|
|
216
|
+
* Customer email address (required)
|
|
217
|
+
* Used as the primary identifier for the customer
|
|
218
|
+
*/
|
|
219
|
+
customerEmail: string;
|
|
220
|
+
/**
|
|
221
|
+
* External customer ID from your system (optional)
|
|
222
|
+
* Use this to link Recur subscriptions to your existing users.
|
|
223
|
+
* Once set during customer creation, this cannot be changed.
|
|
219
224
|
*
|
|
220
225
|
* @example 'user_123', 'cus_abc456'
|
|
221
226
|
*/
|
package/dist/index.js
CHANGED
|
@@ -1455,7 +1455,7 @@ var init_payment_form = __esm({
|
|
|
1455
1455
|
section.className = "customer-info-section";
|
|
1456
1456
|
const customerName = this.getAttribute("customer-name");
|
|
1457
1457
|
const customerEmail = this.getAttribute("customer-email");
|
|
1458
|
-
if (
|
|
1458
|
+
if (customerEmail) {
|
|
1459
1459
|
section.innerHTML = `
|
|
1460
1460
|
<style>
|
|
1461
1461
|
.recur-info-display {
|
|
@@ -1491,10 +1491,12 @@ var init_payment_form = __esm({
|
|
|
1491
1491
|
</style>
|
|
1492
1492
|
|
|
1493
1493
|
<div class="recur-info-display">
|
|
1494
|
-
|
|
1495
|
-
<
|
|
1496
|
-
|
|
1497
|
-
|
|
1494
|
+
${customerName ? `
|
|
1495
|
+
<div class="recur-info-row">
|
|
1496
|
+
<span class="recur-info-label">\u5BA2\u6236\u59D3\u540D\uFF1A</span>
|
|
1497
|
+
<span class="recur-info-value">${customerName}</span>
|
|
1498
|
+
</div>
|
|
1499
|
+
` : ""}
|
|
1498
1500
|
<div class="recur-info-row">
|
|
1499
1501
|
<span class="recur-info-label">\u96FB\u5B50\u90F5\u4EF6\uFF1A</span>
|
|
1500
1502
|
<span class="recur-info-value">${customerEmail}</span>
|
|
@@ -1557,6 +1559,7 @@ var init_payment_form = __esm({
|
|
|
1557
1559
|
id="${this.containerId}-name"
|
|
1558
1560
|
class="recur-form-input"
|
|
1559
1561
|
placeholder="\u738B\u5C0F\u660E"
|
|
1562
|
+
value="${customerName || ""}"
|
|
1560
1563
|
required
|
|
1561
1564
|
/>
|
|
1562
1565
|
</div>
|
|
@@ -2332,8 +2335,8 @@ function RecurProvider({ children, config: initialConfig = {} }) {
|
|
|
2332
2335
|
if (!options.customerName) {
|
|
2333
2336
|
throw new Error("customerName is required");
|
|
2334
2337
|
}
|
|
2335
|
-
if (!options.customerEmail
|
|
2336
|
-
throw new Error("
|
|
2338
|
+
if (!options.customerEmail) {
|
|
2339
|
+
throw new Error("customerEmail is required");
|
|
2337
2340
|
}
|
|
2338
2341
|
const baseUrl = config.baseUrl || "https://api.recur.tw";
|
|
2339
2342
|
console.log("[Recur SDK] Base URL:", baseUrl);
|
package/dist/recur.umd.js
CHANGED
|
@@ -974,7 +974,7 @@
|
|
|
974
974
|
<span class="order-summary-label">\u7E3D\u8A08</span>
|
|
975
975
|
<span class="order-summary-total">NT$ ${Number(i).toLocaleString()}</span>
|
|
976
976
|
</div>
|
|
977
|
-
`,t}createCustomerInfoSection(){let t=document.createElement("div");t.className="customer-info-section";let r=this.getAttribute("customer-name"),i=this.getAttribute("customer-email");return
|
|
977
|
+
`,t}createCustomerInfoSection(){let t=document.createElement("div");t.className="customer-info-section";let r=this.getAttribute("customer-name"),i=this.getAttribute("customer-email");return i?t.innerHTML=`
|
|
978
978
|
<style>
|
|
979
979
|
.recur-info-display {
|
|
980
980
|
background: #f7fafc;
|
|
@@ -1009,10 +1009,12 @@
|
|
|
1009
1009
|
</style>
|
|
1010
1010
|
|
|
1011
1011
|
<div class="recur-info-display">
|
|
1012
|
-
|
|
1013
|
-
<
|
|
1014
|
-
|
|
1015
|
-
|
|
1012
|
+
${r?`
|
|
1013
|
+
<div class="recur-info-row">
|
|
1014
|
+
<span class="recur-info-label">\u5BA2\u6236\u59D3\u540D\uFF1A</span>
|
|
1015
|
+
<span class="recur-info-value">${r}</span>
|
|
1016
|
+
</div>
|
|
1017
|
+
`:""}
|
|
1016
1018
|
<div class="recur-info-row">
|
|
1017
1019
|
<span class="recur-info-label">\u96FB\u5B50\u90F5\u4EF6\uFF1A</span>
|
|
1018
1020
|
<span class="recur-info-value">${i}</span>
|
|
@@ -1073,6 +1075,7 @@
|
|
|
1073
1075
|
id="${this.containerId}-name"
|
|
1074
1076
|
class="recur-form-input"
|
|
1075
1077
|
placeholder="\u738B\u5C0F\u660E"
|
|
1078
|
+
value="${r||""}"
|
|
1076
1079
|
required
|
|
1077
1080
|
/>
|
|
1078
1081
|
</div>
|
|
@@ -1393,7 +1396,7 @@
|
|
|
1393
1396
|
display: block;
|
|
1394
1397
|
user-select: none;
|
|
1395
1398
|
transition: height 0.35s ease, opacity 0.4s ease 0.1s;
|
|
1396
|
-
`.replace(/\s+/g," ").trim(),this.iframe.allow="payment *",this.iframe.setAttribute("title","Secure payment input frame"),this.iframe.setAttribute("role","presentation"),this.iframe.setAttribute("scrolling","no"),this.iframe.setAttribute("frameBorder","0"),this.container.innerHTML="",this.container.appendChild(this.iframe),new Promise((r,i)=>{let s=setTimeout(()=>{i(new Error("Elements initialization timeout"))},3e4),n=()=>{clearTimeout(s),this.off("ready",n),r()},o=l=>{clearTimeout(s),this.off("error",o),i(new Error(l.message||"Elements initialization failed"))};this.on("ready",n),this.on("error",o)})}on(e,t){this.eventHandlers.has(e)||this.eventHandlers.set(e,new Set),this.eventHandlers.get(e).add(t)}off(e,t){let r=this.eventHandlers.get(e);r&&r.delete(t)}emit(e,t){let r=this.eventHandlers.get(e);r&&r.forEach(i=>i(t))}handleMessage(e){if(!this.isValidOrigin(e.origin))return;let{type:t,data:r}=e.data||{};switch(t){case"RECUR_ELEMENTS_READY":this.sessionId=r.sessionId,this.timestamp=r.timestamp,this.creditToken=r.creditToken,this.emit("ready",r);break;case"RECUR_CARD_VALID":this.emit("change",{valid:r.valid});break;case"RECUR_CARD_TOKENIZED":this.cardToken=r.cardToken,this.cardTimestamp=r.timestamp,this.emit("tokenized",r);break;case"RECUR_PAYMENT_ERROR":this.emit("error",r);break;case"RECUR_RESIZE":this.iframe&&r?.height&&(this.iframe.style.height=`${r.height}px`);break}}isValidOrigin(e){try{let t=new URL(this.embedUrl).origin;return e===t}catch{return!1}}async tokenize(){if(!this.iframe||!this.iframe.contentWindow)throw new Error("Elements not mounted");let e=new URL(this.embedUrl).origin;return this.iframe.contentWindow.postMessage({type:"RECUR_TOKENIZE"},e),new Promise((t,r)=>{let i=setTimeout(()=>{r(new Error("Tokenization timeout"))},6e4),s=o=>{clearTimeout(i),this.off("tokenized",s),t(o)},n=o=>{clearTimeout(i),this.off("error",n),r(new Error(o.message||"Tokenization failed"))};this.on("tokenized",s),this.on("error",n)})}async confirmPayment(e){if(!this.sessionId||!this.cardToken)throw new Error("Card not tokenized. Call tokenize() first.");let t=await fetch(`${this.baseUrl}/api/v1/elements/confirm`,{method:"POST",headers:{"Content-Type":"application/json","X-Recur-Publishable-Key":this.publishableKey},body:JSON.stringify({sessionId:this.sessionId,sdkToken:this.cardToken,timestamp:this.cardTimestamp,creditToken:this.creditToken,productId:e.productId,email:e.email,name:e.name,metadata:e.metadata})}),r=await t.json();return t.ok?r:{status:"failed",message:r.error||r.message||"Payment failed",canRetry:r.canRetry??!0}}getDefaultBaseUrl(){if(typeof window>"u")return"https://app.recur.tw";let e=window.location.hostname;return e==="localhost"||e.includes(".test")||e.includes(".local")||e==="127.0.0.1"?`${window.location.protocol}//${e}:3000`:"https://app.recur.tw"}getDefaultEmbedUrl(){if(typeof window>"u")return"https://embed.recur.tw";let e=window.location.hostname;return e==="localhost"||e.includes(".test")||e.includes(".local")||e==="127.0.0.1"?`${window.location.protocol}//${e}:3002`:"https://embed.recur.tw"}destroy(){this.iframe&&this.iframe.parentNode&&this.iframe.parentNode.removeChild(this.iframe),this.iframe=null,this.container=null,this.sessionId=null,this.timestamp=null,this.creditToken=null,this.cardToken=null,this.cardTimestamp=null,this.eventHandlers.clear(),window.removeEventListener("message",this.handleMessage.bind(this))}};function $(c){return new y(c)}var fe="https://vendor.payuni.com.tw/sdk/uni-payment.js",be="https://sandbox-vendor.payuni.com.tw/sdk/uni-payment.js",te=!1,D=!1,x=null;async function re(c=!1){return te&&window.UniPayment?Promise.resolve():(D&&x||(D=!0,x=new Promise((e,t)=>{let r=document.createElement("script");r.src=c?be:fe,r.async=!0,r.onload=()=>{te=!0,D=!1,e()},r.onerror=()=>{D=!1,x=null,t(new Error("Failed to load PAYUNi SDK"))},document.head.appendChild(r)})),x)}var w=class{constructor(e){a(this,"core");a(this,"currentModal",null);a(this,"currentIframe",null);a(this,"currentModalOverlay",null);this.core=new _(e)}async fetchPlans(){return await this.core.fetchPlans()}async createEmbeddedCheckout(e){let t=this.core.getConfig();await new z(t,e).render()}async redirectToCheckout(e){let t=this.core.getConfig(),r=()=>{if(typeof window<"u"){let l=window.location.hostname;if(l==="localhost"||l.includes(".test")||l.includes(".local")||l==="127.0.0.1")return`${window.location.protocol}//${window.location.host}/api`}return"https://api.recur.tw"},i=t.baseUrl||r(),s={productId:e.productId,successUrl:e.successUrl,cancelUrl:e.cancelUrl};e.mode&&(s.mode=e.mode),e.customerEmail&&(s.customerEmail=e.customerEmail),e.externalCustomerId&&(s.externalCustomerId=e.externalCustomerId);let n=await fetch(`${i}/v1/checkout/sessions`,{method:"POST",headers:{"Content-Type":"application/json","X-Recur-Publishable-Key":t.publishableKey},body:JSON.stringify(s)});if(!n.ok){let l=await n.json().catch(()=>({}));throw new Error(l.error?.message||"Failed to create checkout session")}let o=await n.json();window.location.href=o.url}async createCheckoutSession(e){let t=this.core.getConfig(),r=()=>{if(typeof window<"u"){let o=window.location.hostname;if(o==="localhost"||o.includes(".test")||o.includes(".local")||o==="127.0.0.1")return`${window.location.protocol}//${window.location.host}/api`}return"https://api.recur.tw"},i=t.baseUrl||r(),s={productId:e.productId,successUrl:e.successUrl,cancelUrl:e.cancelUrl};e.mode&&(s.mode=e.mode),e.customerEmail&&(s.customerEmail=e.customerEmail),e.externalCustomerId&&(s.externalCustomerId=e.externalCustomerId);let n=await fetch(`${i}/v1/checkout/sessions`,{method:"POST",headers:{"Content-Type":"application/json","X-Recur-Publishable-Key":t.publishableKey},body:JSON.stringify(s)});if(!n.ok){let o=await n.json().catch(()=>({}));throw new Error(o.error?.message||"Failed to create checkout session")}return n.json()}async checkout(e){let t=this.core.getConfig(),r=null;try{if(console.log("[Recur SDK] Starting checkout flow...",{planId:e.planId,mode:e.mode}),!e.planId)throw new Error("planId is required");if(!t.publishableKey)throw new Error("publishableKey is required");if(!e.customerName)throw new Error("customerName is required");if(!e.customerEmail
|
|
1399
|
+
`.replace(/\s+/g," ").trim(),this.iframe.allow="payment *",this.iframe.setAttribute("title","Secure payment input frame"),this.iframe.setAttribute("role","presentation"),this.iframe.setAttribute("scrolling","no"),this.iframe.setAttribute("frameBorder","0"),this.container.innerHTML="",this.container.appendChild(this.iframe),new Promise((r,i)=>{let s=setTimeout(()=>{i(new Error("Elements initialization timeout"))},3e4),n=()=>{clearTimeout(s),this.off("ready",n),r()},o=l=>{clearTimeout(s),this.off("error",o),i(new Error(l.message||"Elements initialization failed"))};this.on("ready",n),this.on("error",o)})}on(e,t){this.eventHandlers.has(e)||this.eventHandlers.set(e,new Set),this.eventHandlers.get(e).add(t)}off(e,t){let r=this.eventHandlers.get(e);r&&r.delete(t)}emit(e,t){let r=this.eventHandlers.get(e);r&&r.forEach(i=>i(t))}handleMessage(e){if(!this.isValidOrigin(e.origin))return;let{type:t,data:r}=e.data||{};switch(t){case"RECUR_ELEMENTS_READY":this.sessionId=r.sessionId,this.timestamp=r.timestamp,this.creditToken=r.creditToken,this.emit("ready",r);break;case"RECUR_CARD_VALID":this.emit("change",{valid:r.valid});break;case"RECUR_CARD_TOKENIZED":this.cardToken=r.cardToken,this.cardTimestamp=r.timestamp,this.emit("tokenized",r);break;case"RECUR_PAYMENT_ERROR":this.emit("error",r);break;case"RECUR_RESIZE":this.iframe&&r?.height&&(this.iframe.style.height=`${r.height}px`);break}}isValidOrigin(e){try{let t=new URL(this.embedUrl).origin;return e===t}catch{return!1}}async tokenize(){if(!this.iframe||!this.iframe.contentWindow)throw new Error("Elements not mounted");let e=new URL(this.embedUrl).origin;return this.iframe.contentWindow.postMessage({type:"RECUR_TOKENIZE"},e),new Promise((t,r)=>{let i=setTimeout(()=>{r(new Error("Tokenization timeout"))},6e4),s=o=>{clearTimeout(i),this.off("tokenized",s),t(o)},n=o=>{clearTimeout(i),this.off("error",n),r(new Error(o.message||"Tokenization failed"))};this.on("tokenized",s),this.on("error",n)})}async confirmPayment(e){if(!this.sessionId||!this.cardToken)throw new Error("Card not tokenized. Call tokenize() first.");let t=await fetch(`${this.baseUrl}/api/v1/elements/confirm`,{method:"POST",headers:{"Content-Type":"application/json","X-Recur-Publishable-Key":this.publishableKey},body:JSON.stringify({sessionId:this.sessionId,sdkToken:this.cardToken,timestamp:this.cardTimestamp,creditToken:this.creditToken,productId:e.productId,email:e.email,name:e.name,metadata:e.metadata})}),r=await t.json();return t.ok?r:{status:"failed",message:r.error||r.message||"Payment failed",canRetry:r.canRetry??!0}}getDefaultBaseUrl(){if(typeof window>"u")return"https://app.recur.tw";let e=window.location.hostname;return e==="localhost"||e.includes(".test")||e.includes(".local")||e==="127.0.0.1"?`${window.location.protocol}//${e}:3000`:"https://app.recur.tw"}getDefaultEmbedUrl(){if(typeof window>"u")return"https://embed.recur.tw";let e=window.location.hostname;return e==="localhost"||e.includes(".test")||e.includes(".local")||e==="127.0.0.1"?`${window.location.protocol}//${e}:3002`:"https://embed.recur.tw"}destroy(){this.iframe&&this.iframe.parentNode&&this.iframe.parentNode.removeChild(this.iframe),this.iframe=null,this.container=null,this.sessionId=null,this.timestamp=null,this.creditToken=null,this.cardToken=null,this.cardTimestamp=null,this.eventHandlers.clear(),window.removeEventListener("message",this.handleMessage.bind(this))}};function $(c){return new y(c)}var fe="https://vendor.payuni.com.tw/sdk/uni-payment.js",be="https://sandbox-vendor.payuni.com.tw/sdk/uni-payment.js",te=!1,D=!1,x=null;async function re(c=!1){return te&&window.UniPayment?Promise.resolve():(D&&x||(D=!0,x=new Promise((e,t)=>{let r=document.createElement("script");r.src=c?be:fe,r.async=!0,r.onload=()=>{te=!0,D=!1,e()},r.onerror=()=>{D=!1,x=null,t(new Error("Failed to load PAYUNi SDK"))},document.head.appendChild(r)})),x)}var w=class{constructor(e){a(this,"core");a(this,"currentModal",null);a(this,"currentIframe",null);a(this,"currentModalOverlay",null);this.core=new _(e)}async fetchPlans(){return await this.core.fetchPlans()}async createEmbeddedCheckout(e){let t=this.core.getConfig();await new z(t,e).render()}async redirectToCheckout(e){let t=this.core.getConfig(),r=()=>{if(typeof window<"u"){let l=window.location.hostname;if(l==="localhost"||l.includes(".test")||l.includes(".local")||l==="127.0.0.1")return`${window.location.protocol}//${window.location.host}/api`}return"https://api.recur.tw"},i=t.baseUrl||r(),s={productId:e.productId,successUrl:e.successUrl,cancelUrl:e.cancelUrl};e.mode&&(s.mode=e.mode),e.customerEmail&&(s.customerEmail=e.customerEmail),e.externalCustomerId&&(s.externalCustomerId=e.externalCustomerId);let n=await fetch(`${i}/v1/checkout/sessions`,{method:"POST",headers:{"Content-Type":"application/json","X-Recur-Publishable-Key":t.publishableKey},body:JSON.stringify(s)});if(!n.ok){let l=await n.json().catch(()=>({}));throw new Error(l.error?.message||"Failed to create checkout session")}let o=await n.json();window.location.href=o.url}async createCheckoutSession(e){let t=this.core.getConfig(),r=()=>{if(typeof window<"u"){let o=window.location.hostname;if(o==="localhost"||o.includes(".test")||o.includes(".local")||o==="127.0.0.1")return`${window.location.protocol}//${window.location.host}/api`}return"https://api.recur.tw"},i=t.baseUrl||r(),s={productId:e.productId,successUrl:e.successUrl,cancelUrl:e.cancelUrl};e.mode&&(s.mode=e.mode),e.customerEmail&&(s.customerEmail=e.customerEmail),e.externalCustomerId&&(s.externalCustomerId=e.externalCustomerId);let n=await fetch(`${i}/v1/checkout/sessions`,{method:"POST",headers:{"Content-Type":"application/json","X-Recur-Publishable-Key":t.publishableKey},body:JSON.stringify(s)});if(!n.ok){let o=await n.json().catch(()=>({}));throw new Error(o.error?.message||"Failed to create checkout session")}return n.json()}async checkout(e){let t=this.core.getConfig(),r=null;try{if(console.log("[Recur SDK] Starting checkout flow...",{planId:e.planId,mode:e.mode}),!e.planId)throw new Error("planId is required");if(!t.publishableKey)throw new Error("publishableKey is required");if(!e.customerName)throw new Error("customerName is required");if(!e.customerEmail)throw new Error("customerEmail is required");let i=this.getBaseUrl();console.log("[Recur SDK] Base URL:",i);let s={"Content-Type":"application/json","X-Recur-Publishable-Key":t.publishableKey},n=e.mode||"modal",o=null;if(n==="modal"){let u=this.createModalWithSkeleton(e.onClose);r=u.overlay,o=u.container}else if(n==="iframe"){if(o=this.getEmbeddedContainer(e.container),!o)throw new Error("Container is required for iframe mode");o.innerHTML="";let u=document.createElement("recur-payment-form-skeleton");o.appendChild(u)}console.log("[Recur SDK] Step 1: Creating checkout session...");let l=await fetch(`${i}/v1/checkouts`,{method:"POST",headers:s,body:JSON.stringify({productId:e.planId,customerName:e.customerName,customerEmail:e.customerEmail,externalCustomerId:e.externalCustomerId})});if(!l.ok){let u=await l.json().catch(()=>({}));console.error("[Recur SDK] Failed to create checkout:",u);let A=u.details||u.error||"Failed to create checkout";throw new Error(A)}let d=await l.json();if(console.log("[Recur SDK] Checkout created successfully:",d),e.onSuccess?.(d),n==="redirect"){let u=`https://checkout.recur.tw/${d.checkout.id}`;console.log("[Recur SDK] Redirecting to hosted checkout:",u),window.location.href=u;return}if(console.log("[Recur SDK] Step 2: Extracting SDK token..."),!d.sdkToken)throw new Error("SDK token missing from checkout response");console.log("[Recur SDK] Step 3: Loading PAYUNi SDK...");let v=!0;if(await re(v),console.log("[Recur SDK] PAYUNi SDK loaded successfully"),!window.UniPayment)throw new Error("PAYUNi SDK failed to load");if(console.log("[Recur SDK] Step 4: Rendering payment form..."),!o)throw new Error("Payment container not available");o.innerHTML="";let m=document.createElement("recur-payment-form");if(m.setAttribute("container-id",o.id||"recur-payment-container"),e.customerName&&m.setAttribute("customer-name",e.customerName),e.customerEmail&&m.setAttribute("customer-email",e.customerEmail),d.plan?.name&&m.setAttribute("plan-name",d.plan.name),d.checkout?.amount&&m.setAttribute("amount",d.checkout.amount.toString()),d.plan?.billingPeriod&&m.setAttribute("billing-period",d.plan.billingPeriod),m.setAttribute("custom-styles",`
|
|
1397
1400
|
.form-input-focus {
|
|
1398
1401
|
border-color: var(--ring, hsl(215 16% 47%)) !important;
|
|
1399
1402
|
outline: 0 !important;
|