Skip to content

bajoski34/Laravel

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

59 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Flutterwave Laravel.

Packagist Downloads Packagist PHP Version Support GitHub stars Packagist License

This Flutterwave Laravel Package provides easy access to Flutterwave for Business (F4B) v3 APIs from Laravel apps. It abstracts the complexity involved in direct integration and allows you to make quick calls to the APIs.

Available features include:

  • Collections: Card, Account, Mobile money, Bank Transfers, USSD, Barter, NQR.

Table of Contents

  1. Requirements
  2. Installation
  3. Initialization
  4. Usage
  5. Testing
  6. Debugging Errors
  7. Support
  8. Contribution guidelines
  9. License
  10. Changelog

Requirements

  1. Flutterwave for business API Keys
  2. Acceptable PHP versions: >= 7.3

Installation

The vendor folder is committed into the project to allow easy installation for those who do not have composer installed. It is recommended to update the project dependencies using:

$ composer require abraham-flutterwave/laravel-payment

Ensure that you publish your config file by running:

$ php artisan vendor:publish --provider="Flutterwave\Payments\Providers\FlutterwaveServiceProvider"  

Initialization

In your .env file add the following environment variables:

FLW_PUBLIC_KEY="****YOUR**PUBLIC**KEY****" // can be gotten from the dashboard
FLW_SECRET_KEY="****YOUR**SECRET**KEY****" // can be gotten from the dashboard
FLW_ENCRYPTION_KEY="Encryption key"
FLW_ENVIRONMENT="development"

Business Settings/preferences like logo, name, payment method can be set in the config file config/flutterwave.php

'businessName' => env('FLW_BUSINESS_NAME', 'Flutterwave Store'),
'transactionPrefix' => env('FLW_TRANSACTION_PREFIX', 'LARAVEL-'),
'logo' => env('FLW_BUSINESS_LOGO', 'https://avatars.githubusercontent.com/u/39011309?v=4'),
'title' => env('FLW_PAYMENT_DESCRIPTOR', 'Flutterwave Store'),
'description' => env('FLW_CHECKOUT_DESCRIPTION', 'Flutterwave Store Description'),
'country' => env('FLW_DEFAULT_COUNTRY', 'NG'),
'currency' => env('FLW_DEFAULT_CURRENCY', Currency::NGN),
'paymentType' => [
    'card', 'account', 'banktransfer', 'mpesa', 'mobilemoneyrwanda', 'mobilemoneyzambia',
    'mobilemoneyuganda', 'ussd', 'qr', 'mobilemoneyghana', 'credit', 'barter',
    'payattitude', 'mobilemoneyfranco', 'mobilemoneytanzania', 'paga', '1voucher',
],

Usage

Render Payment Modal

There are two types of modal that can be rendered, the inline modal and the standard modal. The inline modal is rendered on your website while the standard modal is rendered on a flutterwave hosted page.

Inline Modal

use Flutterwave\Payments\Facades\Flutterwave;
use Flutterwave\Payments\Data\Currency;

$payload = [
    "tx_ref" => Flutterwave::generateTransactionReference(),
    "amount" => 100,
    "currency" => Currency::NGN,
    "customer" => [
        "email" => "[email protected]"
    ],
];

$payment_details = Flutterwave::render('inline', $payload);

return view('flutterwave::modal', compact('payment_details'));

Standard Modal

use Flutterwave\Payments\Facades\Flutterwave;
use Flutterwave\Payments\Data\Currency;

$payload = [
    "tx_ref" => Flutterwave::generateTransactionReference(),
    "amount" => 100,
    "currency" => Currency::NGN,
    "customer" => [
        "email" => "[email protected]"
    ],
];

$payment_link = Flutterwave::render('standard', $payload);

return redirect($payment_link);

These are the routes available for integrating the Flutterwave payment system. Below is a breakdown of each route and its purpose.

Checkout Route

URL: /flutterwave/payment/checkout

Method: POST

Description: This route initiates the payment checkout process. The user will be required to send a POST request with the necessary payment details such as amount, currency, and email. If additional meta data is provided, it will be included in the request.

Parameters:

  • amount (required): The payment amount.
  • currency (required): The currency code (e.g., USD, NGN).
  • email (required): The email address of the customer.
  • meta (optional): Any custom data related to the payment. Response: Returns a view (flutterwave::modal) that contains the payment details and a Flutterwave inline payment form.

Payment Callback Route

URL: /flutterwave/payment/callback

Method: GET

Description: This route handles the callback from Flutterwave after a payment attempt. It verifies the transaction status using the transaction reference (tx_ref). Based on the result, it redirects the user to appropriate pages.

Parameters:

  • tx_ref (required): The transaction reference ID returned by Flutterwave. Response:

If the transaction is successful, the user is redirected to the success page (flutterwave.successful). If the transaction is pending, it may redirect the user to a page that will poll for the transaction's final status. If the transaction has failed, the user is redirected to the failure page (flutterwave.failed). 3. Payment Success Route URL: /flutterwave/payment/success

Method: GET

Description: This route is called when a payment is successfully completed.

Response: Returns a simple message, "Payment Successful".

Payment Failed Route

URL: /flutterwave/payment/failed

Method: GET

Description: This route is called when a payment fails.

Response: Returns a simple message, "Payment Failed".

Payment Cancelled Route

URL: /flutterwave/payment/cancel

Method: GET

Description: This route is called when a payment is cancelled by the user.

Response: Returns a simple message, "Payment Cancelled".


Logging

To enable logging, simple add the following to your config file config/logging.php

'flutterwave' => [
    'driver' => 'single',
    'path' => storage_path('logs/flutterwave.log'),
    'level' => 'debug',
],

Webhook Setup

Create a Webhook url to receive payment notification on Payment events. Below is a sample of a webhook url implementation using the new package.

use Flutterwave\Payments\Facades\Flutterwave;
use Flutterwave\Payments\Data\Status;

Route::post('flutterwave/payment/webhook', function () {
    $method = request()->method();
    if ($method === 'POST') {
        //get the request body
        $body = request()->getContent();
        $webhook = Flutterwave::use('webhooks');
        $transaction = Flutterwave::use('transactions');
        //get the request signature
        $signature = request()->header($webhook::SECURE_HEADER);

        //verify the signature
        $isVerified = $webhook->verifySignature($body, $signature);

        if ($isVerified) {
            [ 'tx_ref' => $tx_ref, 'id' => $id ] = $webhook->getHook();
            [ 'status' => $status, 'data' => $transactionData ] = $transaction->verifyTransactionReference($tx_ref);

            $responseData = ['tx_ref' => $tx_ref, 'id' => $id];
            if ($status === 'success') {
                switch ($transactionData['status']) {
                    case Status::SUCCESSFUL:
                        // do something
                        //save to database
                        //send email
                        break;
                    case Status::PENDING:
                        // do something
                        //save to database
                        //send email
                        break;
                    case Status::FAILED:
                        // do something
                        //save to database
                        //send email
                        break;
                }
            }

            return response()->json(['status' => 'success', 'message' => 'Webhook verified by Flutterwave Laravel Package', 'data' => $responseData]);
        }

        return response()->json(['status' => 'error', 'message' => 'Access denied. Hash invalid'])->setStatusCode(401);
    }

    // return 404
    return abort(404);
})->name('flutterwave.webhook');

Testing

All of the SDK's tests are written with PHP's phpunit module. The tests currently test: Modals, Webhooks, Transactions,

They can be run like so:

phpunit

NOTE: If the test fails for creating a subaccount, just change the account_number account_bank and businesss_email to something different

NOTE: The test may fail for account validation - Pending OTP validation depending on whether the service is down or not


Debugging Errors

We understand that you may run into some errors while integrating our library. You can read more about our error messages here.

For authorization and validation error responses, double-check your API keys and request. If you get a server error, kindly engage the team for support.

Support

For additional assistance using this library, contact the developer experience (DX) team via email or on slack.

You can also follow us @FlutterwaveEng and let us know what you think 😊.

Contribution guidelines

Read more about our community contribution guidelines here

License

By contributing to this library, you agree that your contributions will be licensed under its MIT license.

Copyright (c) Flutterwave Inc.

Flutterwave API References

TODOs

  1. Add other Flutterwave Services - card,transfer,subaccount,payoutsubaccounts,plans and momo
  2. Console Commands - Webhooks, Make Payment, and Refunds.