### Authorization Usage Examples Source: https://github.com/popekabu/pay_with_paystack/blob/master/_autodocs/api-reference/Authorization.md Examples of how to use the Authorization object. ```APIDOC ## Usage Examples **Displaying card info:** ```dart void displayPaymentMethod(PaymentData data) { final auth = data.authorization; if (auth != null) { print('Card: ${auth.brand} ending in ${auth.last4}'); print('Expires: ${auth.expMonth}/${auth.expYear}'); print('Reusable for recurring: ${auth.reusable}'); } } ``` **Checking for recurring payments capability:** ```dart final canRecur = paymentData.authorization?.reusable ?? false; if (canRecur) { print('This card can be used for future recurring charges'); } ``` ``` -------------------------------- ### Create PaystackCartItem Instances Source: https://github.com/popekabu/pay_with_paystack/blob/master/_autodocs/api-reference/PaystackMetadata.md Examples demonstrating how to create PaystackCartItem objects with different product details and quantities. ```dart final item1 = PaystackCartItem( name: 'Wireless Headphones', amount: 15.00, quantity: 1, ); final item2 = PaystackCartItem( name: 'Phone Case', amount: 2.50, quantity: 2, ); ``` -------------------------------- ### Usage Examples Source: https://github.com/popekabu/pay_with_paystack/blob/master/_autodocs/api-reference/PaystackBearer.md Demonstrates how to use the PaystackBearer enum with the PayWithPayStack.now method to specify who bears transaction fees. ```APIDOC ## Usage Examples **Main account bears fees (default):** ```dart await PayWithPayStack().now( context: context, secretKey: 'sk_live_xxxx', customerEmail: 'user@example.com', reference: ref, currency: 'GHS', amount: 100.00, callbackUrl: 'https://your-callback.com', transactionCompleted: (data) {}, transactionNotCompleted: (reason) {}, subaccount: 'ACCT_xxxxxxxxxx', bearer: PaystackBearer.account, // Main account pays fees ); ``` **Subaccount bears fees:** ```dart await PayWithPayStack().now( context: context, secretKey: 'sk_live_xxxx', customerEmail: 'user@example.com', reference: ref, currency: 'GHS', amount: 100.00, callbackUrl: 'https://your-callback.com', transactionCompleted: (data) {}, transactionNotCompleted: (reason) {}, subaccount: 'ACCT_xxxxxxxxxx', bearer: PaystackBearer.subaccount, // Subaccount pays fees ); ``` **With flat fee override:** ```dart await PayWithPayStack().now( context: context, secretKey: 'sk_live_xxxx', customerEmail: 'user@example.com', reference: ref, currency: 'GHS', amount: 100.00, callbackUrl: 'https://your-callback.com', transactionCompleted: (data) {}, transactionNotCompleted: (reason) {}, subaccount: 'ACCT_xxxxxxxxxx', transactionCharge: 5.00, // GHS 5.00 flat fee to main account bearer: PaystackBearer.subaccount, // Subaccount pays Paystack fees ); ``` ``` -------------------------------- ### Combined Paystack Transaction Example Source: https://github.com/popekabu/pay_with_paystack/blob/master/_autodocs/api-reference/PaystackMetadata.md A comprehensive example demonstrating the integration of various parameters including customer details, custom fields, and cart items for a Paystack transaction. Includes transaction completion and failure callbacks. ```dart await PayWithPayStack().now( context: context, secretKey: 'sk_live_xxxx', customerEmail: 'john@example.com', reference: PayWithPayStack().generateUuidV4(), currency: 'GHS', amount: 75.50, callbackUrl: 'https://your-callback.com', transactionCompleted: (data) { print('Payment successful: ${data.amountInMajorUnit} ${data.currency}'); }, transactionNotCompleted: (reason) { print('Payment failed: $reason'); }, customerFirstName: 'John', customerLastName: 'Doe', customerPhone: '+233244000000', // Custom fields visible on Paystack Dashboard customFields: [ PaystackCustomField( displayName: 'Order ID', variableName: 'order_id', value: '#ORD-9876', ), PaystackCustomField( displayName: 'Delivery Address', variableName: 'address', value: '123 Main St, Accra', ), ], // Cart items cartItems: [ PaystackCartItem(name: 'Widget A', amount: 25.00), PaystackCartItem(name: 'Widget B', amount: 50.50), ], ); ``` -------------------------------- ### Example of toJson() Output Source: https://github.com/popekabu/pay_with_paystack/blob/master/_autodocs/api-reference/PaystackMetadata.md Illustrates the JSON output format for a PaystackCartItem, showing the amount converted to the subunit. ```json { 'name': 'Headphones', 'amount': '1500', 'quantity': 1, } ``` -------------------------------- ### Advanced Payment Options Source: https://github.com/popekabu/pay_with_paystack/blob/master/_autodocs/api-reference/PayWithPayStack.md Demonstrates initiating a payment with a comprehensive set of options, including preferred payment channels, split payments, customer prefill details, transaction metadata, and UI customizations. This example shows how to configure the AppBar and loading/error widgets. ```dart await PayWithPayStack().now( context: context, secretKey: 'sk_live_XXXXXXXXXXXXXXXXXXXXX', customerEmail: 'john@example.com', reference: PayWithPayStack().generateUuidV4(), currency: 'GHS', amount: 75.50, callbackUrl: 'https://your-callback.com', transactionCompleted: (data) { print('Paid: ${data.amountInMajorUnit} ${data.currency}'); }, transactionNotCompleted: (reason) { print('Not completed: $reason'); }, // Channels channels: [ PaystackChannel.card, PaystackChannel.mobileMoney, PaystackChannel.bankTransfer, ], // Split payment subaccount: 'ACCT_xxxxxxxxxx', transactionCharge: 5.00, bearer: PaystackBearer.subaccount, // Customer prefill customerFirstName: 'John', customerLastName: 'Doe', customerPhone: '+233244000000', // Metadata cartItems: [ PaystackCartItem(name: 'Headphones', amount: 50.00, quantity: 1), PaystackCartItem(name: 'Cable', amount: 5.00, quantity: 2), ], customFields: [ PaystackCustomField( displayName: 'Order ID', variableName: 'order_id', value: '#ORD-1234', ), ], // UI showAppBar: true, appBarTitle: 'Secure Payment', appBarColor: const Color(0xFF0A0A1A), appBarTextColor: Colors.white, ); ``` -------------------------------- ### Initiate Payment with Flat Fee Override and Subaccount Bearing Fees Source: https://github.com/popekabu/pay_with_paystack/blob/master/_autodocs/api-reference/PaystackBearer.md Example demonstrating how to set a flat transaction fee override while the subaccount bears the standard Paystack fees. This allows for custom fee structures. ```dart await PayWithPayStack().now( context: context, secretKey: 'sk_live_xxxx', customerEmail: 'user@example.com', reference: ref, currency: 'GHS', amount: 100.00, callbackUrl: 'https://your-callback.com', transactionCompleted: (data) {}, transactionNotCompleted: (reason) {}, subaccount: 'ACCT_xxxxxxxxxx', transactionCharge: 5.00, // GHS 5.00 flat fee to main account bearer: PaystackBearer.subaccount, // Subaccount pays Paystack fees ); ``` -------------------------------- ### Example Metadata for Transaction Source: https://github.com/popekabu/pay_with_paystack/blob/master/doc/api/index.html Include custom fields within the metadata object for additional development purposes, such as storing customer contact information. ```json "metadata": { "custom_fields": [ { "name": "Daniel Kabu Asare", "phone": "+2330267268224" } ] } ``` -------------------------------- ### Display Card Information Source: https://github.com/popekabu/pay_with_paystack/blob/master/_autodocs/api-reference/Authorization.md Example of how to display card details from an Authorization object. Assumes `PaymentData` contains an `Authorization` object. ```dart void displayPaymentMethod(PaymentData data) { final auth = data.authorization; if (auth != null) { print('Card: ${auth.brand} ending in ${auth.last4}'); print('Expires: ${auth.expMonth}/${auth.expYear}'); print('Reusable for recurring: ${auth.reusable}'); } } ``` -------------------------------- ### Initiate Payment with Subaccount Bearing Fees Source: https://github.com/popekabu/pay_with_paystack/blob/master/_autodocs/api-reference/PaystackBearer.md Example of initiating a Paystack transaction where the subaccount bears the transaction fees. This is useful for specific split payment scenarios. ```dart await PayWithPayStack().now( context: context, secretKey: 'sk_live_xxxx', customerEmail: 'user@example.com', reference: ref, currency: 'GHS', amount: 100.00, callbackUrl: 'https://your-callback.com', transactionCompleted: (data) {}, transactionNotCompleted: (reason) {}, subaccount: 'ACCT_xxxxxxxxxx', bearer: PaystackBearer.subaccount, // Subaccount pays fees ); ``` -------------------------------- ### Initiate Payment with Main Account Bearing Fees Source: https://github.com/popekabu/pay_with_paystack/blob/master/_autodocs/api-reference/PaystackBearer.md Example of initiating a Paystack transaction where the main account bears the transaction fees. This is the default behavior. ```dart await PayWithPayStack().now( context: context, secretKey: 'sk_live_xxxx', customerEmail: 'user@example.com', reference: ref, currency: 'GHS', amount: 100.00, callbackUrl: 'https://your-callback.com', transactionCompleted: (data) {}, transactionNotCompleted: (reason) {}, subaccount: 'ACCT_xxxxxxxxxx', bearer: PaystackBearer.account, // Main account pays fees ); ``` -------------------------------- ### Custom Metadata and Cart Items Example Source: https://github.com/popekabu/pay_with_paystack/blob/master/_autodocs/INDEX.md Demonstrates how to combine custom fields, cart items, and raw metadata for a transaction. Ensure custom fields have a displayName, variableName, and value. Cart items require a name and amount. ```dart customFields: [ PaystackCustomField( displayName: 'Order ID', variableName: 'order_id', value: '#ORD-1234', ), ], cartItems: [ PaystackCartItem(name: 'Widget', amount: 50.00), ], metadata: { 'custom_key': 'custom_value', }, ``` -------------------------------- ### Provide a Custom Loading Widget Source: https://github.com/popekabu/pay_with_paystack/blob/master/_autodocs/configuration.md Replace the default branded pulsing loader with a custom widget during WebView initialization. The example shows a centered CircularProgressIndicator. ```dart loadingWidget: const Center( child: CircularProgressIndicator( color: Colors.green, strokeWidth: 3.0, ), ), ``` -------------------------------- ### Instantiate PaystackException Source: https://github.com/popekabu/pay_with_paystack/blob/master/_autodocs/api-reference/PaystackException.md Example of throwing a PaystackException with a specific error message, HTTP status code, and response body. This is useful for signaling API communication failures. ```dart throw PaystackException( message: 'Failed to initialize transaction', statusCode: 401, responseBody: '{"status":false,"message":"Invalid secret key"}', ); ``` -------------------------------- ### Initialize and Make Payment Source: https://github.com/popekabu/pay_with_paystack/blob/master/doc/api/index.html Demonstrates how to initialize the PayWithPayStack class and initiate a payment transaction with specified details. ```APIDOC ## Initialize and Make Payment ### Description This operation shows how to use the `PayWithPayStack` class to initiate a payment. You need to provide essential details such as the context, secret key, customer email, reference, currency, amount, and optionally, payment channels and metadata. ### Method Dart Method Call ### Endpoint N/A (Dart SDK) ### Parameters #### Required Parameters - **context** (BuildContext) - The current build context from your Flutter application. - **secretKey** (String) - Your Paystack secret key. - **customerEmail** (String) - The email address of the customer making the payment. - **reference** (String) - A unique identifier for the transaction. - **currency** (String) - The currency code for the transaction (e.g., "GHS"). - **amount** (String) - The amount to be charged, in the smallest currency unit (e.g., kobo for GHS). - **transactionCompleted** (Function) - A callback function executed when the transaction is successful. - **transactionNotCompleted** (Function) - A callback function executed when the transaction is not successful. #### Optional Parameters - **paymentChannels** (List) - A list of payment channels to enable (e.g., `["mobile_money", "card"]`). Available channels include `card`, `bank`, `ussd`, `qr`, `mobile_money`, `bank_transfer`, `eft`. - **metadata** (Map) - Additional data for development purposes, such as custom fields. ### Request Example ```dart PayWithPayStack().now( context: context, secretKey: "sk_live_XXXXXXXXXXXXXXXXXXXXXXXXXXXX", customerEmail: "popekabu@gmail.com", reference: DateTime.now().microsecondsSinceEpoch.toString(), currency: "GHS", paymentChannels: ["mobile_money", "card"], amount: "20000", transactionCompleted: () { print("Transaction Successful"); }, transactionNotCompleted: () { print("Transaction Not Successful!"); }, metadata: { "custom_fields": [ { "name": "Daniel Kabu Asare", "phone": "+2330267268224" } ] } ); ``` ### Response #### Callbacks - **transactionCompleted**: This callback is invoked upon successful completion of the transaction. - **transactionNotCompleted**: This callback is invoked if the transaction fails or is not completed. ### Definitions - **context**: Passed from the current view. - **secretKey**: Provided by Paystack. - **customerEmail**: Email address of the user/customer for receipt purposes. - **reference**: Unique ID for transaction recognition. - **currency**: Currency to be charged. - **amount**: Value to be charged. - **paymentChannels**: Optional list of available payment channels. - **metadata**: Optional extra data for development purposes. ``` -------------------------------- ### Full Parameter Reference Source: https://github.com/popekabu/pay_with_paystack/blob/master/README.md A comprehensive list of all available parameters for the `PayWithPayStack().now()` method, detailing their types, requirements, and default values. ```APIDOC ## Full Parameter Reference ### Description This section provides a detailed breakdown of every parameter accepted by the `PayWithPayStack().now()` method, including their data types, whether they are mandatory, their default values, and a brief explanation. ### Parameters | Parameter | Type | Required | Default | |-------------------------|------------------------------------------|----------|----------------------| | `context` | `BuildContext` | ✅ | — | | `secretKey` | `String` | ✅ | — | | `customerEmail` | `String` | ✅ | — | | `reference` | `String` | ✅ | — | | `callbackUrl` | `String` | ✅ | — | | `currency` | `String` | ✅ | — | | `amount` | `double` | ✅ | — | | `transactionCompleted` | `Function(PaymentData)` | ✅ | — | | `transactionNotCompleted` | `Function(String)` | ✅ | — | | `channels` | `List?` | ❌ | all channels | | `plan` | `String?` | ❌ | `null` | | `invoiceLimit` | `int?` | ❌ | `null` | | `subaccount` | `String?` | ❌ | `null` | | `splitCode` | `String?` | ❌ | `null` | | `transactionCharge` | `double?` | ❌ | `null` | | `bearer` | `PaystackBearer?` | ❌ | `null` | | `customerFirstName` | `String?` | ❌ | `null` | | `customerLastName` | `String?` | ❌ | `null` | | `customerPhone` | `String?` | ❌ | `null` | | `customFields` | `List?` | ❌ | `null` | | `cartItems` | `List?` | ❌ | `null` | | `metadata` | `Map?` | ❌ | `null` | | `showAppBar` | `bool` | ❌ | `true` | | `appBarTitle` | `String` | ❌ | ` ``` -------------------------------- ### Initiate Payment with Paystack Source: https://github.com/popekabu/pay_with_paystack/blob/master/_autodocs/api-reference/PayWithPayStack.md This snippet demonstrates how to initiate a payment transaction using the `now()` method. It includes essential parameters like secret key, amount, currency, and callback URL, along with handling successful and failed transactions. ```APIDOC ## now() ### Description Initiates a payment transaction using Paystack. ### Method `PayWithPayStack().now()` ### Parameters #### Core Parameters - **context** (BuildContext) - Required - The build context for the widget. - **secretKey** (String) - Required - Your Paystack secret key. - **customerEmail** (String) - Required - The email address of the customer. - **reference** (String) - Required - A unique reference for the transaction. - **currency** (String) - Required - The currency code for the transaction (e.g., 'GHS'). - **amount** (double) - Required - The amount to be charged. - **callbackUrl** (String) - Required - The URL to redirect to after the transaction. - **transactionCompleted** (Function(PaymentData)) - Required - Callback function for successful transactions. - **transactionNotCompleted** (Function(String)) - Required - Callback function for failed transactions. #### UI Customisation Parameters - **showAppBar** (bool) - Optional - Show the AppBar above the WebView. Defaults to `true`. - **appBarTitle** (String) - Optional - AppBar title text. Defaults to `"Secure Checkout"`. - **appBarColor** (Color?) - Optional - AppBar background color. Defaults to `null` (uses dark theme default if `null`). - **appBarTextColor** (Color?) - Optional - AppBar text and icon color. Defaults to `null`. - **loadingWidget** (Widget?) - Optional - Custom widget shown while checkout initialises. Defaults to `null` (uses branded loader). - **errorWidget** (Widget Function(String, VoidCallback)?) - Optional - Custom error screen builder. Defaults to `null`. #### Additional Parameters - **channels** (List?) - Optional - List of payment channels to enable. - **subaccount** (String?) - Optional - Subaccount ID for split payments. - **transactionCharge** (double?) - Optional - The charge for the transaction. - **bearer** (PaystackBearer?) - Optional - Specifies who bears the transaction charge. - **customerFirstName** (String?) - Optional - Customer's first name. - **customerLastName** (String?) - Optional - Customer's last name. - **customerPhone** (String?) - Optional - Customer's phone number. - **cartItems** (List?) - Optional - Cart line items for transaction metadata. - **customFields** (List?) - Optional - Custom fields for the transaction. ### Request Example (Basic) ```dart import 'package:flutter/material.dart'; import 'package:pay_with_paystack/pay_with_paystack.dart'; void _initiatePayment(BuildContext context) async { final ref = PayWithPayStack().generateUuidV4(); final result = await PayWithPayStack().now( context: context, secretKey: 'sk_live_XXXXXXXXXXXXXXXXXXXXX', customerEmail: 'user@example.com', reference: ref, currency: 'GHS', amount: 50.00, callbackUrl: 'https://your-callback.com', transactionCompleted: (PaymentData data) { print('✅ Payment successful!'); print('Amount: ${data.amountInMajorUnit} ${data.currency}'); print('Reference: ${data.reference}'); print('Channel: ${data.channel}'); }, transactionNotCompleted: (String reason) { print('❌ Payment failed: $reason'); }, ); } ``` ### Request Example (With all options) ```dart await PayWithPayStack().now( context: context, secretKey: 'sk_live_XXXXXXXXXXXXXXXXXXXXX', customerEmail: 'john@example.com', reference: PayWithPayStack().generateUuidV4(), currency: 'GHS', amount: 75.50, callbackUrl: 'https://your-callback.com', transactionCompleted: (data) { print('Paid: ${data.amountInMajorUnit} ${data.currency}'); }, transactionNotCompleted: (reason) { print('Not completed: $reason'); }, // Channels channels: [ PaystackChannel.card, PaystackChannel.mobileMoney, PaystackChannel.bankTransfer, ], // Split payment subaccount: 'ACCT_xxxxxxxxxx', transactionCharge: 5.00, bearer: PaystackBearer.subaccount, // Customer prefill customerFirstName: 'John', customerLastName: 'Doe', customerPhone: '+233244000000', // Metadata cartItems: [ PaystackCartItem(name: 'Headphones', amount: 50.00, quantity: 1), PaystackCartItem(name: 'Cable', amount: 5.00, quantity: 2), ], customFields: [ PaystackCustomField( displayName: 'Order ID', variableName: 'order_id', value: '#ORD-1234', ), ], // UI showAppBar: true, appBarTitle: 'Secure Payment', appBarColor: const Color(0xFF0A0A1A), appBarTextColor: Colors.white, ); ``` ``` -------------------------------- ### Initiate Payment with Paystack Source: https://github.com/popekabu/pay_with_paystack/blob/master/doc/api/index.html Use the PayWithPayStack class to initiate payments. Provide context, secret key, customer email, a unique reference, currency, amount, and desired payment channels. Callbacks are available for transaction completion status. ```dart PayWithPayStack().now( context: context, secretKey: "sk_live_XXXXXXXXXXXXXXXXXXXXXXXXXXXX", customerEmail: "popekabu@gmail.com", reference: DateTime.now().microsecondsSinceEpoch.toString(), currency: "GHS", paymentChannel:["mobile_money", "card"] amount: "20000", transactionCompleted: () { print("Transaction Successful"); }, transactionNotCompleted: () { print("Transaction Not Successful!"); }); ``` -------------------------------- ### Get Raw String Value of Channel Source: https://github.com/popekabu/pay_with_paystack/blob/master/_autodocs/api-reference/PaystackChannel.md Access the raw string value of a PaystackChannel enum for API interaction. ```dart final channel = PaystackChannel.card; print(channel.value); // "card" ``` -------------------------------- ### Initiate Payment with Paystack Source: https://github.com/popekabu/pay_with_paystack/blob/master/_autodocs/README.md Use the `now` method to initiate a payment transaction. Ensure all required parameters are provided, including context, secret key, customer email, reference, currency, amount, and callback URLs for transaction completion and non-completion events. ```dart import 'package:pay_with_paystack/pay_with_paystack.dart'; // Initiate payment await PayWithPayStack().now( context: context, secretKey: 'sk_live_xxxx', customerEmail: 'user@example.com', reference: PayWithPayStack().generateUuidV4(), currency: 'GHS', amount: 50.00, callbackUrl: 'https://your-app.com/callback', transactionCompleted: (PaymentData data) { print('Status: ${data.status}'); }, transactionNotCompleted: (String reason) { print('Cancelled: $reason'); }, ); ``` -------------------------------- ### Initiate Payment Source: https://github.com/popekabu/pay_with_paystack/blob/master/_autodocs/README.md Initiates a payment transaction using the PayWithPayStack class. This method requires several parameters to configure the transaction, including secret key, customer email, amount, currency, and callback URLs. It also provides callbacks for transaction completion and non-completion. ```APIDOC ## Initiate Payment ### Description Initiates a payment transaction using the `PayWithPayStack` class. This method requires several parameters to configure the transaction, including secret key, customer email, amount, currency, and callback URLs. It also provides callbacks for transaction completion and non-completion. ### Class `PayWithPayStack` ### Method Signature ```dart Future now({ required BuildContext context, required String secretKey, required String customerEmail, required String reference, required String currency, required double amount, required String callbackUrl, required void Function(PaymentData data) transactionCompleted, required void Function(String reason) transactionNotCompleted, // ... other optional parameters }) ``` ### Parameters #### Required Parameters - **context** (BuildContext) - The build context for the widget. - **secretKey** (String) - Your Paystack secret key. - **customerEmail** (String) - The email address of the customer. - **reference** (String) - A unique reference for the transaction. Use `PayWithPayStack().generateUuidV4()` for a UUID. - **currency** (String) - The currency code for the transaction (e.g., 'GHS'). - **amount** (double) - The transaction amount. - **callbackUrl** (String) - The URL to redirect to after the transaction. - **transactionCompleted** (Function(PaymentData)) - Callback function executed when the transaction is completed. - **transactionNotCompleted** (Function(String)) - Callback function executed when the transaction is not completed. ### Request Example ```dart await PayWithPayStack().now( context: context, secretKey: 'sk_live_xxxx', customerEmail: 'user@example.com', reference: PayWithPayStack().generateUuidV4(), currency: 'GHS', amount: 50.00, callbackUrl: 'https://your-app.com/callback', transactionCompleted: (PaymentData data) { print('Status: ${data.status}'); }, transactionNotCompleted: (String reason) { print('Cancelled: $reason'); }, ); ``` ### Return Type `Future` - Returns `PaymentData` on successful completion, or `null` if the transaction was not completed or an error occurred. ``` -------------------------------- ### Create a Subscription Plan Source: https://github.com/popekabu/pay_with_paystack/blob/master/README.md Use the `plan` and `invoiceLimit` parameters to set up recurring payments. The `invoiceLimit` specifies the total number of charges before the subscription stops. ```dart PayWithPayStack().now( // ... plan: 'PLN_xxxxxxxxxx', invoiceLimit: 12, // charge 12 times then stop ); ``` -------------------------------- ### Configure Secret Key Source: https://github.com/popekabu/pay_with_paystack/blob/master/_autodocs/configuration.md Your Paystack secret API key is required. It must start with 'sk_live_' for production or 'sk_test_' for testing. Obtain this from your Paystack Dashboard. ```dart secretKey: 'sk_live_XXXXXXXXXXXXXXXXXXXXX', ``` -------------------------------- ### Initiate Basic Payment Source: https://github.com/popekabu/pay_with_paystack/blob/master/_autodocs/README.md Use this for a standard payment flow. Ensure you provide all required parameters like context, secret key, customer email, a unique reference, currency, amount, and callback URL. The `transactionCompleted` and `transactionNotCompleted` callbacks handle the payment outcome. ```dart await PayWithPayStack().now( context: context, secretKey: 'sk_live_xxx', customerEmail: 'user@example.com', reference: PayWithPayStack().generateUuidV4(), currency: 'GHS', amount: 50.00, callbackUrl: 'https://your-app.com/callback', transactionCompleted: (data) => print('Done: ${data.status}'), transactionNotCompleted: (reason) => print('Cancelled: $reason'), ); ``` -------------------------------- ### PayWithPayStack.now method implementation Source: https://github.com/popekabu/pay_with_paystack/blob/master/doc/api/pay_with_paystack/PayWithPayStack/now.html The implementation of the 'now' method navigates to the PaystackPayNow screen, passing all necessary parameters for the payment process. It includes callbacks for transaction success and failure. ```dart Future now({ ///Context provided from current view required BuildContext context, ///Secret key is provided from your paystack account required String secretKey, ///Email of the customer required String customerEmail, ///Alpha numeric and/or number ID to a transaction required String reference, ///Currency of the transaction required String currency, ///Amount you want to charge the user. Add extra two zeros after typing the amount required String amount, ///What happens next after transaction is completed required VoidCallback transactionCompleted, ///What happens next after transaction is not completed required VoidCallback transactionNotCompleted, ///Extra data not consumed by Paystack but for developer purposes Object? metaData, ///Payment Channels you want to make available to the user Object? paymentChannel, }) { return Navigator.push( context, MaterialPageRoute( builder: (context) => PaystackPayNow( secretKey: secretKey, email: customerEmail, reference: reference, currency: currency, amount: amount, paymentChannel: paymentChannel, metadata: metaData, transactionCompleted: transactionCompleted, transactionNotCompleted: transactionNotCompleted, )), ); } ``` -------------------------------- ### PayWithPayStack Constructor Source: https://github.com/popekabu/pay_with_paystack/blob/master/doc/api/pay_with_paystack/PayWithPayStack/PayWithPayStack.html Initializes a new instance of the PayWithPayStack class. This constructor supports null safety. ```APIDOC ## PayWithPayStack() ### Description Initializes a new instance of the PayWithPayStack class. This constructor supports null safety. ### Method constructor ### Endpoint N/A (Dart class constructor) ### Parameters This constructor does not take any parameters. ### Request Example ```dart var paystack = PayWithPayStack(); ``` ### Response N/A (Constructors do not return values in the traditional sense; they initialize an object.) ``` -------------------------------- ### PayWithPayStack.now Source: https://github.com/popekabu/pay_with_paystack/blob/master/doc/api/pay_with_paystack/PayWithPayStack-class.html Initiates a payment transaction using Paystack. This method requires several parameters to configure the transaction and provides callbacks for completion status. ```APIDOC ## PayWithPayStack.now ### Description Initiates a payment transaction using Paystack. This method requires several parameters to configure the transaction and provides callbacks for completion status. ### Method Signature `PayWithPayStack.now({required BuildContext context, required String secretKey, required String customerEmail, required String reference, required String currency, required String amount, required VoidCallback transactionCompleted, required VoidCallback transactionNotCompleted, Object? metaData, Object? paymentChannel})` ### Parameters #### Required Parameters - **context** (BuildContext) - The build context for the widget. - **secretKey** (String) - Your Paystack secret key. - **customerEmail** (String) - The email address of the customer. - **reference** (String) - A unique transaction reference. - **currency** (String) - The currency of the transaction (e.g., 'NGN'). - **amount** (String) - The amount to be charged, in the smallest currency unit (e.g., kobo for NGN). - **transactionCompleted** (VoidCallback) - Callback function executed when the transaction is successfully completed. - **transactionNotCompleted** (VoidCallback) - Callback function executed when the transaction is not completed. #### Optional Parameters - **metaData** (Object?) - Additional metadata to be sent with the transaction. - **paymentChannel** (Object?) - Specifies the payment channel(s) to be used (e.g., ['card', 'bank']). ### Returns A [Future] that completes when the payment process is initiated. ``` -------------------------------- ### Create Subscription Source: https://github.com/popekabu/pay_with_paystack/blob/master/README.md This snippet demonstrates how to create a subscription with a specified plan and invoice limit, ensuring the charge occurs a set number of times before stopping. ```APIDOC ## Create Subscription ### Description Initiate a recurring payment subscription by specifying the plan ID and the total number of invoices to be generated. ### Method `PayWithPayStack().now()` ### Parameters - **plan** (String) - Required for subscriptions. The ID of the payment plan. - **invoiceLimit** (int) - Optional. The number of times the subscription should be charged before automatically stopping. ### Request Example ```dart PayWithPayStack().now( // ... other parameters plan: 'PLN_xxxxxxxxxx', invoiceLimit: 12, // charge 12 times then stop ); ``` ``` -------------------------------- ### now() Source: https://github.com/popekabu/pay_with_paystack/blob/master/_autodocs/api-reference/PayWithPayStack.md Launches the Paystack payment WebView and resolves with PaymentData when the checkout session ends. This method is the primary way to initiate a payment flow. ```APIDOC ## now() ### Description Launches the Paystack payment WebView and resolves with `PaymentData` when the checkout session ends (whether successful or not). ### Signature ```dart Future now({ required BuildContext context, required String secretKey, required String customerEmail, required String reference, required String callbackUrl, required String currency, required double amount, required Function(PaymentData data) transactionCompleted, required Function(String reason) transactionNotCompleted, List? channels, String? plan, int? invoiceLimit, String? subaccount, String? splitCode, double? transactionCharge, PaystackBearer? bearer, String? customerFirstName, String? customerLastName, String? customerPhone, List? customFields, List? cartItems, Map? metadata, bool showAppBar = true, String appBarTitle = 'Secure Checkout', Color? appBarColor, Color? appBarTextColor, Widget? loadingWidget, Widget Function(String error, VoidCallback retry)? errorWidget, }) ``` ### Return Type `Future` - Completes with `PaymentData` if a transaction is processed (success or failure); `null` if the WebView is dismissed without processing. ### Throws - `PaystackException` — when the Paystack API request fails ### Parameters (Core / Required) | Parameter | Type | Required | Default | Description | |-----------|------|----------|---------|-------------| | `context` | `BuildContext` | ✅ | — | Current `BuildContext` used for navigation. | | `secretKey` | `String` | ✅ | — | Your Paystack secret key (`sk_live_…` or `sk_test_…`). | | `customerEmail` | `String` | ✅ | — | The customer's email address. | | `reference` | `String` | ✅ | — | Unique transaction reference (use `generateUuidV4()`). | | `callbackUrl` | `String` | ✅ | — | Redirect URL after payment; must match Paystack dashboard setting. | | `currency` | `String` | ✅ | — | ISO 4217 currency code (e.g. `"GHS"`, `"NGN"`, `"ZAR"`). | | `amount` | `double` | ✅ | — | Amount in the major unit (e.g. `50.0` = GHS 50.00). Converted to pesewas/kobo automatically. | | `transactionCompleted` | `Function(PaymentData)` | ✅ | — | Callback invoked on successful payment. | | `transactionNotCompleted` | `Function(String)` | ✅ | — | Callback invoked on payment failure (receives status/error reason). | ### Parameters (Payment Channels) | Parameter | Type | Required | Default | Description | |-----------|------|----------|---------|-------------| | `channels` | `List?` | ❌ | `null` (all channels) | Restrict which payment options are shown to the customer. | ### Parameters (Subscriptions) | Parameter | Type | Required | Default | Description | |-----------|------|----------|---------|-------------| | `plan` | `String?` | ❌ | `null` | Paystack subscription plan code (e.g. `PLN_xxxxxxxxxx`). | | `invoiceLimit` | `int?` | ❌ | `null` | Number of times to charge the customer during the plan. | ### Parameters (Split Payments) | Parameter | Type | Required | Default | Description | |-----------|------|----------|---------|-------------| | `subaccount` | `String?` | ❌ | `null` | Subaccount code to route/split payment (e.g. `ACCT_xxxxxxxxxx`). | | `splitCode` | `String?` | ❌ | `null` | Pre-defined multi-recipient split group code (e.g. `SPL_xxxxxxxxxx`). | | `transactionCharge` | `double?` | ❌ | `null` | Flat fee (major unit) that goes to the main account when splitting. | | `bearer` | `PaystackBearer?` | ❌ | `null` | Who bears the Paystack transaction fees. | ### Parameters (Customer Prefill) | Parameter | Type | Required | Default | Description | |-----------|------|----------|---------|-------------| | `customerFirstName` | `String?` | ❌ | `null` | Pre-fills the customer's first name on the checkout form. | | `customerLastName` | `String?` | ❌ | `null` | Pre-fills the customer's last name on the checkout form. | | `customerPhone` | `String?` | ❌ | `null` | Pre-fills the customer's phone number on the checkout form. | ### Parameters (Structured Metadata) | Parameter | Type | Required | Default | Description | |-----------|------|----------|---------|-------------| | `customFields` | `List?` | ❌ | `null` | Custom fields to include in the transaction metadata. | | `cartItems` | `List?` | ❌ | `null` | Items included in the transaction. | | `metadata` | `Map?` | ❌ | `null` | Arbitrary key-value pairs to attach to the transaction. | ### Parameters (UI Customization) | Parameter | Type | Required | Default | Description | |-----------|------|----------|---------|-------------| | `showAppBar` | `bool` | ❌ | `true` | Whether to display an app bar in the WebView. | | `appBarTitle` | `String` | ❌ | `'Secure Checkout'` | Title to display in the app bar. | | `appBarColor` | `Color?` | ❌ | `null` | Background color of the app bar. | | `appBarTextColor` | `Color?` | ❌ | `null` | Text color of the app bar. | | `loadingWidget` | `Widget?` | ❌ | `null` | Widget to display while the WebView is loading. | | `errorWidget` | `Widget Function(String error, VoidCallback retry)?` | ❌ | `null` | Widget to display in case of an error, with a retry callback. | ### Example ```dart final paystack = PayWithPayStack(); try { await paystack.now( context: context, secretKey: "sk_test_YOUR_SECRET_KEY", customerEmail: "customer@example.com", reference: paystack.generateUuidV4(), callbackUrl: "https://your-app.com/callback", currency: "NGN", amount: 10000.00, transactionCompleted: (PaymentData data) { print("Transaction successful: ${data.reference}"); }, transactionNotCompleted: (String reason) { print("Transaction failed: $reason"); }, // Optional parameters can be added here // channels: [PaystackChannel.card, PaystackChannel.bank], // metadata: {"custom_fields": [{"display_name": "Order ID", "variable_name": "order_id", "value": "12345"}]} ); } catch (e) { print("An error occurred: $e"); } ``` ``` -------------------------------- ### now Source: https://github.com/popekabu/pay_with_paystack/blob/master/doc/api/pay_with_paystack/PayWithPayStack/now.html Initiates a payment transaction with Paystack. This method navigates to a payment screen and handles the transaction flow. ```APIDOC ## now ### Description Initiates a payment transaction with Paystack. This method navigates to a payment screen and handles the transaction flow. ### Method `now` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters * **context** (BuildContext) - Required - The build context for the current view. * **secretKey** (String) - Required - Your Paystack secret key. * **customerEmail** (String) - Required - The email address of the customer. * **reference** (String) - Required - A unique alphanumeric ID for the transaction. * **currency** (String) - Required - The currency of the transaction (e.g., 'NGN'). * **amount** (String) - Required - The amount to charge. Append two zeros for kobo/cents (e.g., '10000' for 100.00). * **transactionCompleted** (VoidCallback) - Required - Callback function executed when the transaction is successfully completed. * **transactionNotCompleted** (VoidCallback) - Required - Callback function executed when the transaction is not completed. * **metaData** (Object?) - Optional - Additional data for developer use, not consumed by Paystack. * **paymentChannel** (Object?) - Optional - Specifies the payment channels to be made available to the user. ### Request Example ```dart PayWithPayStack().now( context: context, secretKey: 'YOUR_SECRET_KEY', customerEmail: 'customer@example.com', reference: 'TXN123456789', currency: 'NGN', amount: '50000', transactionCompleted: () { // Handle successful transaction print('Transaction successful!'); }, transactionNotCompleted: () { // Handle failed transaction print('Transaction failed!'); }, metaData: {'order_id': 'ORD987'}, paymentChannel: ['card', 'bank'] ); ``` ### Response * Returns a `Future` which resolves when the payment process is complete. #### Success Response (Implicit) * The `transactionCompleted` callback is invoked upon successful payment. #### Response Example (No direct response body, relies on callbacks) #### Error Handling * The `transactionNotCompleted` callback is invoked if the transaction fails or is not completed. ``` -------------------------------- ### Perform Payment with Paystack Source: https://github.com/popekabu/pay_with_paystack/blob/master/README.md Initiate a payment transaction using the `PayWithPayStack().now()` method. Ensure you provide all required parameters, including secret key, customer details, amount, and callback URL. The `transactionCompleted` callback handles successful payments, while `transactionNotCompleted` handles failures. ```dart import 'package:pay_with_paystack/pay_with_paystack.dart'; final ref = PayWithPayStack().generateUuidV4(); await PayWithPayStack().now( context: context, secretKey: 'sk_live_XXXXXXXXXXXXXXXXXXXXX', customerEmail: 'user@example.com', reference: ref, currency: 'GHS', amount: 50.00, // GHS 50.00 — converted to pesewas automatically callbackUrl: 'https://your-callback.com', transactionCompleted: (PaymentData data) { print('✅ Paid ${data.amountInMajorUnit} ${data.currency}'); print(' Reference : ${data.reference}'); print(' Channel : ${data.channel}'); print(' Customer : ${data.customer?.fullName}'); }, transactionNotCompleted: (String reason) { print('❌ Payment not completed: $reason'); }, ); ``` -------------------------------- ### Basic Payment Initiation Source: https://github.com/popekabu/pay_with_paystack/blob/master/_autodocs/api-reference/PayWithPayStack.md Initiates a payment transaction with essential details like amount, currency, and customer email. It includes callbacks for successful and failed transactions. Ensure you have imported the necessary packages. ```dart import 'package:flutter/material.dart'; import 'package:pay_with_paystack/pay_with_paystack.dart'; void _initiatePayment(BuildContext context) async { final ref = PayWithPayStack().generateUuidV4(); final result = await PayWithPayStack().now( context: context, secretKey: 'sk_live_XXXXXXXXXXXXXXXXXXXXX', customerEmail: 'user@example.com', reference: ref, currency: 'GHS', amount: 50.00, callbackUrl: 'https://your-callback.com', transactionCompleted: (PaymentData data) { print('✅ Payment successful!'); print('Amount: ${data.amountInMajorUnit} ${data.currency}'); print('Reference: ${data.reference}'); print('Channel: ${data.channel}'); }, transactionNotCompleted: (String reason) { print('❌ Payment failed: $reason'); }, ); } ``` -------------------------------- ### PayWithPayStack Class Source: https://github.com/popekabu/pay_with_paystack/blob/master/_autodocs/INDEX.md The main entry point for interacting with the Pay with Paystack library. It provides methods to initiate payments and generate transaction IDs. ```APIDOC ## Class: PayWithPayStack ### Description This is the primary class for using the Pay with Paystack SDK. It serves as the entry point for all payment-related operations. ### Methods - **`generateUuidV4()`** - **Description**: Generates a unique identifier for transactions, typically a UUID version 4. - **Purpose**: Ensures each transaction has a distinct ID for tracking and management. - **`now()`** - **Description**: Initiates a new payment process. - **Purpose**: Starts the workflow for processing a payment through Paystack. ``` -------------------------------- ### Customer Constructor Source: https://github.com/popekabu/pay_with_paystack/blob/master/_autodocs/api-reference/Customer.md Initializes a new immutable Customer instance. All fields are optional. ```dart const Customer({ this.id, this.firstName, this.lastName, this.email, this.customerCode, this.phone, this.metadata, }) ```