@boostengine/payments 1.1.0 → 1.1.1

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.
Files changed (2) hide show
  1. package/README.md +132 -117
  2. package/package.json +10 -1
package/README.md CHANGED
@@ -1,30 +1,84 @@
1
- # @boostengine/payments
1
+ # @boostengine/payments 💳
2
2
 
3
- > **Unified Multi-Gateway Payment Orchestration Layer** for Indian & Global eCommerce. Seamlessly integrate **Razorpay, Cashfree, PhonePe, Paytm, Stripe, and Cash On Delivery (COD)** through a single unified API with smart routing, automatic fallbacks, Next.js App Router webhook helpers, and React checkout hooks.
3
+ [![npm version](https://img.shields.io/npm/v/@boostengine/payments.svg?style=flat-square&color=blue)](https://www.npmjs.com/package/@boostengine/payments)
4
+ [![npm downloads](https://img.shields.io/npm/dm/@boostengine/payments.svg?style=flat-square&color=green)](https://www.npmjs.com/package/@boostengine/payments)
5
+ [![license](https://img.shields.io/npm/l/@boostengine/payments.svg?style=flat-square)](https://github.com/boostengine/boostengine/blob/main/LICENSE)
6
+ [![TypeScript](https://img.shields.io/badge/TypeScript-Ready-3178c6.svg?style=flat-square)](https://www.typescriptlang.org/)
7
+ [![Gateways](https://img.shields.io/badge/Gateways-Razorpay%20%7C%20Cashfree%20%7C%20PhonePe%20%7C%20Paytm%20%7C%20Stripe%20%7C%20COD-purple.svg?style=flat-square)](https://npmjs.com/package/@boostengine/payments)
8
+
9
+ > **Unified multi-gateway payment orchestration for Indian and global eCommerce. Connect Razorpay, Cashfree, PhonePe, Paytm, Stripe, and Cash on Delivery (COD) with a single, unified API. Features automatic gateway failover, smart currency routing, Next.js webhook normalizers, and React checkout hooks.**
10
+
11
+ Zero dependency bloat — uses native Node.js `crypto` and `fetch`. No need to install 6 separate heavy vendor SDKs.
12
+
13
+ ---
14
+
15
+ ## 📸 Architecture & Payment Flow
16
+
17
+ ```text
18
+ Customer Clicks "Pay Now" (₹1,499)
19
+
20
+
21
+ ┌─────────────────────────────────────────────────────────────┐
22
+ │ Smart Payment Orchestrator │
23
+ ├─────────────────────────────────────────────────────────────┤
24
+ │ Currency Routing: │
25
+ │ - If INR ──► Route to Cashfree / Razorpay / PhonePe │
26
+ │ - If USD ──► Route to Stripe │
27
+ │ - If COD ──► Verify min/max limits & add handling fee │
28
+ │ │
29
+ │ High-Availability Failover: │
30
+ │ [Cashfree Server 500] ──► Auto-retry with [Razorpay] ──► OK│
31
+ └──────────────────────────────┬──────────────────────────────┘
32
+
33
+
34
+ ┌─────────────────────────────────────────────────────────────┐
35
+ │ Client Checkout Hook (`useBoostPayment`) │
36
+ ├─────────────────────────────────────────────────────────────┤
37
+ │ Opens Razorpay Popup / Cashfree Dropin / PhonePe App / UPI │
38
+ └──────────────────────────────┬──────────────────────────────┘
39
+
40
+
41
+ ┌─────────────────────────────────────────────────────────────┐
42
+ │ Next.js Webhook Handler (2 Lines) │
43
+ ├─────────────────────────────────────────────────────────────┤
44
+ │ Validates HMAC-SHA256 signature and returns normalized event:│
45
+ │ 'PAYMENT_SUCCESS' | 'PAYMENT_FAILED' | 'REFUND_PROCESSED' │
46
+ └─────────────────────────────────────────────────────────────┘
47
+ ```
4
48
 
5
49
  ---
6
50
 
7
- ## Key Highlights
51
+ ## 🌟 Gateway Comparison
8
52
 
9
- - 🔌 **Universal Checkout API**: Pass standard amounts (e.g. `1499.00`). Subunits (paise/cents) are normalized internally!
10
- - 🛡️ **High-Availability Fallback**: If your primary gateway is down or bank servers timeout, automatically failover to your secondary gateway!
11
- - 💱 **Smart Currency Routing**: Automatically route USD/EUR to Stripe and INR to Cashfree/Razorpay/PhonePe.
12
- - **Next.js App Router Native**: 2-line webhook verification with `payments.verifyNextJsWebhook(req, { gateway: 'razorpay' })`.
13
- - 🏷️ **Normalized Webhook Events**: Standardized events like `'PAYMENT_SUCCESS'`, `'PAYMENT_FAILED'`, `'REFUND_PROCESSED'`.
14
- - ⚛️ **Client Checkout Hook**: `useBoostPayment()` hook to open Razorpay modals or Cashfree dropin with automatic SDK loading!
15
- - 🪶 **Zero Dependency Bloat**: Uses native Node.js `fetch` and `crypto`. No 10 heavy third-party vendor SDKs.
53
+ | Gateway | Supported Currencies | Methods Supported | Best For |
54
+ | :--- | :--- | :--- | :--- |
55
+ | **Razorpay** | INR, USD, EUR + 90 more | UPI, Cards, NetBanking, Wallets, EMI | Reliable Indian D2C checkout |
56
+ | **Cashfree** | INR | Instant UPI QR, Intent, NetBanking, Cards | Low transaction fees & high UPI success |
57
+ | **PhonePe** | INR | PhonePe App, UPI Intent, QR Code | Fast mobile conversions in India |
58
+ | **Stripe** | Global (135+ currencies) | Credit/Debit Cards, Apple Pay, Google Pay | International cross-border sales |
59
+ | **Paytm** | INR | Paytm Wallet, UPI, Postpaid, NetBanking | Indian mobile users |
60
+ | **Cash on Delivery** | Any | Pay in cash upon delivery | Tier 2/3 Indian cities |
16
61
 
17
62
  ---
18
63
 
19
64
  ## 📦 Installation
20
65
 
21
66
  ```bash
67
+ # npm
22
68
  npm install @boostengine/payments
69
+
70
+ # pnpm
71
+ pnpm add @boostengine/payments
72
+
73
+ # yarn
74
+ yarn add @boostengine/payments
23
75
  ```
24
76
 
25
77
  ---
26
78
 
27
- ## 🚀 1. Server-Side Setup (`lib/payments.ts`)
79
+ ## 🚀 Step-by-Step Integration Guide
80
+
81
+ ### Step 1: Initialize Payment Manager (`lib/payments.ts`)
28
82
 
29
83
  ```typescript
30
84
  import { createPaymentManager } from '@boostengine/payments';
@@ -56,11 +110,11 @@ export const payments = createPaymentManager({
56
110
  cod: {
57
111
  minOrderValue: 200,
58
112
  maxOrderValue: 10000,
59
- extraFee: 49, // Rs. 49 COD handling charge
113
+ extraFee: 49, // 49 COD handling charge
60
114
  },
61
115
  },
62
116
 
63
- // Smart Routing & Resilience
117
+ // Smart Routing & High Availability
64
118
  smartRouting: {
65
119
  currencyMap: {
66
120
  USD: 'stripe',
@@ -74,17 +128,19 @@ export const payments = createPaymentManager({
74
128
 
75
129
  ---
76
130
 
77
- ## 💳 2. Unified Order Creation (Server Route)
131
+ ### Step 2: Create Order API Route (`app/api/checkout/route.ts`)
78
132
 
79
- Always pass standard human currency units (e.g. `1499.00`). Package handles paise/cents conversions automatically:
133
+ Pass standard human amounts (e.g. `1499.00`). Paise and cents conversion is handled automatically!
80
134
 
81
135
  ```typescript
82
- // Next.js Route Handler / Express
136
+ import { payments } from '@/lib/payments';
137
+
83
138
  export async function POST(req: Request) {
84
- const { amount, customer, chosenGateway } = await req.json();
139
+ const { amount, customer, gateway } = await req.json();
85
140
 
86
- const order = await payments.createOrder({
87
- amount: 1499.00, // Always in standard currency (e.g. Rs. 1499.00)
141
+ // Create order with automatic fallback if primary gateway is down
142
+ const order = await payments.createOrderWithFallback({
143
+ amount: amount, // e.g. 1499
88
144
  currency: 'INR',
89
145
  receipt: `order_${Date.now()}`,
90
146
  customer: {
@@ -92,7 +148,7 @@ export async function POST(req: Request) {
92
148
  email: customer.email,
93
149
  phone: customer.phone,
94
150
  },
95
- gateway: chosenGateway, // or let smartRouting decide
151
+ fallbackChain: gateway ? [gateway, 'razorpay'] : ['cashfree', 'razorpay'],
96
152
  });
97
153
 
98
154
  return Response.json(order);
@@ -101,50 +157,9 @@ export async function POST(req: Request) {
101
157
 
102
158
  ---
103
159
 
104
- ## 🔥 3. Next.js App Router Webhook (`app/api/webhooks/[gateway]/route.ts`)
105
-
106
- No manual stream parsing or signature math required:
107
-
108
- ```typescript
109
- import { payments } from '@/lib/payments';
110
-
111
- export async function POST(
112
- req: Request,
113
- { params }: { params: { gateway: string } }
114
- ) {
115
- const result = await payments.verifyNextJsWebhook(req, {
116
- gateway: params.gateway as any,
117
- });
118
-
119
- if (!result.isValid) {
120
- return new Response('Invalid Signature', { status: 400 });
121
- }
122
-
123
- // Use standardized normalized events across all gateways!
124
- switch (result.normalizedEvent) {
125
- case 'PAYMENT_SUCCESS':
126
- console.log(`✅ Order ${result.orderId} paid successfully! Amount: ${result.amount}`);
127
- // Update database: Order status -> PAID
128
- break;
129
-
130
- case 'PAYMENT_FAILED':
131
- console.log(`❌ Order ${result.orderId} failed.`);
132
- break;
133
-
134
- case 'REFUND_PROCESSED':
135
- console.log(`🔄 Refund processed for payment ${result.paymentId}`);
136
- break;
137
- }
138
-
139
- return new Response('OK');
140
- }
141
- ```
142
-
143
- ---
144
-
145
- ## ⚛️ 4. Frontend Checkout Hook (`useBoostPayment`)
160
+ ### Step 3: Frontend Checkout Button (`components/CheckoutButton.tsx`)
146
161
 
147
- Automatically detects gateway, dynamically loads required vendor script, and triggers modals or redirects:
162
+ The `useBoostPayment` hook automatically injects the right vendor scripts on demand and displays payment modals:
148
163
 
149
164
  ```tsx
150
165
  'use client';
@@ -152,44 +167,40 @@ Automatically detects gateway, dynamically loads required vendor script, and tri
152
167
  import { useBoostPayment } from '@boostengine/payments/react';
153
168
  import { useRouter } from 'next/navigation';
154
169
 
155
- export default function CheckoutButton({ cartTotal, customer }) {
170
+ export default function CheckoutButton({ cartTotal, customer }: any) {
156
171
  const router = useRouter();
157
172
  const { openPaymentModal, isProcessing } = useBoostPayment();
158
173
 
159
- const handleCheckout = async (gateway: 'razorpay' | 'cashfree' | 'phonepe' | 'cod') => {
160
- // 1. Call your server API to create order
161
- const res = await fetch('/api/orders/create', {
174
+ const handlePay = async (gateway: 'razorpay' | 'cashfree' | 'phonepe' | 'cod') => {
175
+ // 1. Create order on server
176
+ const res = await fetch('/api/checkout', {
162
177
  method: 'POST',
163
- body: JSON.stringify({ amount: cartTotal, customer, chosenGateway: gateway }),
178
+ body: JSON.stringify({ amount: cartTotal, customer, gateway }),
164
179
  });
165
180
  const order = await res.json();
166
181
 
167
- // 2. Open checkout modal / redirect automatically
182
+ // 2. Open popup modal or redirect
168
183
  openPaymentModal({
169
184
  order,
170
- name: 'Boost Engine Store',
171
- description: 'Order Checkout',
185
+ name: 'BoostStore',
186
+ description: 'Order Payment',
172
187
  themeColor: '#4f46e5',
173
- onSuccess: async (response) => {
174
- // Automatically called when Razorpay modal succeeds or COD is chosen
175
- router.push(`/order-confirmed?id=${response.orderId}`);
188
+ onSuccess: async (result) => {
189
+ router.push(`/order-success?id=${result.orderId}`);
176
190
  },
177
191
  onFailure: (err) => {
178
- alert(err.message);
192
+ alert(`Payment failed: ${err.message}`);
179
193
  },
180
194
  });
181
195
  };
182
196
 
183
197
  return (
184
- <div className="flex gap-2">
185
- <button disabled={isProcessing} onClick={() => handleCheckout('razorpay')}>
186
- Pay with Razorpay
187
- </button>
188
- <button disabled={isProcessing} onClick={() => handleCheckout('cashfree')}>
189
- Pay with Cashfree
198
+ <div style={{ display: 'flex', gap: '10px' }}>
199
+ <button disabled={isProcessing} onClick={() => handlePay('cashfree')}>
200
+ Pay Online (UPI / Card)
190
201
  </button>
191
- <button disabled={isProcessing} onClick={() => handleCheckout('cod')}>
192
- Cash On Delivery
202
+ <button disabled={isProcessing} onClick={() => handlePay('cod')}>
203
+ Cash on Delivery
193
204
  </button>
194
205
  </div>
195
206
  );
@@ -198,57 +209,61 @@ export default function CheckoutButton({ cartTotal, customer }) {
198
209
 
199
210
  ---
200
211
 
201
- ## 🛡️ 5. High-Availability Fallback Checkout
212
+ ### Step 4: Next.js Universal Webhook Handler (`app/api/webhooks/[gateway]/route.ts`)
202
213
 
203
- If your primary payment gateway experiences bank server outages or 500 errors, automatic fallback routes the order through the next available gateway:
214
+ Verify webhook signatures in 2 lines with standard normalized events:
204
215
 
205
216
  ```typescript
206
- const order = await payments.createOrderWithFallback({
207
- amount: 1499.00,
208
- currency: 'INR',
209
- receipt: `order_${Date.now()}`,
210
- customer: {
211
- name: 'Aman Sharma',
212
- email: 'aman@example.com',
213
- phone: '9876543210',
214
- },
215
- fallbackChain: ['razorpay', 'cashfree', 'phonepe'],
216
- });
217
- ```
217
+ import { payments } from '@/lib/payments';
218
218
 
219
- ---
219
+ export async function POST(
220
+ req: Request,
221
+ { params }: { params: { gateway: string } }
222
+ ) {
223
+ const result = await payments.verifyNextJsWebhook(req, {
224
+ gateway: params.gateway as any,
225
+ });
226
+
227
+ if (!result.isValid) {
228
+ return new Response('Invalid Signature', { status: 400 });
229
+ }
220
230
 
221
- ## 🧰 Explicit TypeScript Type Exports
231
+ // Handle standardized events across all payment gateways!
232
+ switch (result.normalizedEvent) {
233
+ case 'PAYMENT_SUCCESS':
234
+ console.log(`✅ Order ${result.orderId} paid! Amount: ₹${result.amount}`);
235
+ // TODO: Update Order status to 'PAID' in database
236
+ break;
222
237
 
223
- ```typescript
224
- import type {
225
- PaymentOrderResult,
226
- VerificationResult,
227
- RefundResult,
228
- WebhookResult,
229
- SupportedGateway,
230
- NormalizedWebhookEvent,
231
- CreateOrderOptions,
232
- BoostPaymentOpenOptions,
233
- } from '@boostengine/payments';
238
+ case 'PAYMENT_FAILED':
239
+ console.log(`❌ Order ${result.orderId} failed.`);
240
+ break;
241
+
242
+ case 'REFUND_PROCESSED':
243
+ console.log(`🔄 Refund completed for ${result.paymentId}`);
244
+ break;
245
+ }
246
+
247
+ return new Response('OK');
248
+ }
234
249
  ```
235
250
 
236
251
  ---
237
252
 
238
- ## 🛠️ CLI Tool
253
+ ## 🛠️ CLI Utilities
254
+
255
+ Test and configure payment credentials quickly:
239
256
 
240
257
  ```bash
241
- # List all 6 supported gateways
258
+ # List supported gateways and their status
242
259
  npx @boostengine/payments list
243
260
 
244
- # Generate .env.payments.example template
261
+ # Generate .env.payments template
245
262
  npx @boostengine/payments init-env
246
-
247
- # Compute quick SHA-256 hash
248
- npx @boostengine/payments hash "my_test_payload"
249
263
  ```
250
264
 
251
265
  ---
252
266
 
253
267
  ## 📄 License
254
- MIT © Boost Engine Team
268
+
269
+ MIT © [Boost Engine](https://github.com/boostengine)
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@boostengine/payments",
3
- "version": "1.1.0",
3
+ "version": "1.1.1",
4
4
  "description": "Unified Multi-Gateway Payment Orchestration for Indian & Global eCommerce (Razorpay, Cashfree, PhonePe, Paytm, Stripe, COD) with smart routing, automatic fallbacks, signature verification, and React checkout hooks.",
5
5
  "author": "Boost Engine <boostengine001@gmail.com>",
6
6
  "license": "MIT",
@@ -22,6 +22,15 @@
22
22
  "nextjs-webhook",
23
23
  "react-payments"
24
24
  ],
25
+ "homepage": "https://github.com/boostengine/boostengine/tree/main/packages/boost-payments#readme",
26
+ "repository": {
27
+ "type": "git",
28
+ "url": "https://github.com/boostengine/boostengine.git",
29
+ "directory": "packages/boost-payments"
30
+ },
31
+ "bugs": {
32
+ "url": "https://github.com/boostengine/boostengine/issues"
33
+ },
25
34
  "bin": {
26
35
  "boost-payments": "./bin/cli.cjs"
27
36
  },