### Quick Start with PaystackButton Source: https://github.com/iamraphson/react-paystack/blob/master/_autodocs/README.md A basic example demonstrating how to integrate the PaystackButton component for initiating a payment. Ensure you replace 'pk_test_your_key' with your actual public key. ```typescript import { PaystackButton } from 'react-paystack'; console.log('Success:', ref)} onClose={() => console.log('Payment closed')} /> ``` -------------------------------- ### Start Development Server Source: https://github.com/iamraphson/react-paystack/blob/master/_autodocs/integration-guide.md Run this command to start your React application's development server and test the payment integration. ```bash npm start ``` -------------------------------- ### Quick Start Payment Button Source: https://github.com/iamraphson/react-paystack/blob/master/_autodocs/INDEX.md A basic example of how to integrate the PaystackButton component for initiating payments. Ensure you replace 'pk_test_your_key' with your actual public key and provide the customer's email and amount. ```typescript import { PaystackButton } from 'react-paystack'; console.log(ref)} onClose={() => console.log('closed')} /> ``` -------------------------------- ### Install React Paystack Source: https://github.com/iamraphson/react-paystack/blob/master/_autodocs/INDEX.md Install the library using npm. Ensure you have Node.js and npm installed. ```bash npm install react-paystack ``` -------------------------------- ### Minimal Example: usePaystackPayment Hook Source: https://github.com/iamraphson/react-paystack/blob/master/_autodocs/quick-reference.md A minimal example demonstrating how to configure and use the usePaystackPayment hook to initiate a payment via a button click. ```typescript const config = { publicKey: 'pk_test_key', email: 'user@example.com', amount: 50000, }; const initializePayment = usePaystackPayment(config); ``` -------------------------------- ### InitializePayment Usage Example Source: https://github.com/iamraphson/react-paystack/blob/master/_autodocs/types.md Demonstrates how to use the `initializePayment` function obtained from the `usePaystackPayment` hook. Shows basic calls with callbacks and an example of overriding configuration like amount and currency. ```typescript const initializePayment = usePaystackPayment({ publicKey: 'pk_test_key', email: 'user@example.com', amount: 50000, }); // Basic call initializePayment({ onSuccess: (response) => console.log('Success:', response), onClose: () => console.log('Dialog closed'), }); // With config override initializePayment({ config: { amount: 100000, currency: 'USD', }, onSuccess: (response) => console.log('Success:', response), }); ``` -------------------------------- ### Install react-paystack with npm Source: https://github.com/iamraphson/react-paystack/blob/master/README.md Use npm to install the react-paystack library. This is the standard package manager for Node.js. ```sh npm install react-paystack --save ``` -------------------------------- ### Minimal Example: PaystackConsumer Component Source: https://github.com/iamraphson/react-paystack/blob/master/_autodocs/quick-reference.md A minimal example of the PaystackConsumer component, demonstrating how to use its children render prop to trigger payment initialization. ```typescript {({initializePayment}) => ( )} ``` -------------------------------- ### Basic PaystackProvider Setup Source: https://github.com/iamraphson/react-paystack/blob/master/_autodocs/api-reference/PaystackProvider.md Set up the PaystackProvider with essential configuration like publicKey, email, amount, and reference. This is the most straightforward way to integrate Paystack. ```typescript import React from 'react'; import { PaystackProvider } from 'react-paystack'; const config = { publicKey: 'pk_test_your_public_key_here', email: 'user@example.com', amount: 50000, reference: new Date().getTime().toString(), }; const handleSuccess = (response) => { console.log('Payment successful:', response); }; const handleClose = () => { console.log('Payment dialog closed'); }; const App = () => { return ( ); }; export default App; ``` -------------------------------- ### Install react-paystack with yarn Source: https://github.com/iamraphson/react-paystack/blob/master/README.md Use yarn to install the react-paystack library. Yarn is an alternative package manager for JavaScript. ```sh yarn add react-paystack ``` -------------------------------- ### Initialize Payment with usePaystackPayment Hook Source: https://github.com/iamraphson/react-paystack/blob/master/_autodocs/quick-reference.md Use the usePaystackPayment hook to get an initializePayment function. Call this function to start the payment process, optionally providing callbacks for success and close events, and partial configuration. ```typescript const initializePayment = usePaystackPayment(config: HookConfig) // Call the returned function to start payment initializePayment({ onSuccess?: (response) => void, onClose?: () => void, config?: Partial }) ``` -------------------------------- ### Basic Render-Props Pattern Source: https://github.com/iamraphson/react-paystack/blob/master/_autodocs/api-reference/PaystackConsumer.md A simple example demonstrating how to use the PaystackConsumer component with basic payment configuration and event handlers. ```APIDOC ## Basic Render-Props Pattern ```typescript import React from 'react'; import { PaystackConsumer } from 'react-paystack'; const PaymentPage = () => { const config = { reference: new Date().getTime().toString(), email: 'user@example.com', amount: 50000, publicKey: 'pk_test_your_public_key_here', }; const handleSuccess = (response) => { console.log('Payment successful:', response); }; const handleClose = () => { console.log('Payment dialog closed'); }; return ( {({ initializePayment }) => ( )} ); }; export default PaymentPage; ``` ``` -------------------------------- ### Minimal Example: PaystackButton Component Source: https://github.com/iamraphson/react-paystack/blob/master/_autodocs/quick-reference.md A minimal example of the PaystackButton component, showing the essential props required to render a functional payment button. ```typescript ``` -------------------------------- ### Example PaystackProps Configuration Source: https://github.com/iamraphson/react-paystack/blob/master/_autodocs/types.md Illustrates how to configure the PaystackProps for a payment transaction. Ensure the amount is in the smallest currency unit. ```typescript const config: PaystackProps = { publicKey: 'pk_test_your_key', email: 'customer@example.com', amount: 100000, firstname: 'John', lastname: 'Doe', phone: '+2348012345678', reference: new Date().getTime().toString(), currency: 'NGN', channels: ['card', 'bank_transfer'], metadata: { custom_fields: [ { display_name: 'Order ID', variable_name: 'order_id', value: 'ORD-123', }, ], }, }; ``` -------------------------------- ### Install react-paystack with PNPM Source: https://github.com/iamraphson/react-paystack/blob/master/_autodocs/integration-guide.md Use this command to add react-paystack to your project dependencies using PNPM. ```bash pnpm add react-paystack ``` -------------------------------- ### Dynamic Payment Configuration with usePaystackPayment Source: https://github.com/iamraphson/react-paystack/blob/master/_autodocs/integration-guide.md This example demonstrates dynamic payment configuration where user inputs for email and amount are used. It utilizes the `usePaystackPayment` hook for interactive payments. ```typescript import { useState } from 'react'; import { usePaystackPayment } from 'react-paystack'; function DynamicCheckout() { const [email, setEmail] = useState(''); const [amount, setAmount] = useState(''); const initializePayment = usePaystackPayment({ publicKey: process.env.REACT_APP_PAYSTACK_PUBLIC_KEY, email, amount: parseInt(amount) * 100, reference: Date.now().toString(), }); const handlePayment = () => { if (!email || !amount) { alert('Please fill in all fields'); return; } initializePayment({ onSuccess: (response) => { console.log('Payment successful:', response); // Save to database, send confirmation email, etc. }, onClose: () => { alert('Payment cancelled'); }, }); }; return (
setEmail(e.target.value)} /> setAmount(e.target.value)} />
); } export default DynamicCheckout; ``` -------------------------------- ### Complex Custom UI Source: https://github.com/iamraphson/react-paystack/blob/master/_autodocs/api-reference/PaystackConsumer.md An example showcasing how to integrate the PaystackConsumer with a more complex custom user interface for payment. ```APIDOC ## Complex Custom UI ```typescript const AdvancedPaymentUI = () => { const config = { publicKey: 'pk_test_your_public_key_here', email: 'customer@example.com', amount: 100000, reference: Date.now().toString(), }; return ( { alert(`Payment successful! Reference: ${ref.reference}`); }} onClose={() => alert('Payment cancelled')} > {({ initializePayment }) => (

Order Summary

Total: ₦1,000.00

)}
); }; ``` ``` -------------------------------- ### React Paystack Project File Structure Source: https://github.com/iamraphson/react-paystack/blob/master/_autodocs/INDEX.md An example of the typical file organization for a project using React Paystack, outlining the purpose of each file. ```plaintext output/ ├── INDEX.md (this file) ├── integration-guide.md # Getting started & setup ├── quick-reference.md # Condensed API reference ├── module-overview.md # Architecture & structure ├── usage-patterns.md # 9+ real-world patterns ├── types.md # Type definitions ├── configuration.md # All config options ├── errors.md # Error handling guide └── api-reference/ ├── usePaystackPayment.md # Hook documentation ├── PaystackButton.md # Button component ├── PaystackConsumer.md # Consumer component ├── PaystackProvider.md # Provider component └── PaystackContext.md # Context documentation ``` -------------------------------- ### HookConfig Usage Example Source: https://github.com/iamraphson/react-paystack/blob/master/_autodocs/types.md Illustrates the creation of a `HookConfig` object for the `usePaystackPayment` hook. It highlights that `publicKey` is mandatory, while other properties like `email` and `amount` are optional. ```typescript const hookConfig: HookConfig = { publicKey: 'pk_test_required_key', // All other fields are optional email: 'user@example.com', amount: 50000, }; ``` -------------------------------- ### Amount Calculation Examples Source: https://github.com/iamraphson/react-paystack/blob/master/_autodocs/README.md Demonstrates how to calculate payment amounts in different currencies based on the smallest currency unit. This is crucial for correctly setting the 'amount' parameter in Paystack transactions. ```text NGN: 50000 kobo = ₦500 (divide by 100 to get naira) USD: 5000 cents = $50 (divide by 100 to get dollars) GHS: 50000 pesewa = GH₵500 (divide by 100 to get cedis) ``` -------------------------------- ### Example PaystackMetadata Usage Source: https://github.com/iamraphson/react-paystack/blob/master/_autodocs/types.md Illustrates how to construct a PaystackMetadata object with custom fields and additional arbitrary properties like order timestamp and user segment. ```typescript const metadata: PaystackMetadata = { custom_fields: [ { display_name: 'Order ID', variable_name: 'order_id', value: '12345', }, { display_name: 'Product Name', variable_name: 'product', value: 'Premium Subscription', }, ], order_timestamp: '2024-01-15T10:30:00Z', user_segment: 'premium_users', }; ``` -------------------------------- ### Example PaystackConnectSplit Usage Source: https://github.com/iamraphson/react-paystack/blob/master/_autodocs/types.md Demonstrates how to create an array of PaystackConnectSplit objects to define how a payment should be distributed between two connected accounts. ```typescript const connectSplit: PaystackConnectSplit[] = [ { account_id: 'acct_xyz123abc', share: 60, }, { account_id: 'acct_abc123xyz', share: 40, }, ]; ``` -------------------------------- ### Implement Paystack Payment using Hooks Source: https://github.com/iamraphson/react-paystack/blob/master/README.md This example shows how to use the `usePaystackPayment` hook to initialize and manage Paystack payments within a React component. Ensure the `config` object contains your public key and payment details. The `onSuccess` and `onClose` callbacks handle post-payment actions and dialog closure. ```javascript import React from 'react'; import logo from './logo.svg'; import { usePaystackPayment } from 'react-paystack'; import './App.css'; const config = { reference: (new Date()).getTime().toString(), email: "user@example.com", amount: 20000, //Amount is in the country's lowest currency. E.g Kobo, so 20000 kobo = N200 publicKey: 'pk_test_dsdfghuytfd2345678gvxxxxxxxxxx', }; // you can call this function anything const onSuccess = (reference) => { // Implementation for whatever you want to do with reference and after success call. console.log(reference); }; // you can call this function anything const onClose = () => { // implementation for whatever you want to do when the Paystack dialog closed. console.log('closed') } const PaystackHookExample = () => { const initializePayment = usePaystackPayment(config); return (
); }; function App() { return (
logo

Edit src/App.js and save to reload.

Learn React
); } export default App; ``` -------------------------------- ### Implement Paystack Payment using Button Component Source: https://github.com/iamraphson/react-paystack/blob/master/README.md This example demonstrates using the `PaystackButton` component for Paystack integration. It requires a `config` object with payment details and a public key, along with `onSuccess` and `onClose` handler functions. The `componentProps` object merges these configurations for the button. ```javascript import React from 'react'; import logo from './logo.svg'; import { PaystackButton } from 'react-paystack'; import './App.css'; const config = { reference: (new Date()).getTime().toString(), email: "user@example.com", amount: 20000, //Amount is in the country's lowest currency. E.g Kobo, so 20000 kobo = N200 publicKey: 'pk_test_dsdfghuytfd2345678gvxxxxxxxxxx', }; function App() { // you can call this function anything const handlePaystackSuccessAction = (reference) => { // Implementation for whatever you want to do with reference and after success call. console.log(reference); }; // you can call this function anything const handlePaystackCloseAction = () => { // implementation for whatever you want to do when the Paystack dialog closed. console.log('closed') } const componentProps = { ...config, text: 'Paystack Button Implementation', onSuccess: (reference) => handlePaystackSuccessAction(reference), onClose: handlePaystackCloseAction, }; return (
logo

Edit src/App.js and save to reload.

Learn React
); } export default App; ``` -------------------------------- ### Dynamic PaystackProvider Configuration Source: https://github.com/iamraphson/react-paystack/blob/master/_autodocs/api-reference/PaystackProvider.md Configure the PaystackProvider dynamically using props to set user-specific details, transaction amounts, and custom metadata. This example also shows an asynchronous success handler for payment confirmation. ```typescript const DynamicPaymentProvider = ({ userEmail, transactionAmount, orderId }) => { const config = { publicKey: 'pk_test_your_public_key_here', email: userEmail, amount: transactionAmount, reference: `order_${orderId}_${Date.now()}`, metadata: { custom_fields: [ { display_name: 'Order ID', variable_name: 'order_id', value: orderId, }, ], }, }; const handlePaymentSuccess = async (response) => { const result = await fetch('/api/confirm-payment', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ reference: response.reference, orderId, }), }); return result.json(); }; const handlePaymentClose = () => { // Handle user cancellation }; return ( ); }; ``` -------------------------------- ### Using PaystackConsumer with Ref Forwarding Source: https://github.com/iamraphson/react-paystack/blob/master/_autodocs/api-reference/PaystackConsumer.md Demonstrates how to use `React.forwardRef` with `PaystackConsumer` to get a reference to the underlying element. The `initializePayment` function is accessed via the render prop. ```typescript const paymentRef = useRef(); {({ initializePayment, ref }) => ( )} ``` -------------------------------- ### Basic Paystack Button Component Setup Source: https://github.com/iamraphson/react-paystack/blob/master/_autodocs/integration-guide.md Integrate the PaystackButton component into your React application. Ensure your Paystack public key is set as an environment variable. ```typescript import React from 'react'; import { PaystackButton } from 'react-paystack'; const MyApp = () => { const publicKey = process.env.REACT_APP_PAYSTACK_PUBLIC_KEY; const componentProps = { email: 'user@example.com', amount: 50000, publicKey: publicKey, text: 'Pay with Paystack', onSuccess: ({ reference }) => { alert('Payment successful. Reference: ' + reference); }, onClose: () => alert('Payment window closed.'), }; return ; }; export default MyApp; ``` -------------------------------- ### Generate Unique Transaction References Source: https://github.com/iamraphson/react-paystack/blob/master/_autodocs/errors.md This example demonstrates the correct way to generate unique transaction references to avoid conflicts. It contrasts a wrong approach using a fixed reference with a correct approach using a dynamic reference generator. ```typescript // ❌ Wrong: Using the same reference const reference = 'fixed_ref_123'; initializePayment1({ config: { reference } }); // First payment initializePayment2({ config: { reference } }); // May conflict! // ✅ Correct: Generate unique references const generateReference = (): string => { return `txn_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`; }; const config1 = { publicKey: 'pk_test_key', email: 'user@example.com', amount: 50000, reference: generateReference(), // Unique per transaction }; const config2 = { publicKey: 'pk_test_key', email: 'user@example.com', amount: 75000, reference: generateReference(), // Different reference }; ``` -------------------------------- ### Multi-Step Checkout with React-Paystack Source: https://github.com/iamraphson/react-paystack/blob/master/_autodocs/usage-patterns.md Implement a multi-step checkout process where payment is the final step. This example manages form state across multiple steps and initializes payment upon completion of user information. ```typescript import React, { useState } from 'react'; import { usePaystackPayment } from 'react-paystack'; const MultiStepCheckout = () => { const [step, setStep] = useState(1); const [formData, setFormData] = useState({ email: '', firstname: '', lastname: '', phone: '', amount: 50000, }); const config = { publicKey: 'pk_test_your_key', email: formData.email, firstname: formData.firstname, lastname: formData.lastname, phone: formData.phone, amount: formData.amount, reference: `checkout_${Date.now()}`, }; const initializePayment = usePaystackPayment(config); const handleInputChange = (e) => { const { name, value } = e.target; setFormData((prev) => ({ ...prev, [name]: value })); }; const handleStepNext = () => { if (step < 3) setStep(step + 1); }; const handlePayment = () => { initializePayment({ onSuccess: (response) => { console.log('Order placed:', response); setStep(4); // Success step }, onClose: () => { alert('Payment cancelled. Please try again.'); }, }); }; return (
{step === 1 && (

Shipping Information

)} {step === 2 && (

Contact Information

)} {step === 3 && (

Review & Pay

{formData.firstname} {formData.lastname}

{formData.email}

₦{(formData.amount / 100).toFixed(2)}

)} {step === 4 && (

Thank You!

Your order has been placed successfully.

)}
); }; export default MultiStepCheckout; ``` -------------------------------- ### Build Project Source: https://github.com/iamraphson/react-paystack/blob/master/_autodocs/module-overview.md Execute this command in the project root to build the library. ```bash npm run build ``` -------------------------------- ### Run Tests Source: https://github.com/iamraphson/react-paystack/blob/master/_autodocs/module-overview.md Execute this command in the project root to run the library's unit tests. ```bash npm test ``` -------------------------------- ### Basic Payment Integration with usePaystackPayment Source: https://github.com/iamraphson/react-paystack/blob/master/_autodocs/api-reference/usePaystackPayment.md Demonstrates the fundamental usage of the usePaystackPayment hook. Configure payment details like reference, email, amount, and public key. Define success and close handlers for the payment flow. ```typescript import React from 'react'; import { usePaystackPayment } from 'react-paystack'; const MyPaymentComponent = () => { const config = { reference: new Date().getTime().toString(), email: 'user@example.com', amount: 20000, // Amount in lowest currency unit (kobo for NGN) publicKey: 'pk_test_your_public_key_here', }; const initializePayment = usePaystackPayment(config); const handleSuccess = (response) => { console.log('Payment successful:', response); }; const handleClose = () => { console.log('Payment dialog closed'); }; return ( ); }; export default MyPaymentComponent; ``` -------------------------------- ### Initialize Payment with usePaystackPayment Hook Source: https://github.com/iamraphson/react-paystack/blob/master/_autodocs/integration-guide.md Use this hook for custom UI and full control over the payment process. It requires configuration with publicKey, email, amount, and reference. ```typescript import { usePaystackPayment } from 'react-paystack'; function PaymentForm() { const config = { publicKey: process.env.REACT_APP_PAYSTACK_PUBLIC_KEY, email: 'customer@example.com', amount: 100000, reference: new Date().getTime().toString(), }; const initializePayment = usePaystackPayment(config); return ( ); } export default PaymentForm; ``` -------------------------------- ### Hook-Based Data Flow Source: https://github.com/iamraphson/react-paystack/blob/master/_autodocs/module-overview.md Illustrates the sequence of calls and data transformations when using the usePaystackPayment hook to initialize a payment. ```text User Component ↓ usePaystackPayment(config) ↓ initializePayment({onSuccess, onClose, config}) ↓ Merge configs ↓ Transform to Paystack format ↓ callPaystackPop(paystackArgs) ↓ PaystackPop.newTransaction() ↓ Paystack Popup Modal Opens ↓ User completes/cancels payment ↓ onSuccess() or onClose() called ``` -------------------------------- ### Validating Paystack Amount Source: https://github.com/iamraphson/react-paystack/blob/master/_autodocs/errors.md Checks if the provided amount is a positive integer, which is a requirement for Paystack transactions. This example shows valid and invalid amount configurations. ```typescript const config = { publicKey: 'pk_test_key', email: 'user@example.com', amount: 50000, // ✅ Valid: positive integer }; // Invalid examples // amount: 0, // ❌ Zero not allowed // amount: -5000, // ❌ Negative not allowed // amount: '50000', // ❌ String, should be number // Validate amount const validateAmount = (amount: any): boolean => { return typeof amount === 'number' && amount > 0 && Number.isInteger(amount); }; ``` -------------------------------- ### Enable Logging for Payment Initialization Source: https://github.com/iamraphson/react-paystack/blob/master/_autodocs/errors.md This snippet demonstrates how to enable logging during payment initialization to help debug issues. It logs the configuration and wraps the `initializePayment` call to log success responses and dialog closure events. ```typescript const initializePayment = usePaystackPayment(config); const handlePaymentWithLogging = (onSuccess: any, onClose: any) => { console.log('Initializing payment with config:', config); initializePayment({ onSuccess: (response) => { console.log('Payment success response:', response); onSuccess(response); }, onClose: () => { console.log('Payment dialog closed'); onClose(); }, }); }; ``` -------------------------------- ### PaystackConsumer with Conditional Rendering Source: https://github.com/iamraphson/react-paystack/blob/master/_autodocs/api-reference/PaystackConsumer.md This example demonstrates how to conditionally render a payment button based on an 'isPending' state. The button is disabled and shows 'Processing...' when 'isPending' is true. ```typescript const ConditionalPaymentUI = ({ isPending, customerEmail }) => { const config = { publicKey: 'pk_test_your_public_key_here', email: customerEmail, amount: 75000, reference: Date.now().toString(), }; return ( {({ initializePayment }) => ( )} ); }; ``` -------------------------------- ### Generate Unique Transaction References Source: https://github.com/iamraphson/react-paystack/blob/master/_autodocs/configuration.md Always generate unique references for each transaction to prevent conflicts. This example shows a good practice using a timestamp and a random string. ```typescript // Good: Generate unique references per transaction const reference = `txn_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`; ``` ```typescript // Avoid: Reusing the same reference const reference = 'fixed_reference'; // ❌ Can cause transaction conflicts ``` -------------------------------- ### Override Payment Configuration at Runtime Source: https://github.com/iamraphson/react-paystack/blob/master/_autodocs/configuration.md Demonstrates how to override the default configuration, such as amount and metadata, when initializing a payment. Ensure the amount is in the smallest currency unit. ```typescript const initializePayment = usePaystackPayment({ publicKey: 'pk_test_key', email: 'user@example.com', }); // Override amount and add metadata at payment time initializePayment({ config: { amount: 100000, currency: 'USD', reference: `payment_${Date.now()}`, metadata: { custom_fields: [ { display_name: 'Additional Info', variable_name: 'info', value: 'Extra details', }, ], }, }, onSuccess: (response) => console.log('Paid'), onClose: () => console.log('Closed'), }); ``` -------------------------------- ### PaystackConsumer with Complex Custom UI Source: https://github.com/iamraphson/react-paystack/blob/master/_autodocs/api-reference/PaystackConsumer.md Illustrates how to integrate PaystackConsumer with a more complex custom user interface. This example shows a payment card with order summary and multiple payment method buttons, where only one triggers the Paystack payment. ```typescript const AdvancedPaymentUI = () => { const config = { publicKey: 'pk_test_your_public_key_here', email: 'customer@example.com', amount: 100000, reference: Date.now().toString(), }; return ( { alert(`Payment successful! Reference: ${ref.reference}`); }} onClose={() => alert('Payment cancelled')} > {({ initializePayment }) => (

Order Summary

Total: ₦1,000.00

)}
); }; ``` -------------------------------- ### Production Public Key Source: https://github.com/iamraphson/react-paystack/blob/master/_autodocs/integration-guide.md Switch to your live public key before deploying to production. It is recommended to store live keys in environment variables. ```typescript // Switch to live public key before deploying const publicKey = process.env.REACT_APP_PAYSTACK_PUBLIC_KEY; // pk_live_xxxxx ``` -------------------------------- ### Module Structure Source: https://github.com/iamraphson/react-paystack/blob/master/_autodocs/module-overview.md Illustrates the directory and file organization of the react-paystack library, showing the main entry point, type definitions, and core hooks/components. ```tree libs/ ├── index.ts # Main entry point (exports) ├── types.ts # Type definitions ├── use-paystack.ts # usePaystackPayment hook ├── paystack-button.tsx # PaystackButton component ├── paystack-consumer.tsx # PaystackConsumer component (render-props) ├── paystack-provider.tsx # PaystackProvider context provider ├── paystack-context.ts # React context definition └── paystack-actions.ts # Internal Paystack popup invocation ``` -------------------------------- ### Handle Blocked Popups in React Paystack Source: https://github.com/iamraphson/react-paystack/blob/master/_autodocs/errors.md This example shows how to manage situations where the Paystack payment dialog is blocked by browser settings. The `onClose` callback alerts the user to allow popups, and a try-catch block handles potential initialization errors. ```typescript const handlePaymentClick = () => { try { initializePayment({ onSuccess: (response) => { console.log('Payment successful:', response); }, onClose: () => { // Inform user to allow popups alert('Payment dialog was blocked. Please allow popups in your browser settings.'); }, }); } catch (error) { console.error('Error initializing payment:', error); } }; // Use button or explicit user action to trigger payment ``` -------------------------------- ### Donation Platform with usePaystackPayment Source: https://github.com/iamraphson/react-paystack/blob/master/_autodocs/integration-guide.md Implement a donation widget using usePaystackPayment for dynamic amount selection. The initializePayment function is called on button click. ```typescript import { useState } from 'react'; import { usePaystackPayment } from 'react-paystack'; function DonationWidget() { const [amount, setAmount] = useState(1000); const initializePayment = usePaystackPayment({ publicKey: process.env.REACT_APP_PAYSTACK_PUBLIC_KEY, email: donorEmail, amount, reference: `donation_${Date.now()}`, }); return (
{[500, 1000, 5000, 10000].map((amt) => ( ))}
); } ``` -------------------------------- ### Basic Paystack Button with Text Source: https://github.com/iamraphson/react-paystack/blob/master/_autodocs/api-reference/PaystackButton.md Demonstrates a simple Paystack button with custom text. Ensure you have the PaystackButton imported and provide necessary configuration like reference, email, amount, and publicKey. Define onSuccess and onClose handlers for payment events. ```typescript import React from 'react'; import { PaystackButton } from 'react-paystack'; const CheckoutPage = () => { const config = { reference: new Date().getTime().toString(), email: 'customer@example.com', amount: 50000, publicKey: 'pk_test_your_public_key_here', }; const handleSuccess = (response) => { console.log('Payment successful! Reference:', response.reference); // Handle post-payment logic (update database, send confirmation, etc.) }; const handleClose = () => { console.log('Payment window closed'); // Handle modal closure }; return ( ); }; export default CheckoutPage; ``` -------------------------------- ### Advanced Paystack Button Configuration with Metadata Source: https://github.com/iamraphson/react-paystack/blob/master/_autodocs/api-reference/PaystackButton.md Shows an advanced usage scenario with custom metadata, including 'custom_fields' for additional transaction details like order ID and product name. It also includes a post-payment verification step using fetch. ```typescript const AdvancedPaymentButton = ({ orderId, productName }) => { const config = { publicKey: 'pk_test_your_public_key_here', email: 'customer@example.com', amount: 120000, reference: Date.now().toString(), firstname: 'John', lastname: 'Doe', phone: '+2348012345678', currency: 'NGN', metadata: { custom_fields: [ { display_name: 'Order ID', variable_name: 'order_id', value: orderId, }, { display_name: 'Product', variable_name: 'product', value: productName, }, ], }, }; const handleSuccess = async (response) => { const result = await fetch('/api/verify-payment', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ reference: response.reference, orderId, }), }); const verified = await result.json(); if (verified.success) { window.location.href = '/success'; } }; return ( console.log('Order cancelled')} /> ); }; ``` -------------------------------- ### Paystack Configuration with Customer Info Source: https://github.com/iamraphson/react-paystack/blob/master/_autodocs/quick-reference.md Include customer details like name, phone, and a unique reference for better transaction tracking. The reference should be unique for each transaction. ```typescript { publicKey: 'pk_test_key', email: 'user@example.com', amount: 50000, firstname: 'John', lastname: 'Doe', phone: '+2348012345678', reference: Date.now().toString() } ``` -------------------------------- ### Minimal Paystack Configuration Source: https://github.com/iamraphson/react-paystack/blob/master/_autodocs/configuration.md Use this basic configuration for simple payment processing. It includes essential fields like public key, customer email, and amount. ```typescript const config = { publicKey: 'pk_test_your_key', email: 'customer@example.com', amount: 50000, }; ``` -------------------------------- ### PaystackConsumer Basic Usage Source: https://github.com/iamraphson/react-paystack/blob/master/_autodocs/api-reference/PaystackConsumer.md Demonstrates the basic usage of the PaystackConsumer component with a simple button to initiate payment. It includes configuration for reference, email, amount, and public key, along with success and close handlers. ```typescript import React from 'react'; import { PaystackConsumer } from 'react-paystack'; const PaymentPage = () => { const config = { reference: new Date().getTime().toString(), email: 'user@example.com', amount: 50000, publicKey: 'pk_test_your_public_key_here', }; const handleSuccess = (response) => { console.log('Payment successful:', response); }; const handleClose = () => { console.log('Payment dialog closed'); }; return ( {({ initializePayment }) => ( )} ); }; export default PaymentPage; ``` -------------------------------- ### Using Supported Currency Types in React Paystack Source: https://github.com/iamraphson/react-paystack/blob/master/_autodocs/errors.md Demonstrates how to correctly use supported currency types with explicit typing or by checking against a list of valid currencies. Ensure you use the `Currency` enum or a predefined array of supported types. ```typescript // ✅ Use supported currency types import { Currency } from 'react-paystack'; const config = { publicKey: 'pk_test_key', email: 'user@example.com', amount: 50000, currency: 'NGN' as Currency, // Explicitly typed }; // Or use the type constraint const supportedCurrencies: Currency[] = ['NGN', 'GHS', 'USD', 'ZAR', 'KES', 'XOF']; const selectCurrency = (currency: Currency) => { return { publicKey: 'pk_test_key', email: 'user@example.com', amount: 50000, currency, }; }; ``` -------------------------------- ### Integrate Payment with PaystackConsumer (Render Props) Source: https://github.com/iamraphson/react-paystack/blob/master/_autodocs/integration-guide.md This approach is ideal when multiple components need access to payment context. It uses render props to provide the initializePayment function. ```typescript import { PaystackConsumer } from 'react-paystack'; function App() { return ( console.log('Success:', ref)} onClose={() => console.log('Closed')} > {({ initializePayment }) => ( )} ); } export default App; ``` -------------------------------- ### Subscription Plan Checkout with PaystackButton Source: https://github.com/iamraphson/react-paystack/blob/master/_autodocs/integration-guide.md Integrate subscription payments using PaystackButton by providing the plan ID. The onSuccess callback should activate the subscription. ```typescript import { PaystackButton } from 'react-paystack'; function SubscriptionPage({ plan }) { return ( { // Activate subscription activateSubscription(plan.id, ref.reference); }} /> ); } ``` -------------------------------- ### Dynamic Payment Configuration Override Source: https://github.com/iamraphson/react-paystack/blob/master/_autodocs/api-reference/usePaystackPayment.md Shows how to override default payment configurations, such as currency and amount, at the time of initializing the payment. This allows for flexible payment options within the same component. ```typescript const MyAdvancedPaymentComponent = () => { const baseConfig = { publicKey: 'pk_test_your_public_key_here', email: 'user@example.com', amount: 10000, }; const initializePayment = usePaystackPayment(baseConfig); const handlePaymentWithCurrency = (currency) => { initializePayment({ config: { currency: currency, // Override currency at payment time amount: 20000, // Override amount if needed }, onSuccess: (response) => console.log('Success:', response), onClose: () => console.log('Closed'), }); }; return (
); }; ``` -------------------------------- ### Subscription Paystack Configuration Source: https://github.com/iamraphson/react-paystack/blob/master/_autodocs/configuration.md Set up recurring payments by providing a Paystack plan ID, quantity, and a unique reference for subscription transactions. ```typescript const config = { publicKey: 'pk_test_your_key', email: 'subscriber@example.com', amount: 50000, plan: 'PLN_abc123def456', // Paystack plan ID quantity: 1, currency: 'NGN', reference: `sub_${Date.now()}`, }; ``` -------------------------------- ### Import Public API Components and Hooks Source: https://github.com/iamraphson/react-paystack/blob/master/_autodocs/module-overview.md Import all user-facing components and hooks from the library's main entry point. This is the standard way to integrate react-paystack into your application. ```typescript import { usePaystackPayment, PaystackButton, PaystackConsumer } from 'react-paystack'; ``` -------------------------------- ### TypeScript Configuration for Paystack Button Source: https://github.com/iamraphson/react-paystack/blob/master/_autodocs/integration-guide.md Use this snippet for static checkout configurations in TypeScript projects. Ensure your public key is set in environment variables. ```typescript import { PaystackButton, PaystackProps } from 'react-paystack'; interface CheckoutProps { orderId: string; totalAmount: number; } const CheckoutComponent: React.FC = ({ orderId, totalAmount, }) => { const paystackConfig: PaystackProps = { publicKey: process.env.REACT_APP_PAYSTACK_PUBLIC_KEY || '', email: 'customer@example.com', amount: totalAmount * 100, // Convert to kobo reference: `order_${orderId}_${Date.now()}`, }; return ( ); }; export default CheckoutComponent; ``` -------------------------------- ### Multiple Payment Options in One Component Source: https://github.com/iamraphson/react-paystack/blob/master/_autodocs/api-reference/PaystackConsumer.md Demonstrates how to use multiple PaystackConsumer instances within a single component to offer different payment amounts or options. ```APIDOC ## Multiple Payment Options in One Component ```typescript const MultiPaymentComponent = () => { const baseConfig = { publicKey: 'pk_test_your_public_key_here', email: 'user@example.com', }; return (

Choose Payment Amount

console.log('Small payment done')} > {({ initializePayment }) => ( )} console.log('Medium payment done')} > {({ initializePayment }) => ( )} console.log('Large payment done')} > {({ initializePayment }) => ( )}
); }; ``` ``` -------------------------------- ### InitializePayment Source: https://github.com/iamraphson/react-paystack/blob/master/_autodocs/types.md The `InitializePayment` type represents the function returned by the `usePaystackPayment` hook. It is used to initiate a payment transaction with optional success and close callbacks, or to override the initial configuration for a specific transaction. ```APIDOC ## InitializePayment ### Description Function type returned by the `usePaystackPayment` hook. Calling this function initializes a payment transaction. ### Parameters #### Options Object - **onSuccess** (`callback`) - Optional - Override success callback for this transaction. - **onClose** (`callback`) - Optional - Override close callback for this transaction. - **config** (`Omit`) - Optional - Partial config to override initial hook config. `publicKey` cannot be overridden. ### Request Example ```typescript const initializePayment = usePaystackPayment({ publicKey: 'pk_test_key', email: 'user@example.com', amount: 50000, }); // Basic call initializePayment({ onSuccess: (response) => console.log('Success:', response), onClose: () => console.log('Dialog closed'), }); // With config override initializePayment({ config: { amount: 100000, currency: 'USD', }, onSuccess: (response) => console.log('Success:', response), }); ``` ```