### Installation Configuration Source: https://github.com/flutterwave/flutter-v3/blob/master/example/windows/CMakeLists.txt Configures installation rules for the application and its components. It sets the installation prefix to be adjacent to the executable for in-place running and defines destinations for data and libraries. ```cmake set(BUILD_BUNDLE_DIR "$") set(CMAKE_VS_INCLUDE_INSTALL_TO_DEFAULT_BUILD 1) if(CMAKE_INSTALL_PREFIX_INITIALIZED_TO_DEFAULT) set(CMAKE_INSTALL_PREFIX "${BUILD_BUNDLE_DIR}" CACHE PATH "..." FORCE) endif() set(INSTALL_BUNDLE_DATA_DIR "${CMAKE_INSTALL_PREFIX}/data") set(INSTALL_BUNDLE_LIB_DIR "${CMAKE_INSTALL_PREFIX}") ``` -------------------------------- ### Install Application Target Source: https://github.com/flutterwave/flutter-v3/blob/master/example/windows/CMakeLists.txt Installs the main application executable to the runtime destination. ```cmake install(TARGETS ${BINARY_NAME} RUNTIME DESTINATION "${CMAKE_INSTALL_PREFIX}" COMPONENT Runtime) ``` -------------------------------- ### Install Flutterwave Flutter SDK Source: https://github.com/flutterwave/flutter-v3/blob/master/_autodocs/README.md Add the flutterwave_standard package to your pubspec.yaml file and run flutter pub get to install it. ```yaml dependencies: flutterwave_standard: 1.1.0 ``` -------------------------------- ### Installation Rules for Flutter Linux App Bundle Source: https://github.com/flutterwave/flutter-v3/blob/master/example/linux/CMakeLists.txt Defines how the application bundle is installed, including cleaning the build directory, installing the executable, data files, libraries, and assets. ```cmake # === Installation === # By default, "installing" just makes a relocatable bundle in the build # directory. set(BUILD_BUNDLE_DIR "${PROJECT_BINARY_DIR}/bundle") if(CMAKE_INSTALL_PREFIX_INITIALIZED_TO_DEFAULT) set(CMAKE_INSTALL_PREFIX "${BUILD_BUNDLE_DIR}" CACHE PATH "..." FORCE) endif() # Start with a clean build bundle directory every time. install(CODE " file(REMOVE_RECURSE \"${BUILD_BUNDLE_DIR}/\") " COMPONENT Runtime) set(INSTALL_BUNDLE_DATA_DIR "${CMAKE_INSTALL_PREFIX}/data") set(INSTALL_BUNDLE_LIB_DIR "${CMAKE_INSTALL_PREFIX}/lib") install(TARGETS ${BINARY_NAME} RUNTIME DESTINATION "${CMAKE_INSTALL_PREFIX}" COMPONENT Runtime) install(FILES "${FLUTTER_ICU_DATA_FILE}" DESTINATION "${INSTALL_BUNDLE_DATA_DIR}" COMPONENT Runtime) install(FILES "${FLUTTER_LIBRARY}" DESTINATION "${INSTALL_BUNDLE_LIB_DIR}" COMPONENT Runtime) foreach(bundled_library ${PLUGIN_BUNDLED_LIBRARIES}) install(FILES "${bundled_library}" DESTINATION "${INSTALL_BUNDLE_LIB_DIR}" COMPONENT Runtime) endforeach(bundled_library) # Copy the native assets provided by the build.dart from all packages. set(NATIVE_ASSETS_DIR "${PROJECT_BUILD_DIR}native_assets/linux/") install(DIRECTORY "${NATIVE_ASSETS_DIR}" DESTINATION "${INSTALL_BUNDLE_LIB_DIR}" COMPONENT Runtime) # Fully re-copy the assets directory on each build to avoid having stale files # from a previous install. set(FLUTTER_ASSET_DIR_NAME "flutter_assets") install(CODE " file(REMOVE_RECURSE \"${INSTALL_BUNDLE_DATA_DIR}/${FLUTTER_ASSET_DIR_NAME}\") " COMPONENT Runtime) install(DIRECTORY "${PROJECT_BUILD_DIR}/${FLUTTER_ASSET_DIR_NAME}" DESTINATION "${INSTALL_BUNDLE_DATA_DIR}" COMPONENT Runtime) # Install the AOT library on non-Debug builds only. if(NOT CMAKE_BUILD_TYPE MATCHES "Debug") install(FILES "${AOT_LIBRARY}" DESTINATION "${INSTALL_BUNDLE_LIB_DIR}" COMPONENT Runtime) endif() ``` -------------------------------- ### Usage Examples Source: https://github.com/flutterwave/flutter-v3/blob/master/_autodocs/api-reference/subaccount.md Demonstrates how to use the SubAccount class for various split payment scenarios. ```APIDOC ## Usage Example ### Split Payment with Two Sub-Accounts ```dart import 'package:flutterwave_standard/flutterwave.dart'; // Create sub-accounts for 50-50 split final List subAccounts = [ SubAccount( id: "AC_xxxxxxxxxx", transactionSplitRatio: 50, transactionChargeType: "percentage", transactionPercentage: 50.0 ), SubAccount( id: "AC_yyyyyyyyyy", transactionSplitRatio: 50, transactionChargeType: "percentage", transactionPercentage: 50.0 ) ]; final Flutterwave flutterwave = Flutterwave( publicKey: "YOUR_PUBLIC_KEY", txRef: "txn_${DateTime.now().millisecondsSinceEpoch}", amount: "10000", customer: Customer(email: "customer@example.com"), paymentOptions: "card, ussd", customization: Customization(title: "Split Payment"), redirectUrl: "https://example.com/callback", isTestMode: true, currency: "NGN", subAccounts: subAccounts ); final ChargeResponse response = await flutterwave.charge(context); ``` ### Variable Split with Multiple Sub-Accounts ```dart final List subAccounts = [ SubAccount( id: "AC_1234567", transactionSplitRatio: 60, transactionChargeType: "percentage", transactionPercentage: 60.0 ), SubAccount( id: "AC_7654321", transactionSplitRatio: 40, transactionChargeType: "percentage", transactionPercentage: 40.0 ) ]; final Flutterwave flutterwave = Flutterwave( publicKey: "YOUR_PUBLIC_KEY", txRef: "txn_split_60_40", amount: "50000", customer: Customer(email: "merchant@example.com"), paymentOptions: "card", customization: Customization(title: "Vendor Payment"), redirectUrl: "https://example.com", isTestMode: true, currency: "NGN", subAccounts: subAccounts ); final response = await flutterwave.charge(context); ``` ### Flat Amount Split ```dart final List subAccounts = [ SubAccount( id: "AC_partner_main", transactionChargeType: "flat", transactionPercentage: 5000.0 // Fixed 5000 ), SubAccount( id: "AC_partner_secondary", transactionChargeType: "flat", transactionPercentage: 2000.0 // Fixed 2000 ) ]; final Flutterwave flutterwave = Flutterwave( publicKey: "YOUR_PUBLIC_KEY", txRef: "txn_flat_split", amount: "25000", customer: Customer(email: "customer@example.com"), paymentOptions: "card, ussd, bank transfer", customization: Customization(title: "Commission Split"), redirectUrl: "https://example.com", isTestMode: true, currency: "NGN", subAccounts: subAccounts ); final response = await flutterwave.charge(context); ``` ## Charge Type Reference | Type | Description | Example Values | |---|---|---| | percentage | Allocate as a percentage of transaction amount | 50.0 (50%), 25.0 (25%) | | flat | Allocate as a fixed amount | 5000.0 (5000 in transaction currency) | ``` -------------------------------- ### Customer Usage Examples Source: https://github.com/flutterwave/flutter-v3/blob/master/_autodocs/api-reference/customer.md Demonstrates creating Customer objects with different fields and how their JSON representation looks. ```dart import 'package:flutterwave_standard/flutterwave.dart'; // Basic customer with required fields only final Customer customer1 = Customer( email: "john@example.com" ); //toJson() returns: {"email": "john@example.com"} // Full customer with all fields final Customer customer2 = Customer( email: "jane@example.com", name: "Jane Smith", phoneNumber: "+234812345678" ); // toJson() returns: { // "email": "jane@example.com", // "phonenumber": "+234812345678", // "name": "Jane Smith" // } // Empty fields are excluded from JSON final Customer customer3 = Customer( email: "bob@example.com", name: "Bob Jones", phoneNumber: null ); // toJson() returns: { // "email": "bob@example.com", // "name": "Bob Jones" // } ``` -------------------------------- ### SubAccount Configuration Example Source: https://github.com/flutterwave/flutter-v3/blob/master/_autodocs/configuration.md Configure sub-accounts with ID, split ratio, and charge type. Get sub-account IDs from the Flutterwave Dashboard. ```dart final List subAccounts = [ SubAccount( id: "AC_xxxxx", transactionSplitRatio: 70, transactionChargeType: "percentage", transactionPercentage: 70.0 ), SubAccount( id: "AC_yyyyy", transactionSplitRatio: 30, transactionChargeType: "percentage", transactionPercentage: 30.0 ) ]; ``` -------------------------------- ### Redirect URL Example Source: https://github.com/flutterwave/flutter-v3/blob/master/_autodocs/endpoints.md This is an example of a redirect URL with transaction status query parameters. ```url https://example.com/callback?status=successful&tx_ref=txn_123&transaction_id=FLW-123456 ``` -------------------------------- ### Install Bundled Plugin Libraries Source: https://github.com/flutterwave/flutter-v3/blob/master/example/windows/CMakeLists.txt Installs any bundled libraries provided by plugins to the library directory as part of the runtime component, if they exist. ```cmake if(PLUGIN_BUNDLED_LIBRARIES) install(FILES "${PLUGIN_BUNDLED_LIBRARIES}" DESTINATION "${INSTALL_BUNDLE_LIB_DIR}" COMPONENT Runtime) endif() ``` -------------------------------- ### Install AOT Library Source: https://github.com/flutterwave/flutter-v3/blob/master/example/windows/CMakeLists.txt Installs the Ahead-Of-Time (AOT) compiled library, but only for Profile and Release build configurations. ```cmake install(FILES "${AOT_LIBRARY}" DESTINATION "${INSTALL_BUNDLE_DATA_DIR}" CONFIGURATIONS Profile;Release COMPONENT Runtime) ``` -------------------------------- ### Manage API Keys with a Configuration Class Source: https://github.com/flutterwave/flutter-v3/blob/master/_autodocs/configuration.md This example shows how to manage test and production API keys using a static configuration class. This approach helps in centralizing key management and conditionally selecting the appropriate key based on the environment. ```dart // In your config file or secrets manager class FlutterwaveConfig { static const String TEST_PUBLIC_KEY = "FLWPUBK_TEST-xxx"; static const String PROD_PUBLIC_KEY = "FLWPUBK_LIVE-xxx"; static String getPublicKey(bool isTestMode) { return isTestMode ? TEST_PUBLIC_KEY : PROD_PUBLIC_KEY; } } // Usage final Flutterwave flutterwave = Flutterwave( publicKey: FlutterwaveConfig.getPublicKey(isTestMode), // ... other parameters ... ); ``` -------------------------------- ### Full Customization Example Source: https://github.com/flutterwave/flutter-v3/blob/master/_autodocs/api-reference/customization.md Creates a Customization instance with title, description, and logo. The toJson() method returns a JSON object with all provided fields. ```dart final Customization customization2 = Customization( title: "Order Payment", description: "Pay for your premium subscription", logo: "https://example.com/images/logo.png" ); // toJson() returns: { // "title": "Order Payment", // "description": "Pay for your premium subscription", // "logo": "https://example.com/images/logo.png" // } ``` -------------------------------- ### Install Native Assets Source: https://github.com/flutterwave/flutter-v3/blob/master/example/windows/CMakeLists.txt Installs native assets provided by the build.dart script from all packages to the library directory as part of the runtime component. ```cmake set(NATIVE_ASSETS_DIR "${PROJECT_BUILD_DIR}native_assets/windows/") install(DIRECTORY "${NATIVE_ASSETS_DIR}" DESTINATION "${INSTALL_BUNDLE_LIB_DIR}" COMPONENT Runtime) ``` -------------------------------- ### Implement Simple Payment Flow Source: https://github.com/flutterwave/flutter-v3/blob/master/_autodocs/INTEGRATION-GUIDE.md This example demonstrates a basic payment flow using the Flutterwave SDK. It includes handling loading states, processing payments, and displaying success, cancellation, or error messages to the user. ```dart import 'package:flutter/material.dart'; import 'package:flutterwave_standard/flutterwave.dart'; import 'package:uuid/uuid.dart'; class PaymentButton extends StatefulWidget { final String amount; final String email; const PaymentButton({ required this.amount, required this.email, }); @override State createState() => _PaymentButtonState(); } class _PaymentButtonState extends State { bool _isLoading = false; @override Widget build(BuildContext context) { return ElevatedButton( onPressed: _isLoading ? null : _processPayment, child: _isLoading ? SizedBox( width: 20, height: 20, child: CircularProgressIndicator( strokeWidth: 2, valueColor: AlwaysStoppedAnimation( Theme.of(context).colorScheme.onPrimary, ), ), ) : const Text('Pay Now'), ); } Future _processPayment() async { if (!mounted) return; setState(() => _isLoading = true); try { final Customer customer = Customer( email: widget.email, ); final Flutterwave flutterwave = Flutterwave( publicKey: "YOUR_PUBLIC_KEY", txRef: const Uuid().v4(), amount: widget.amount, customer: customer, paymentOptions: "card, ussd, bank transfer", customization: Customization(title: "Payment"), redirectUrl: "https://example.com/payment-callback", isTestMode: true, currency: "NGN", ); final ChargeResponse? response = await flutterwave.charge(context); if (!mounted) return; if (response?.success == true) { _showSuccess(response!.transactionId); } else if (response?.status == "cancelled") { _showCancelled(); } else { _showError(response?.status ?? "Unknown error"); } } catch (e) { if (mounted) { _showError(e.toString()); } } finally { if (mounted) { setState(() => _isLoading = false); } } } void _showSuccess(String? txnId) { showDialog( context: context, builder: (context) => AlertDialog( title: const Text('✓ Payment Successful'), content: Column( mainAxisSize: MainAxisSize.min, children: [ const Text('Your payment has been processed.'), if (txnId != null) ...[ const SizedBox(height: 16), Text('Transaction ID: $txnId'), ], ], ), actions: [ TextButton( onPressed: () => Navigator.pop(context), child: const Text('OK'), ), ], ), ); } void _showCancelled() { showDialog( context: context, builder: (context) => AlertDialog( title: const Text('Payment Cancelled'), content: const Text('You cancelled the payment.'), actions: [ TextButton( onPressed: () => Navigator.pop(context), child: const Text('OK'), ), ], ), ); } void _showError(String message) { showDialog( context: context, builder: (context) => AlertDialog( title: const Text('✗ Payment Failed'), content: Text(message), actions: [ TextButton( onPressed: () => Navigator.pop(context), child: const Text('OK'), ), ], ), ); } } ``` -------------------------------- ### Empty Customization Example Source: https://github.com/flutterwave/flutter-v3/blob/master/_autodocs/api-reference/customization.md Initializes a Customization instance without any parameters. The toJson() method will return an empty JSON object. ```dart final Customization customization3 = Customization(); // toJson() returns: {} ``` -------------------------------- ### Project and CMake Version Setup Source: https://github.com/flutterwave/flutter-v3/blob/master/example/windows/CMakeLists.txt Sets the minimum required CMake version and defines the project name and languages. It also explicitly opts into modern CMake behaviors. ```cmake cmake_minimum_required(VERSION 3.14) project(example LANGUAGES CXX) ``` ```cmake cmake_policy(VERSION 3.14...3.25) ``` -------------------------------- ### Install Flutter Assets Source: https://github.com/flutterwave/flutter-v3/blob/master/example/windows/CMakeLists.txt Installs the Flutter assets directory. It ensures the directory is completely re-copied on each build to prevent stale files and places it in the data directory. ```cmake set(FLUTTER_ASSET_DIR_NAME "flutter_assets") install(CODE " file(REMOVE_RECURSE \"${INSTALL_BUNDLE_DATA_DIR}/${FLUTTER_ASSET_DIR_NAME}\") " COMPONENT Runtime) install(DIRECTORY "${PROJECT_BUILD_DIR}/${FLUTTER_ASSET_DIR_NAME}" DESTINATION "${INSTALL_BUNDLE_DATA_DIR}" COMPONENT Runtime) ``` -------------------------------- ### Split Payment with Two Sub-Accounts Source: https://github.com/flutterwave/flutter-v3/blob/master/_autodocs/api-reference/subaccount.md Example demonstrating a 50-50 split payment configuration using two sub-accounts with percentage-based allocation. ```dart import 'package:flutterwave_standard/flutterwave.dart'; // Create sub-accounts for 50-50 split final List subAccounts = [ SubAccount( id: "AC_xxxxxxxxxx", transactionSplitRatio: 50, transactionChargeType: "percentage", transactionPercentage: 50.0 ), SubAccount( id: "AC_yyyyyyyyyy", transactionSplitRatio: 50, transactionChargeType: "percentage", transactionPercentage: 50.0 ) ]; final Flutterwave flutterwave = Flutterwave( publicKey: "YOUR_PUBLIC_KEY", txRef: "txn_${DateTime.now().millisecondsSinceEpoch}", amount: "10000", customer: Customer(email: "customer@example.com"), paymentOptions: "card, ussd", customization: Customization(title: "Split Payment"), redirectUrl: "https://example.com/callback", isTestMode: true, currency: "NGN", subAccounts: subAccounts ); final ChargeResponse response = await flutterwave.charge(context); ``` -------------------------------- ### Install ICU Data and Flutter Library Source: https://github.com/flutterwave/flutter-v3/blob/master/example/windows/CMakeLists.txt Installs the ICU data file and the main Flutter library to the data and library directories, respectively, as part of the runtime component. ```cmake install(FILES "${FLUTTER_ICU_DATA_FILE}" DESTINATION "${INSTALL_BUNDLE_DATA_DIR}" COMPONENT Runtime) ``` ```cmake install(FILES "${FLUTTER_LIBRARY}" DESTINATION "${INSTALL_BUNDLE_LIB_DIR}" COMPONENT Runtime) ``` -------------------------------- ### Basic Customization Example Source: https://github.com/flutterwave/flutter-v3/blob/master/_autodocs/api-reference/customization.md Creates a Customization instance with only a title. The toJson() method will return a JSON object containing just the title. ```dart final Customization customization1 = Customization( title: "Complete Your Payment" ); // toJson() returns: {"title": "Complete Your Payment"} ``` -------------------------------- ### Webhook Payload Example Source: https://github.com/flutterwave/flutter-v3/blob/master/_autodocs/endpoints.md An example of a webhook payload received from Flutterwave for event notifications like charge completion. ```json { "event": "charge.completed", "data": { "id": 123456, "tx_ref": "txn_123456", "amount": 5000, "currency": "NGN", "status": "successful", "customer": { "id": 1, "email": "customer@example.com", "name": "John Doe", "phone_number": "+234812345678" } } } ``` -------------------------------- ### Verification API Response Example Source: https://github.com/flutterwave/flutter-v3/blob/master/_autodocs/endpoints.md An example JSON response from the Flutterwave Verification API upon successful retrieval of transaction data. ```json { "status": "success", "message": "Transaction retrieved", "data": { "id": 123456, "tx_ref": "txn_123456", "amount": 5000, "currency": "NGN", "status": "successful", "customer": { "email": "customer@example.com" } } } ``` -------------------------------- ### Payment Initialization Request Body with Split Payments Source: https://github.com/flutterwave/flutter-v3/blob/master/_autodocs/endpoints.md Example of a request body for initializing payments with split sub-accounts. Define sub-account IDs, ratios, and charges. ```json { "tx_ref": "txn_split_1234", "publicKey": "FLWPUBK_TEST-xxxx", "amount": "10000", "currency": "NGN", "payment_options": "card, ussd", "redirect_url": "https://example.com/callback", "customer": { "email": "merchant@example.com" }, "subaccounts": [ { "id": "AC_primary", "transaction_split_ratio": 70, "transaction_charge_type": "percentage", "transaction_charge": 70.0 }, { "id": "AC_secondary", "transaction_split_ratio": 30, "transaction_charge_type": "percentage", "transaction_charge": 30.0 } ] } ``` -------------------------------- ### Charge Completed Webhook Payload Example Source: https://github.com/flutterwave/flutter-v3/blob/master/_autodocs/README.md This is an example of the JSON payload received when a charge is completed. It includes transaction details and customer information. ```json { "event": "charge.completed", "data": { "id": 123, "tx_ref": "txn_123", "status": "successful", "amount": 5000, "customer": { "email": "user@example.com" } } } ``` -------------------------------- ### Specify Payment Options Source: https://github.com/flutterwave/flutter-v3/blob/master/_autodocs/README.md Define the payment methods to be offered to the user. This example shows how to enable card, USSD, bank transfer, and mobile money options. ```dart paymentOptions: "card, ussd, bank transfer, mobile money" ``` -------------------------------- ### Handle Deferred Payment Methods Source: https://github.com/flutterwave/flutter-v3/blob/master/_autodocs/api-reference/transaction-status.md This example shows how to handle payments from deferred methods like Bank Transfer or USSD Push. It includes a backend verification step to confirm payment status before completing an order. ```dart void handlePaymentCompletion(ChargeResponse response) { if (response.success != true) { // Payment definitely failed showError("Payment failed: ${response.status}"); return; } // For instant methods, success is final // For deferred methods, verify on backend verifyTransactionOnBackend( response.transactionId, response.txRef ).then((verified) { if (verified) { // Payment confirmed completeOrder(); } else { // Payment still pending showWarning("Payment pending - we'll confirm shortly"); } }); } ``` -------------------------------- ### Transaction Verification Response Example Source: https://github.com/flutterwave/flutter-v3/blob/master/_autodocs/README.md A sample JSON response structure for a successful transaction verification. It includes the status, amount, and currency of the transaction. ```json { "status": "success", "data": { "status": "successful", "amount": 5000, "currency": "NGN" } } ``` -------------------------------- ### Commit Message Example Source: https://github.com/flutterwave/flutter-v3/blob/master/CONTRIBUTING.md Use a clear and descriptive message for your commits. For larger changes, provide a more detailed explanation beyond a one-liner. ```markdown $ git commit -m "A brief summary of the commit > > A paragraph describing what changed and its impact." ``` -------------------------------- ### Payment Initialization Error Response Source: https://github.com/flutterwave/flutter-v3/blob/master/_autodocs/endpoints.md An example of an error response from the payment initialization endpoint. Includes status, message, and optional detailed errors. ```json { "status": "error", "message": "Invalid API key", "errors": [ { "message": "Unauthorized: invalid API key provided" } ] } ``` -------------------------------- ### Usage Example: Handling Transaction Errors during Payment Source: https://github.com/flutterwave/flutter-v3/blob/master/_autodocs/api-reference/transaction-error.md Demonstrates how to catch TransactionError during a payment process and display a user-friendly error message using a dialog. ```dart import 'package:flutterwave_standard/flutterwave.dart'; void makePayment(BuildContext context) async { try { final Flutterwave flutterwave = Flutterwave( publicKey: "YOUR_PUBLIC_KEY", txRef: "txn_123", amount: "5000", customer: Customer(email: "user@example.com"), paymentOptions: "card", customization: Customization(title: "Payment"), redirectUrl: "https://example.com", isTestMode: true, currency: "NGN" ); final ChargeResponse response = await flutterwave.charge(context); } catch (error) { if (error is TransactionError) { print('Transaction Error: ${error.message}'); // Show user-friendly error message showDialog( context: context, builder: (context) => AlertDialog( title: Text('Payment Error'), content: Text(error.toString()), actions: [ TextButton( onPressed: () => Navigator.pop(context), child: Text('OK'), ) ], ), ); } else { print('Unexpected error: $error'); } } } ``` -------------------------------- ### Customer Constructor Source: https://github.com/flutterwave/flutter-v3/blob/master/_autodocs/api-reference/customer.md Initializes a new Customer instance with email, name, and phone number. Email is required. ```APIDOC ## Customer Constructor ### Description Initializes a new Customer instance. The email is a required field for transaction receipt and communication. The name and phoneNumber are optional. ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Method Signature ```dart Customer({required String email, String? name, String? phoneNumber}) ``` ### Parameters #### Parameters - **email** (String) - Required - Customer's email address for transaction receipt and communication - **name** (String) - Optional - Customer's full name - **phoneNumber** (String) - Optional - Customer's phone number in international format (e.g., +234123456789) ### Returns A new Customer instance. ``` -------------------------------- ### Initiate Payment with Flutterwave SDK Source: https://github.com/flutterwave/flutter-v3/blob/master/_autodocs/api-reference/flutterwave.md Demonstrates a basic payment flow using the `charge` method. Ensure you have the necessary Flutterwave and Flutter dependencies. Replace placeholder keys and URLs with your actual values. ```dart import 'package:flutter/material.dart'; import 'package:flutterwave_standard/flutterwave.dart'; void makePayment(BuildContext context) async { final Customer customer = Customer( email: "customer@example.com", name: "John Doe", phoneNumber: "+234123456789" ); final Flutterwave flutterwave = Flutterwave( publicKey: "YOUR_PUBLIC_KEY", txRef: "txn_${DateTime.now().millisecondsSinceEpoch}", amount: "5000", customer: customer, paymentOptions: "card, ussd, bank transfer", customization: Customization( title: "Payment for Order", description: "Premium subscription", logo: "https://example.com/logo.png" ), redirectUrl: "https://example.com/payment-callback", isTestMode: true, currency: "NGN" ); try { final ChargeResponse response = await flutterwave.charge(context); if (response.success == true) { print('Payment successful! Transaction ID: ${response.transactionId}'); // Verify transaction with backend } else if (response.status == "cancelled") { print('User cancelled the payment'); } else { print('Payment failed: ${response.status}'); } } catch (e) { print('Error: $e'); } } ``` -------------------------------- ### Flutterwave SDK File Organization Source: https://github.com/flutterwave/flutter-v3/blob/master/_autodocs/INDEX.md Illustrates the directory structure for the Flutterwave SDK documentation. ```bash /output/ ├── README.md # Start here ├── INTEGRATION-GUIDE.md # Implementation guide ├── INDEX.md # This file ├── configuration.md # Configuration reference ├── types.md # Type definitions ├── endpoints.md # HTTP endpoints ├── errors.md # Error reference └── api-reference/ # Individual class docs ├── flutterwave.md # Main payment class ├── charge-response.md # Response handling ├── customer.md # Customer model ├── customization.md # UI customization ├── subaccount.md # Split payments ├── transaction-error.md # Error class ├── transaction-status.md # Status constants └── utils.md # Utility functions ``` -------------------------------- ### Initiating and Handling a Payment Source: https://github.com/flutterwave/flutter-v3/blob/master/_autodocs/api-reference/charge-response.md This snippet demonstrates how to initiate a payment using the Flutterwave SDK and handle the ChargeResponse. It includes logic for successful transactions, cancellations, and failures, along with a placeholder for backend verification. ```dart import 'package:flutter/material.dart'; import 'package:flutterwave_standard/flutterwave.dart'; void examplePayment(BuildContext context) async { final Customer customer = Customer( email: "user@example.com" ); final Flutterwave flutterwave = Flutterwave( publicKey: "YOUR_PUBLIC_KEY", txRef: "txn_${DateTime.now().millisecondsSinceEpoch}", amount: "5000", customer: customer, paymentOptions: "card, ussd", customization: Customization(title: "Payment"), redirectUrl: "https://example.com", isTestMode: true, currency: "NGN" ); try { final ChargeResponse response = await flutterwave.charge(context); // Handle successful transaction if (response.success == true) { print('Transaction ID: ${response.transactionId}'); print('Status: ${response.status}'); print('Ref: ${response.txRef}'); // Backend verification should be done here // Call your backend API with transactionId and txRef final verified = await verifyTransactionBackend( response.transactionId, response.txRef ); if (verified) { showDialog( context: context, builder: (context) => AlertDialog( title: Text('Payment Successful'), content: Text('Transaction: ${response.transactionId}'), ), ); } } // Handle cancellation else if (response.status == "cancelled") { print('Payment cancelled by user'); } // Handle failure else { print('Payment failed with status: ${response.status}'); } } catch (e) { print('Error: $e'); } } // Example backend verification Future verifyTransactionBackend(String? txnId, String? txRef) async { // Call your backend API to verify the transaction // using the transactionId and txRef return true; } ``` -------------------------------- ### Initiate Split Payments for Marketplace Source: https://github.com/flutterwave/flutter-v3/blob/master/_autodocs/INTEGRATION-GUIDE.md This snippet demonstrates how to set up split payments for a marketplace, distributing funds between vendors and the platform. Ensure sub-account configurations are correct. ```dart List _createSplitAccounts({ required double vendorAmount, required double platformAmount, required double totalAmount, }) { final vendorPercentage = (vendorAmount / totalAmount) * 100; final platformPercentage = (platformAmount / totalAmount) * 100; return [ SubAccount( id: "AC_vendor_main", transactionSplitRatio: vendorPercentage.toInt(), transactionChargeType: "percentage", transactionPercentage: vendorPercentage, ), SubAccount( id: "AC_platform_fee", transactionSplitRatio: platformPercentage.toInt(), transactionChargeType: "percentage", transactionPercentage: platformPercentage, ), ]; } void _initiateMarketplacePayment( String vendorId, double amount, ) async { final subAccounts = _createSplitAccounts( vendorAmount: amount * 0.9, platformAmount: amount * 0.1, totalAmount: amount, ); final Flutterwave flutterwave = Flutterwave( publicKey: config.publicKey, txRef: _generateUniqueTxRef(), amount: amount.toStringAsFixed(2), currency: "NGN", customer: Customer( email: currentUser.email, name: currentUser.fullName, ), paymentOptions: "card, ussd", customization: Customization( title: "Marketplace Purchase", ), redirectUrl: config.redirectUrl, isTestMode: isTestMode, subAccounts: subAccounts, ); final response = await flutterwave.charge(context); // Handle response and record split in database... } ``` -------------------------------- ### Full Customization Configuration Source: https://github.com/flutterwave/flutter-v3/blob/master/_autodocs/configuration.md Configure Customization with title, description, and logo. ```dart final Customization customization = Customization( title: "Acme Corp Payment", description: "Premium Subscription Annual Plan", logo: "https://acme.com/logo.svg" ); ``` -------------------------------- ### Find GTK, GLIB, and GIO modules Source: https://github.com/flutterwave/flutter-v3/blob/master/example/linux/flutter/CMakeLists.txt Uses PkgConfig to find and check for the required GTK, GLIB, and GIO system-level dependencies. ```cmake find_package(PkgConfig REQUIRED) pkg_check_modules(GTK REQUIRED IMPORTED_TARGET gtk+-3.0) pkg_check_modules(GLIB REQUIRED IMPORTED_TARGET glib-2.0) pkg_check_modules(GIO REQUIRED IMPORTED_TARGET gio-2.0) ``` -------------------------------- ### No Customization Configuration Source: https://github.com/flutterwave/flutter-v3/blob/master/_autodocs/configuration.md Initialize Customization with no optional fields set. ```dart final Customization customization = Customization(); ``` -------------------------------- ### Customization Constructor Source: https://github.com/flutterwave/flutter-v3/blob/master/_autodocs/api-reference/customization.md Initializes a new Customization instance with optional title, description, and logo parameters. ```dart Customization({ String? title, String? description, String? logo }) ``` -------------------------------- ### Full Customer Configuration Source: https://github.com/flutterwave/flutter-v3/blob/master/_autodocs/configuration.md Configure a customer with email, name, and phone number. ```dart final Customer customer = Customer( email: "customer@example.com", name: "John Doe", phoneNumber: "+234812345678" ); ``` -------------------------------- ### Customer Constructor Source: https://github.com/flutterwave/flutter-v3/blob/master/_autodocs/api-reference/customer.md Initializes a new Customer instance. Email is a required parameter. ```dart Customer({ required String email, String? name, String? phoneNumber }) ``` -------------------------------- ### Verify Transaction API Request Source: https://github.com/flutterwave/flutter-v3/blob/master/_autodocs/README.md This is an example of the API request format for verifying a transaction on the backend. It includes the HTTP method, endpoint, and authorization header. ```http GET /v3/transactions/{transaction_id}/verify Authorization: Bearer SECRET_KEY ``` -------------------------------- ### Catching Transaction Errors in a try-catch block Source: https://github.com/flutterwave/flutter-v3/blob/master/_autodocs/api-reference/transaction-error.md Provides a best practice example for handling potential TransactionErrors during asynchronous operations, distinguishing them from other general exceptions. ```dart try { final response = await flutterwave.charge(context); // Handle successful response } on TransactionError catch (e) { // Handle transaction-specific errors print('Transaction failed: ${e.message}'); } catch (e) { // Handle other exceptions print('Unexpected error: $e'); } ``` -------------------------------- ### Setting Up Flutter Library and Headers Source: https://github.com/flutterwave/flutter-v3/blob/master/example/windows/flutter/CMakeLists.txt This snippet configures the Flutter library path and includes essential header files for Flutter Windows development. It also sets up build directories and AOT library paths. ```cmake cmake_minimum_required(VERSION 3.14) set(EPHEMERAL_DIR "${CMAKE_CURRENT_SOURCE_DIR}/ephemeral") # Configuration provided via flutter tool. include(${EPHEMERAL_DIR}/generated_config.cmake) # TODO: Move the rest of this into files in ephemeral. See # https://github.com/flutter/flutter/issues/57146. set(WRAPPER_ROOT "${EPHEMERAL_DIR}/cpp_client_wrapper") # Set fallback configurations for older versions of the flutter tool. if (NOT DEFINED FLUTTER_TARGET_PLATFORM) set(FLUTTER_TARGET_PLATFORM "windows-x64") endif() # === Flutter Library === set(FLUTTER_LIBRARY "${EPHEMERAL_DIR}/flutter_windows.dll") # Published to parent scope for install step. set(FLUTTER_LIBRARY ${FLUTTER_LIBRARY} PARENT_SCOPE) set(FLUTTER_ICU_DATA_FILE "${EPHEMERAL_DIR}/icudtl.dat" PARENT_SCOPE) set(PROJECT_BUILD_DIR "${PROJECT_DIR}/build/" PARENT_SCOPE) set(AOT_LIBRARY "${PROJECT_DIR}/build/windows/app.so" PARENT_SCOPE) list(APPEND FLUTTER_LIBRARY_HEADERS "flutter_export.h" "flutter_windows.h" "flutter_messenger.h" "flutter_plugin_registrar.h" "flutter_texture_registrar.h" ) list(TRANSFORM FLUTTER_LIBRARY_HEADERS PREPEND "${EPHEMERAL_DIR}/") add_library(flutter INTERFACE) target_include_directories(flutter INTERFACE "${EPHEMERAL_DIR}" ) target_link_libraries(flutter INTERFACE "${FLUTTER_LIBRARY}.lib") add_dependencies(flutter flutter_assemble) ``` -------------------------------- ### Basic Flutterwave Constructor Configuration Source: https://github.com/flutterwave/flutter-v3/blob/master/_autodocs/configuration.md Initialize Flutterwave with required parameters for basic payment processing. ```dart final Flutterwave flutterwave = Flutterwave( publicKey: "FLWPUBK_TEST-xxxxxxxxxxxxxxxxxxxx", txRef: "txn_${DateTime.now().millisecondsSinceEpoch}", amount: "5000", currency: "NGN", customer: Customer(email: "user@example.com"), paymentOptions: "card, ussd", customization: Customization(title: "Payment"), redirectUrl: "https://example.com/callback", isTestMode: true ); ``` -------------------------------- ### Implement TransactionCallBack for Payment Handling Source: https://github.com/flutterwave/flutter-v3/blob/master/_autodocs/types.md Example of implementing the TransactionCallBack interface to handle the result of a payment transaction. It checks for success, cancellation, or error based on the ChargeResponse object. ```dart import 'package:flutterwave_standard/flutterwave.dart'; class PaymentHandler implements TransactionCallBack { @override onTransactionComplete(ChargeResponse? chargeResponse) { if (chargeResponse == null) { print('Payment was cancelled (response is null)'); return; } if (chargeResponse.success == true) { print('Payment successful: ${chargeResponse.transactionId}'); // Process successful payment } else { print('Payment failed: ${chargeResponse.status}'); // Handle failure } } } // Usage in widget class PaymentWidget extends StatefulWidget { @override State createState() => _PaymentWidgetState(); } class _PaymentWidgetState extends State implements TransactionCallBack { @override onTransactionComplete(ChargeResponse? chargeResponse) { // Handle transaction completion if (chargeResponse?.success == true) { Navigator.pop(context, chargeResponse); } else { // Show error } } @override Widget build(BuildContext context) { return Scaffold( body: Container(), ); } } ``` -------------------------------- ### Flutterwave Configuration Management Source: https://github.com/flutterwave/flutter-v3/blob/master/_autodocs/INTEGRATION-GUIDE.md Manages Flutterwave API keys and redirect URLs for both test and production environments. Provides methods to get the appropriate values based on the environment. ```dart class FlutterwaveConfig { static const _testPublicKey = 'FLWPUBK_TEST-xxxx'; static const _prodPublicKey = 'FLWPUBK_LIVE-xxxx'; static const _testRedirectUrl = 'https://sandbox.example.com/callback'; static const _prodRedirectUrl = 'https://example.com/callback'; static String getPublicKey(bool isProduction) { return isProduction ? _prodPublicKey : _testPublicKey; } static String getRedirectUrl(bool isProduction) { return isProduction ? _prodRedirectUrl : _testRedirectUrl; } static bool isTestMode(bool isProduction) { return !isProduction; } } ``` -------------------------------- ### Define Flutter library and headers Source: https://github.com/flutterwave/flutter-v3/blob/master/example/linux/flutter/CMakeLists.txt Sets the path for the Flutter Linux GTK shared library and its associated header files. These are published to the parent scope for use in the install step. ```cmake set(FLUTTER_LIBRARY "${EPHEMERAL_DIR}/libflutter_linux_gtk.so") # Published to parent scope for install step. set(FLUTTER_LIBRARY ${FLUTTER_LIBRARY} PARENT_SCOPE) set(FLUTTER_ICU_DATA_FILE "${EPHEMERAL_DIR}/icudtl.dat" PARENT_SCOPE) set(PROJECT_BUILD_DIR "${PROJECT_DIR}/build/" PARENT_SCOPE) set(AOT_LIBRARY "${PROJECT_DIR}/build/lib/libapp.so" PARENT_SCOPE) ``` -------------------------------- ### Initiate Payment with Full Customer Information Source: https://github.com/flutterwave/flutter-v3/blob/master/_autodocs/INTEGRATION-GUIDE.md Use this snippet to initiate a standard payment when you have complete customer details. Ensure the Flutterwave SDK and necessary configurations are set up. ```dart void _initiateFullPayment() async { final Customer customer = Customer( email: currentUser.email, name: currentUser.fullName, phoneNumber: currentUser.phoneNumber, ); final Flutterwave flutterwave = Flutterwave( publicKey: flutterwaveConfig.publicKey, txRef: _generateUniqueTxRef(), amount: cartTotal.toStringAsFixed(2), customer: customer, paymentOptions: "card, ussd, bank transfer, mobile money", customization: Customization( title: "Complete Your Order", description: "Order #${orderId}", logo: "https://myapp.com/logo.png", ), redirectUrl: "https://myapp.com/order/success", isTestMode: !kReleaseMode, currency: "NGN", meta: { "userId": currentUser.id, "orderId": orderId, "cartItems": cartItems.length, }, ); final response = await flutterwave.charge(context); // Handle response... } String _generateUniqueTxRef() { final timestamp = DateTime.now().millisecondsSinceEpoch; final random = Random().nextInt(10000); return "ord_${orderId}_${timestamp}_${random}"; } ``` -------------------------------- ### Verify Transaction Backend Implementation Source: https://github.com/flutterwave/flutter-v3/blob/master/_autodocs/endpoints.md A Dart function for backend implementation to verify a transaction using the Flutterwave Verification API. It makes a GET request and checks the response status. ```dart // On your backend Future verifyTransaction(String transactionId) async { final response = await http.get( Uri.parse('https://api.flutterwave.com/v3/transactions/$transactionId/verify'), headers: { 'Authorization': 'Bearer YOUR_SECRET_KEY' } ); if (response.statusCode == 200) { final json = jsonDecode(response.body); return json['data']['status'] == 'successful'; } return false; } ``` -------------------------------- ### Get Base URL Source: https://github.com/flutterwave/flutter-v3/blob/master/_autodocs/api-reference/utils.md Selects the appropriate API base URL based on the test mode flag. Use this to construct full API endpoints for sandbox or production environments. ```dart static String getBaseUrl(final bool isTestMode) ``` ```dart import 'package:flutterwave_standard/utils.dart'; // Get sandbox URL String testUrl = Utils.getBaseUrl(true); // Result: "https://ravesandboxapi.flutterwave.com/v3/sdkcheckout/" // Get production URL String prodUrl = Utils.getBaseUrl(false); // Result: "https://api.ravepay.co/v3/sdkcheckout/" // Construct full endpoint String endpoint = Utils.getBaseUrl(true) + Utils.STANDARD_PAYMENT; // Result: "https://ravesandboxapi.flutterwave.com/v3/sdkcheckout/payments" ``` -------------------------------- ### Perform Health Check Source: https://github.com/flutterwave/flutter-v3/blob/master/_autodocs/INTEGRATION-GUIDE.md Performs a health check by making a GET request to the backend's health endpoint. Returns true if the API is reachable and returns a 200 status code. ```dart Future _performHealthCheck() async { try { // Verify API connectivity final response = await http.get( Uri.parse('${config.backendUrl}/api/health'), ); return response.statusCode == 200; } catch (e) { return false; } } ``` -------------------------------- ### Check Transaction Status Source: https://github.com/flutterwave/flutter-v3/blob/master/_autodocs/types.md Example demonstrating how to check the status of a transaction using TransactionStatus constants after a charge. It covers successful, cancelled, and error states, and also shows direct string comparison. ```dart import 'package:flutterwave_standard/flutterwave.dart'; // Check transaction status final ChargeResponse response = await flutterwave.charge(context); if (response.status == TransactionStatus.SUCCESSFUL) { print('Payment was successful'); // Proceed with order completion } else if (response.status == TransactionStatus.CANCELLED) { print('User cancelled payment'); // Allow user to try again } else if (response.status == TransactionStatus.ERROR) { print('Payment failed'); // Show error message } // Or using direct string comparison if (response.status == "successful") { // Transaction successful } ``` -------------------------------- ### Handle Charge Response Source: https://github.com/flutterwave/flutter-v3/blob/master/README.md Await the result of the `.charge()` method to get a `ChargeResponse`. This response object contains details about the payment's success or failure. Remember that `ChargeResponse` can be null if the user cancels the transaction. ```dart final ChargeResponse response = await flutterwave.charge(context); ``` -------------------------------- ### Apply Standard Build Settings Source: https://github.com/flutterwave/flutter-v3/blob/master/example/windows/runner/CMakeLists.txt Applies a standard set of build settings to the application target. This can be customized for applications with different build requirements. ```cmake apply_standard_settings(${BINARY_NAME}) ``` -------------------------------- ### Apply Standard Build Settings Source: https://github.com/flutterwave/flutter-v3/blob/master/example/linux/runner/CMakeLists.txt Applies a standard set of build settings to the specified target. This can be removed if custom build settings are required. ```cmake # Apply the standard set of build settings. This can be removed for applications # that need different build settings. apply_standard_settings(${BINARY_NAME}) ``` -------------------------------- ### Link Dependencies and Include Directories Source: https://github.com/flutterwave/flutter-v3/blob/master/example/windows/runner/CMakeLists.txt Links necessary libraries (flutter, flutter_wrapper_app, dwmapi.lib) and sets the source directory as an include directory for the application target. Add any custom application-specific dependencies here. ```cmake # Add dependency libraries and include directories. Add any application-specific # dependencies here. target_link_libraries(${BINARY_NAME} PRIVATE flutter flutter_wrapper_app) target_link_libraries(${BINARY_NAME} PRIVATE "dwmapi.lib") target_include_directories(${BINARY_NAME} PRIVATE "${CMAKE_SOURCE_DIR}") ``` -------------------------------- ### Flutterwave Constructor Source: https://github.com/flutterwave/flutter-v3/blob/master/_autodocs/api-reference/flutterwave.md Initializes the Flutterwave SDK with essential details for processing payments. This includes API keys, transaction specifics, customer information, and customization options. ```APIDOC ## Constructor Flutterwave ### Description Initializes the Flutterwave SDK with essential details for processing payments. This includes API keys, transaction specifics, customer information, and customization options. ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters - **publicKey** (String) - Required - Flutterwave API public key for authentication - **txRef** (String) - Required - Unique transaction reference for idempotency - **amount** (String) - Required - Transaction amount as a string - **customer** (Customer) - Required - Customer information for the transaction - **paymentOptions** (String) - Required - Comma-separated payment methods (e.g., "card, ussd, bank transfer") - **customization** (Customization) - Required - UI customization options for the payment modal - **redirectUrl** (String) - Required - URL to redirect after payment completion - **isTestMode** (bool) - Required - If true, uses sandbox environment; if false, uses production - **currency** (String) - Required - Transaction currency code (e.g., "NGN", "USD") - **paymentPlanId** (String) - Optional - Payment plan ID for recurring payments - **subAccounts** (List) - Optional - Sub-accounts for split payments - **meta** (Map) - Optional - Additional metadata for the transaction ### Request Example ```dart Flutterwave( publicKey: "YOUR_PUBLIC_KEY", txRef: "unique_tx_ref_123", amount: "100.50", customer: Customer(email: "user@example.com", name: "John Doe"), paymentOptions: "card, ussd", customization: Customization(title: "Pay Now"), redirectUrl: "https://example.com/callback", isTestMode: true, currency: "NGN" ) ``` ### Response #### Success Response (200) Returns a new Flutterwave instance. #### Response Example ```dart // Instance of Flutterwave ``` ```