@upayments-kw/react
v1.0.0-beta.4
Published
Official React components and SDK integration for UPayments
Readme
@upayments-kw/react — React Integration for UPayments Web SDK
Official React components and SDK integration for UPayments. Seamlessly accept Apple Pay and Apple Pay KNET in React 18+ and Next.js applications without requiring manual Web Component or SDK setup.
Key Highlights
- All-in-One Package: You only need to install
@upayments-kw/react. All classes, types, and utilities from@upayments-kw/web-sdk(UPayments,PayOptions,PaymentMethodId,PaymentResult, etc.) are re-exported directly. - Automated Bearer Auth: Simply pass
token: 'YOUR_TOKEN'during initialization. - SSR-Safe: Built-in SSR guards prevent Node.js server pre-rendering crashes.
- Framework Support: Verified for Next.js 14 App Router, Vite, Create React App, and Remix.
Requirements & Prerequisites
| Requirement | Minimum Version / Specification | Details |
| ------------------------ | ------------------------------- | ----------------------------------------------------------------------------- |
| Node.js | >= 18.0.0 | Required for building React & Next.js applications. |
| React / React DOM | >= 18.0.0 | Supports React 18 and React 19. |
| Browsers | Safari 13+ (macOS / iOS) | Required for Apple Pay payments. |
| HTTPS Protocol | Valid SSL / TLS Certificate | Apple Pay requires HTTPS (exceptlocalhost during development). |
| Merchant Credentials | API Bearer Token | Issued via theUPayments Merchant Dashboard. |
Installation
npm install @upayments-kw/react
# or
pnpm add @upayments-kw/react
# or
yarn add @upayments-kw/react[!NOTE] There is no need to install
@upayments-kw/web-sdkseparately.@upayments-kw/reactincludes everything.
UI Component Previews
1. Group Payment Container (<PaymentMethods />)
Automatically renders all available payment options for the customer's device. Additional payment methods (Credit/Debit Card, KNET direct) will appear automatically once enabled on your merchant account.
┌───────────────────────────────────────────────────────────┐
│ Payment Methods │
│ │
│ ┌─────────────────────────────────────────────────────┐ │
│ │ Pay │ │ <-- Apple Pay
│ └─────────────────────────────────────────────────────┘ │
│ ┌─────────────────────────────────────────────────────┐ │
│ │ Pay | KNET │ │ <-- Apple Pay KNET
│ └─────────────────────────────────────────────────────┘ │
│ │
│ [ Credit / Debit Card (Coming Soon) ] │
└───────────────────────────────────────────────────────────┘2. Standalone Apple Pay Button (<ApplePayButton />)
Direct branded button for express checkout flows.
┌───────────────────────────────────────────────┐
│ Pay │ (Default / Black)
└───────────────────────────────────────────────┘
┌───────────────────────────────────────────────┐
│ Pay │ (White with line)
└───────────────────────────────────────────────┘Usage Guide
Option 1: Group Payments Usage (<PaymentMethods />)
Use the <PaymentMethods /> container to display all payment methods enabled for your merchant account:
import React, { useEffect, useState } from 'react';
import {
UPayments,
PaymentMethods,
type PaymentMethodId,
type BoundPayHandler,
type PayOptions,
} from '@upayments-kw/react';
export const Checkout = () => {
const [sdk, setSdk] = useState<UPayments | null>(null);
const [availableMethods, setAvailableMethods] = useState<PaymentMethodId[]>([]);
useEffect(() => {
async function init() {
// Initialize SDK — token is automatically handled as Bearer
const instance = UPayments.create({
environment: 'sandbox', // 'sandbox' or 'production'
token: 'YOUR_MERCHANT_API_TOKEN',
});
// Handshake and detect available payment methods
await instance.initialize();
setSdk(instance);
setAvailableMethods(instance.getAvailablePaymentMethods());
}
init();
}, []);
const handlePay = async (method: PaymentMethodId, pay: BoundPayHandler) => {
if (!sdk) return;
try {
const payload = {
amount: 25.0,
products: [{ name: 'Classic Sneakers', price: 25.0, quantity: 1 }],
order: {
id: `ORD_${Date.now()}`,
currency: 'KWD',
amount: 25.0,
},
customer: {
name: 'Ahmed Al-Sabah',
mobile: '+96560000000',
email: '[email protected]',
},
returnUrl: `${window.location.origin}/orders/success`,
cancelUrl: `${window.location.origin}/orders/cancel`,
};
// Executes payment directly inside user gesture
const result = await pay({ payload });
console.log('Payment Success:', result);
} catch (error) {
console.error('Payment Failed:', error);
}
};
return (
<div style={{ maxWidth: 460, margin: '2rem auto' }}>
<h2>Complete Checkout</h2>
{sdk ? (
<PaymentMethods
sdk={sdk}
availableMethods={availableMethods}
onMethodSelected={handlePay}
/>
) : (
<p>Loading payment methods...</p>
)}
</div>
);
};Option 2: Standalone Payment Method Usage (<ApplePayButton />)
Use <ApplePayButton /> directly for one-touch express checkout:
import React, { useEffect, useState } from 'react';
import { UPayments, ApplePayButton, type BoundPayHandler } from '@upayments-kw/react';
export const ExpressApplePay = () => {
const [sdk, setSdk] = useState<UPayments | null>(null);
useEffect(() => {
async function init() {
const instance = UPayments.create({
environment: 'sandbox',
token: 'YOUR_MERCHANT_API_TOKEN',
});
await instance.initialize();
setSdk(instance);
}
init();
}, []);
const handlePay = async (pay: BoundPayHandler) => {
if (!sdk) return;
const payload = {
amount: 15.0,
products: [{ name: 'Espresso Roast', price: 15.0, quantity: 1 }],
order: {
id: `ORD_${Date.now()}`,
currency: 'KWD',
amount: 15.0,
},
customer: {
name: 'Sara Ahmad',
mobile: '+96590000000',
email: '[email protected]',
},
returnUrl: `${window.location.origin}/orders/success`,
cancelUrl: `${window.location.origin}/orders/cancel`,
};
// Executes Apple Pay sheet within active user gesture
await pay({ payload });
};
return (
<div>
<h3>One-Click Checkout</h3>
<ApplePayButton
sdk={sdk}
paymentMethod="apple_pay"
type="buy"
buttonStyle="black"
height={52}
borderRadius={12}
onClick={handlePay}
/>
</div>
);
};Apple Pay Button Customization Guide
<ApplePayButton /> supports complete styling and customization per Apple's Human Interface Guidelines (HIG):
1. All 16 Button Types (type)
'plain' (default) | 'buy' | 'set-up' | 'donate' | 'check-out' | 'book' | 'subscribe' | 'reload' | 'add-money' | 'top-up' | 'order' | 'rent' | 'support' | 'contribute' | 'tip' | 'continue'
2. Visual Styles / Colors (buttonStyle or variant)
'black'(default): Black button with white text and logo (for light backgrounds).'white': White button with black text and logo (for dark backgrounds).'white-outline': White button with black border and text (also accepts'white-with-line').
3. Props Reference
| Prop | Type | Default | Description |
|---|---|---|---|
| sdk | UPayments | null | SDK instance for bound payment execution |
| type | ApplePayButtonType | 'plain' | Button action verb |
| buttonStyle | 'black' \| 'white' \| 'white-outline' | 'black' | Visual appearance |
| variant | 'black' \| 'white' \| 'white-outline' | 'black' | Alias for buttonStyle |
| locale | string | 'en' | BCP 47 language tag (e.g. 'en', 'ar') |
| width | string \| number | '100%' | Button width (min 140px) |
| height | string \| number | '48px' | Button height (min 30px, standard 44px–64px) |
| borderRadius | string \| number | '8px' | Corner radius (e.g. 8, 12, or 9999 for pill) |
| padding | string \| number | '0px 0px' | Inner padding |
| boxSizing | 'border-box' \| 'content-box' | 'border-box' | Box sizing model |
| loading | boolean | false | Displays spinner overlay and disables clicks |
| disabled | boolean | false | Disables button and dims opacity |
| ariaLabel | string | (auto) | Accessible screen-reader label |
| onClick | (pay) => void | undefined | Click callback providing pay function |
Next.js (App Router) & SSR Compatibility
While @upayments-kw/react provides safe fallbacks for server environments, payment flows (window.ApplePaySession) and interactive payment buttons require a client-side browser runtime.
In Next.js App Router, mark the checkout component with 'use client' and dynamically import it with { ssr: false }:
// app/page.tsx
'use client';
import dynamic from 'next/dynamic';
const CheckoutClient = dynamic(
() => import('../components/CheckoutClient').then((mod) => mod.CheckoutClient),
{
ssr: false,
loading: () => <p>Loading payment checkout...</p>,
},
);
export default function Page() {
return (
<main>
<CheckoutClient />
</main>
);
}In next.config.mjs:
/** @type {import('next').NextConfig} */
const nextConfig = {
transpilePackages: ['@upayments-kw/react'],
};
export default nextConfig;Events & Callbacks Reference
Listen to lifecycle events on the SDK instance:
| Event Name | Trigger Condition | Payload Details |
| ----------------------------- | -------------------------------------------------------------------------- | -------------------------------------------------------------------- |
| upay:ready | Fired when the SDK has initialized and verified available payment methods. | { availablePaymentMethods: PaymentMethodId[] } |
| upay:payment-methods-loaded | Fired when payment capabilities are received from the backend. | { availablePaymentMethods: PaymentMethodId[], merchantId: string } |
| upay:payment-started | Fired immediately whensdk.pay() is called and flow begins. | { paymentMethod: PaymentMethodId } |
| upay:payment-method-opened | Fired when the interactive payment sheet (e.g. Apple Pay) is presented. | { paymentMethod: PaymentMethodId } |
| upay:payment-processing | Fired when the token is submitted to the gateway for processing. | { paymentMethod: PaymentMethodId } |
| upay:payment-success | Fired when the transaction is successfully captured. | { paymentMethod: PaymentMethodId, result: PaymentResult } |
| upay:payment-failed | Fired when a payment attempt fails or is declined. | { paymentMethod: PaymentMethodId, error: SDKError } |
| upay:payment-cancelled | Fired when the customer dismisses or cancels the payment sheet. | { paymentMethod: PaymentMethodId } |
| upay:error | Fired when an initialization or unexpected runtime error occurs. | SDKError |
Support & Documentation
- Developer Documentation: https://developers.upayments.com
- Merchant Dashboard: https://my.upayments.com
- Technical Support: [email protected]
- Official Website: https://upayments.com
- Examples Repository: https://github.com/upaymentskwt/web-sdk-examples
