PHP Library for Flutterwave v3 APIs

Related tags

Miscellaneous PHP
Overview

Flutterwave v3 PHP SDK.

Packagist Downloads Packagist PHP Version Support GitHub stars Packagist License

This Flutterwave v3 PHP Library provides easy access to Flutterwave for Business (F4B) v3 APIs from php 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.
  • Payouts and Beneficiaries.
  • Recurring payments: Tokenization and Subscriptions.
  • Split payments
  • Card issuing
  • Transactions dispute management: Refunds.
  • Transaction reporting: Collections, Payouts, Settlements, and Refunds.
  • Bill payments: Airtime, Data bundle, Cable, Power, Toll, E-bills, and Remitta.
  • Identity verification: Resolve bank account, resolve BVN information.

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: >= 5.4.0

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 flutterwavedev/flutterwave-v3

Initialization

Create a .env file and follow the format of the .env.example file Save your PUBLIC_KEY, SECRET_KEY, ENV in the .env file

PUBLIC_KEY="****YOUR**PUBLIC**KEY****" // can be gotten from the dashboard
SECRET_KEY="****YOUR**SECRET**KEY****" // can be gotten from the dashboard
ENCRYPTION_KEY="Encryption key"
ENV="development/production"

Usage

Card Charge

This is used to facilitate card transactions.

Edit the paymentForm.php and processPayment.php files to suit your purpose. Both files are well documented.

Simply redirect to the paymentForm.php file on your browser to process a payment.

In this implementation, we are expecting a form encoded POST request to this script. The request will contain the following parameters.

  • payment_method Can be card, account, both
  • description Your transaction description
  • logo Your logo url
  • title Your transaction title
  • country Your transaction country
  • currency Your transaction currency
  • email Your customer's email
  • firstname Your customer's first name
  • lastname Your customer's last name
  • phonenumber Your customer's phonenumber
  • pay_button_text The payment button text you prefer
  • ref Your transaction reference. It must be unique per transaction. By default, the Rave class generates a unique transaction reference for each transaction. Pass this parameter only if you uncommented the related section in the script below.
// Prevent direct access to this class
define("BASEPATH", 1);

include('library/rave.php');
include('library/raveEventHandlerInterface.php');


use Flutterwave\EventHandlers\EventHandlers\EventHandlers\EventHandlers\EventHandlers\Rave;


$URL = (isset($_SERVER['HTTPS']) ? 'https' : 'http') . '://'.$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'];
$getData = $_GET;
$postData = $_POST;
$publicKey = $_SERVER['PUBLIC_KEY'];
$secretKey = $_SERVER['SECRET_KEY'];
$success_url = $postData['successurl'];
$failure_url = $postData['failureurl'];
$env = $_SERVER['ENV'];

if($postData['amount']){
    $_SESSION['publicKey'] = $publicKey;
    $_SESSION['secretKey'] = $secretKey;
    $_SESSION['env'] = $env;
    $_SESSION['successurl'] = $success_url;
    $_SESSION['failureurl'] = $failure_url;
    $_SESSION['currency'] = $postData['currency'];
    $_SESSION['amount'] = $postData['amount'];
}

$prefix = 'RV'; // Change this to the name of your business or app
$overrideRef = false;

// Uncomment here to enforce the useage of your own ref else a ref will be generated for you automatically
if($postData['ref']){
    $prefix = $postData['ref'];
    $overrideRef = true;
}

$payment = new Rave($_SESSION['secretKey'], $prefix, $overrideRef);

function getURL($url,$data = array()){
    $urlArr = explode('?',$url);
    $params = array_merge($_GET, $data);
    $new_query_string = http_build_query($params).'&'.$urlArr[1];
    $newUrl = $urlArr[0].'?'.$new_query_string;
    return $newUrl;
};

In order to handle events that at occurs at different transaction stages. You define a class that implements the EventHandlerInterface

class myEventHandler implements EventHandlerInterface{
    /**
     * This is called when the Rave class is initialized
     **/
    function onInit($initializationData){
        // Save the transaction to your DB.
    }
    
    /**
     * This is called only when a transaction is successful
     **/

    function onSuccessful($transactionData) {
        /** 
        * Get the transaction from your DB using the transaction reference (txref). 
        * Check if you have previously given value for the transaction. If you have, redirect to your successpage else, continue. 
        * Comfirm that the transaction is successful
        * Confirm that the currency on your db transaction is equal to the returned currency
        * Confirm that the db transaction amount is equal to the returned amount
        * Update the db transaction record (includeing parameters that didn't exist before the transaction is completed. for audit purpose)
        * Give value for the transaction
        * Update the transaction to note that you have given value for the transaction
        * You can also redirect to your success page from here
        **/

        if ($transactionData->status == 'success'){
          if ($transactionData->currency == $_SESSION['currency'] && $transactionData->amount == $_SESSION['amount']){
              
              if ($_SESSION['publicKey']){
                    header('Location: '.getURL($_SESSION['successurl'], array('event' => 'successful')));
                    $_SESSION = array();
                    session_destroy();
                }
          } else {
              if($_SESSION['publicKey']){
                    header('Location: '.getURL($_SESSION['failureurl'], array('event' => 'suspicious')));
                    $_SESSION = array();
                    session_destroy();
                }
          }
      } else {
          $this->onFailure($transactionData);
      }
    }
    
    /**
     * This is called only when a transaction failed
     **/
    function onFailure($transactionData){
        /**
        * Get the transaction from your DB using the transaction reference (txref)
        * Update the db transaction record (includeing parameters that didn't exist before the transaction is completed. for audit purpose)
        * You can also redirect to your failure page from here
        **/

        if ($_SESSION['publicKey']) {
            header('Location: '.getURL($_SESSION['failureurl'], array('event' => 'failed')));
            $_SESSION = array();
            session_destroy();
        }
    }
    
    /**
     * This is called when a transaction is requeryed from the payment gateway
     **/
    function onRequery($transactionReference){
        // Do something, anything!
    }
    
    /**
     * This is called a transaction requery returns with an error
     **/
    function onRequeryError($requeryResponse){
        // Do something, anything!
    }
    
    /**
     * This is called when a transaction is canceled by the user
     **/
    function onCancel($transactionReference){
        // Do something, anything!
        // Note: Somethings a payment can be successful, before a user clicks the cancel button so proceed with caution
        if($_SESSION['publicKey']){
            header('Location: '.getURL($_SESSION['failureurl'], array('event' => 'canceled')));
            $_SESSION = array();
            session_destroy();
        }
    }
    
    /**
     * This is called when a transaction doesn't return with a success or a failure response. This can be a timedout transaction on the Rave server or an abandoned transaction by the customer.
     **/
    function onTimeout($transactionReference, $data){
        /**
        * Get the transaction from your DB using the transaction reference (txref)
        * Queue it for requery. Preferably using a queue system. The requery should be about 15 minutes after.
        * Ask the customer to contact your support and you should escalate this issue to the flutterwave support team. Send this as an email and as a notification on the page. just incase the page timesout or disconnects
        **/
        if($_SESSION['publicKey']){
            header('Location: '.getURL($_SESSION['failureurl'], array('event' => 'timedout')));
            $_SESSION = array();
            session_destroy();
        }
    }
}

if($postData['amount']){
    // Make payment
    $payment
    ->eventHandler(new myEventHandler)
    ->setAmount($postData['amount'])
    ->setPaymentOptions($postData['payment_options']) // value can be card, account or both
    ->setDescription($postData['description'])
    ->setLogo($postData['logo'])
    ->setTitle($postData['title'])
    ->setCountry($postData['country'])
    ->setCurrency($postData['currency'])
    ->setEmail($postData['email'])
    ->setFirstname($postData['firstname'])
    ->setLastname($postData['lastname'])
    ->setPhoneNumber($postData['phonenumber'])
    ->setPayButtonText($postData['pay_button_text'])
    ->setRedirectUrl($URL)
    // ->setMetaData(array('metaname' => 'SomeDataName', 'metavalue' => 'SomeValue')) // can be called multiple times. Uncomment this to add meta datas
    // ->setMetaData(array('metaname' => 'SomeOtherDataName', 'metavalue' => 'SomeOtherValue')) // can be called multiple times. Uncomment this to add meta datas
    ->initialize();
}else{
    if($getData['cancelled'] && $getData['tx_ref']){
        // Handle canceled payments
        $payment
        ->eventHandler(new myEventHandler)
        ->requeryTransaction($getData['tx_ref'])
        ->paymentCanceled($getData['tx_ref']);
    }elseif($getData['tx_ref']){
        // Handle completed payments
        $payment->logger->notice('Payment completed. Now requerying payment.');
        
        $payment
        ->eventHandler(new myEventHandler)
        ->requeryTransaction($getData['tx_ref']);
    }else{
        $payment->logger->warn('Stop!!! Please pass the txref parameter!');
        echo 'Stop!!! Please pass the txref parameter!';
    }
}

Account Charge

The following implementation shows how to initiate a direct bank charge. Use the Playground DIrectory to view Responses and samples of use.

require("Flutterwave-Rave-PHP-SDK/library/AccountPayment.php");
use Flutterwave\EventHandlers\EventHandlers\EventHandlers\EventHandlers\EventHandlers\AccountPayment;

//The data variable holds the payload
$data = array(
    "amount" => "3000",
    "type" => "debit_ng_account",//debit_ng_account or debit_uk_account
    "account_bank" => "044",
    "account_number" => "0690000037",
    "currency" => "NGN",//NGN or GBP
    "email" => "[email protected]",
    "phone_number" => "07067965809",
    "fullname" => "Olaobaju Abraham",
    "client_ip" => "154.123.220.1",
    "device_fingerprint" => "62wd23423rq324323qew1",
    "meta" => [
        "flightID" => "213213AS"
        ]       
    );

$payment = new AccountPayment();
$result = $payment->accountCharge($data);

if(isset($result['data'])){
  $id = $result['data']['id'];
  $verify = $payment->verifyTransaction($id);
}
print_r($result);

ACH Charge

The following implementation shows how to accept payments directly from customers in the US and South Africa. Use the Playground DIrectory to view Responses and samples of use.

require("Flutterwave-Rave-PHP-SDK/library/AchPayment.php");
use Flutterwave\EventHandlers\EventHandlers\EventHandlers\EventHandlers\EventHandlers\AchPayment;

// The data variable holds the payload
$data = array(
    "tx_ref" =>  "MC-1585230ew9v5050e8",
    "amount" => "100",
    "type" => "ach_payment",
    "currency" => "USD",
    "country" => "US",
    "email" => "[email protected]",
    "phone_number" => "0902620185",
    "fullname" => "Ekene Eze",
    "redirect_url" => "http://ekene.com/u/payment-completed",
    );

$payment = new AchPayment();

$result = $payment->achCharge($data);
if(isset($result['data'])){
  $id = $result['data']['id'];
  $verify = $payment->verifyTransaction($id);
}
print_r($result);

Direct Card Charge

The following implementation shows how to initiate a card charge. Use the Playground Directory to view an implementation Responses and samples of use.

require("Flutterwave-Rave-PHP-SDK/library/CardPayment.php");
use Flutterwave\EventHandlers\EventHandlers\EventHandlers\EventHandlers\EventHandlers\CardPayment;

//The data variable holds the payload
$data = array(
    "card_number"=> "5531886652142950",
    "cvv"=> "564",
    "expiry_month"=> "09",
    "expiry_year"=> "22",
    "currency"=> "NGN",
    "amount" => "1000",
    "fullname"=> "Ekene Eze",
    "email"=> "[email protected]",
    "phone_number"=> "0902620185",
    "fullname" => "temi desola",
    //"tx_ref"=> "MC-3243e",// should be unique for every transaction
    "redirect_url"=> "https://webhook.site/3ed41e38-2c79-4c79-b455-97398730866c",
           
    );

$payment = new CardPayment();
$res = $payment->cardCharge($data);//This call is to figure out the authmodel
$data['authorization']['mode'] = $res['meta']['authorization']['mode'];

if($res['meta']['authorization']['mode'] == 'pin'){

    //Supply authorization pin here
    $data['authorization']['pin'] = '3310';
}

if($res['meta']['authorization']['mode'] == 'avs_noauth'){
    //supply avs details here
    $data["authorization"] = array(
            "mode" => "avs_noauth",
            "city"=> "Sampleville",
            "address"=> "3310 sample street ",
            "state"=> "Simplicity",
            "country"=> "Simple",
            "zipcode"=> "000000",
        );
}

$result = $payment->cardCharge($data);//charge with new fields
// print_r($result);//this returns the an array

if($result['data']['auth_mode'] == 'otp'){
    $id = $result['data']['id'];
    $flw_ref = $result['data']['flw_ref'];
    $otp = '12345';
    $validate = $payment->validateTransaction($otp,$flw_ref);// you can print_r($validate) to see the response
    $verify = $payment->verifyTransaction($id);
}

Mobile Money Payments

The following implementation shows how to initiate a mobile money payment. Use the Playground Directory to view Responses and samples of use.

require("Flutterwave-Rave-PHP-SDK/library/MobileMoney.php");
use Flutterwave\EventHandlers\EventHandlers\EventHandlers\EventHandlers\EventHandlers\MobileMoney;

// The data variable holds the payload
$data = array(
    "order_id" => "USS_URG_89245453s2323",
    "amount" => "1500",
    "type" => "mobile_money_rwanda",// could be mobile_money_rwanda,mobile_money_uganda, mobile_money_zambia, mobile_money_ghana
    "currency" => "RWF",
    "email" => "[email protected]",
    "phone_number" => "054709929220",
    "fullname" => "John Madakin",
    "client_ip" => "154.123.220.1",
    "device_fingerprint" => "62wd23423rq324323qew1",
    "meta" => [
        "flightID" => "213213AS"
        ]       
    );


$payment = new MobileMoney();
$result = $payment->mobilemoney($data);
$id = $result['data']['id'];
$verify = $payment->verifyTransaction($id);
$print_r($result);

USSD

Collect payments via ussd

require("Flutterwave-Rave-PHP-SDK/library/Ussd.php");
use Flutterwave\EventHandlers\EventHandlers\EventHandlers\EventHandlers\EventHandlers\Ussd;
//The data variable holds the payload
$data = array(
        "tx_ref" => "MC-15852309v5050e8",
        "account_bank" => "058",
        "amount" => "1500",
        "currency" =>"NGN",
        "email" =>"[email protected]",
        "phone_number" =>"054709929220",
        "fullname" => "John Madakin",
        
      
    );

$payment = new Ussd();
$result = $payment->ussd($data);//initiates the charge

echo 'Dial '.$result['meta']['authorization']['note'].' to authorize your transaction';

//A webhook notification would be sent to you....

if(isset($result['data'])){
  $id = $result['data']['id'];
  $verify = $payment->verifyTransaction($id);
}

Mpesa

Collect payments from your customers via Mpesa.

require("Flutterwave-Rave-PHP-SDK/library/Mpesa.php");
use Flutterwave\EventHandlers\EventHandlers\EventHandlers\EventHandlers\EventHandlers\Mpesa;

$data = array(
    "amount" => "1500",
    "type" => "mpesa",
    "currency" => "KES",
    "email" => "[email protected]",
    "phone_number" => "054709929220",
    "fullname" => "Ekene Eze",
    "client_ip" => "154.123.220.1",
    "device_fingerprint" => "62wd23423rq324323qew1",
    "meta" => [
        "flightID" => "213213AS"
        ]       
    );

$payment = new Mpesa();

$result = $payment->mpesa($data);
print_r($result);
if(isset($result['data'])){
  $id = $result['data']['id'];
  $verify = $payment->verifyTransaction($id);
}

Transfer Implementation

How to make a transfer payment

require("Flutterwave-Rave-PHP-SDK/library/Transfer.php");
use Flutterwave\EventHandlers\EventHandlers\EventHandlers\EventHandlers\EventHandlers\Transfer;

// sample payload for payBill()
$data = array(
    "account_bank"=> "044",
    "account_number"=> "0690000040",
    "amount"=> 5500,
    "narration"=> "Akhlm Pstmn Trnsfr xx007",
    "currency"=> "NGN",
    "reference"=> "akhlm-pstmnpyt-rfxx007_PMCKDU_1",// read the docs about testing successful and failed transaction.
    "callback_url"=> "https://webhook.site/b3e505b0-fe02-430e-a538-22bbbce8ce0d",
    "debit_currency"=> "NGN"
);

//sample payload for bulkBill()
$bulkdata = array(
  "title"=> "Staff salary",
  "bulk_data"=> array(
      array(
          "bank_code"=> "044",
          "account_number"=> "0690000032",
          "amount"=> 45000,
          "currency"=> "NGN",
          "narration"=> "akhlm blktrnsfr",
          "reference"=> "akhlm-blktrnsfr-xx03"
      ),
      array(
          "bank_code"=> "044",
          "account_number"=> "0690000034",
          "amount"=> 5000,
          "currency"=> "NGN",
          "narration"=> "akhlm blktrnsfr",
          "reference"=> "akhlm-blktrnsfr-xy03"
      ))
);

$getdata = array(
    //"reference"=>"edf-12de5223d2f32434753432"
     "id"=>"BIL136",
     "product_id"=>"OT150"
);

$listdata = array(
  'status'=>'failed'
);

$feedata = array(
'currency'=> 'NGN', //if currency is omitted. the default currency of NGN would be used.
'amount'=> 1000
);

$payment = new Transfer();
$result = $payment->singleTransfer($data);//initiate single transfer payment
$createBulkTransfer = $payment->bulkTransfer($bulkdata);// get bulk result....
$transfers = $payment->listTransfers($listdata);//you can add a payload for the page. you can remove the array if want to get it all.
$getTransferFee = $payment->getTransferFee($feedata);
if(isset($result['data'])){
  $id = $result['data']['id'];
  $verify = $payment->verifyTransaction($id);
}

Vitual Cards

The following implementation shows how to create virtual cards on rave. Use the Playground Directory to view Responses and samples of use.

require("Flutterwave-Rave-PHP-SDK/library/VirtualCards.php");
use Flutterwave\EventHandlers\EventHandlers\EventHandlers\EventHandlers\EventHandlers\VirtualCard;

$data = array(
    "currency"=>"NGN",
    "amount"=>20000,
    "billing_name"=>"Jermaine Graham",
    "billing_address"=>"2014 Forest Hills Drive",
    "billing_city"=>"Node",
    "billing_state"=>"Javascript",
    "billing_postal_code"=>"000009",
    "billing_country"=>"NG",
    "callback_url"=>"https://webhook.site/96374895-154d-4aa0-99b5-709a0a128674"
    );

    $trns_data = array('id'=> 'a41de883-c8da-45a0-9b23-37780c88285f');
    $getCardData = array('id'=>'7a81d279-a07a-4775-a55a-5fa2c98e20ae');
    $terminate_data = array('id'=>'1cb36826-8e05-40d6-8b9e-7f7439a141cb');
    $fund_data = array('id'=>'1cb36826-8e05-40d6-8b9e-7f7439a141cb', 'amount'=>'2000', 'debit_currency'=>'NGN');
    $withdraw_data = array('id'=>'1cb36826-8e05-40d6-8b9e-7f7439a141cb', 'amount'=>'500');
    $blockCard_data = array('id' => '1cb36826-8e05-40d6-8b9e-7f7439a141cb', 'status_action'=>'block');

    $card = new VirtualCard();
    $createCard = $card->createCard($data);//initiates the charge
    $getCard = $card->getCard($getCardData);
    $getCards = $card->listCards();
    $terminate = $card->terminateCard($terminate_data);
    $fund = $card->fundCard($fund_data);
    $transactions = $card->cardTransactions($trns_data);
    $withdraw = $card->cardWithdrawal($withdraw_data);
    $block_unblock = $card->block_unblock_card($blockCard_data);
    print_r($createCard);

BVN Verification

The following implementation shows how to verify a Bank Verification Number.

require("Flutterwave-Rave-PHP-SDK/library/Bvn.php");
use Flutterwave\EventHandlers\EventHandlers\EventHandlers\EventHandlers\EventHandlers\Bvn;
//The data variable holds the payload
$bvn_number = "123456789";
$bvn = new Bvn();
$result = $bvn->verifyBVN($bvn_number);
print_r($result);

Payment Plans

The following implementation shows how to create a payment plan on the rave dashboard. Use the Playground Directory to view Responses and samples of use.

require("Flutterwave-Rave-PHP-SDK/library/PaymentPlan.php");
use Flutterwave\EventHandlers\EventHandlers\EventHandlers\EventHandlers\EventHandlers\PaymentPlan;

//sample payload for payBill()
$data = array(
    "amount"=> 2000,
    "name"=> "plan 2",
    "interval"=> "monthly",
    "duration"=> 48
);
$update = array( "id" => "5356","name" => "The Game","status" => "Active");
$getdata = array("id"=>"5116");

$payment = new PaymentPlan();
$result = $payment->createPlan($data);//create a Plan reciept
$updateResult = $payment->updatePlan($update);//update a plan....
$paymentPlans = $payment->getPlans();//list all payment plans....
$aPlan = $payment->get_a_plan($getdata);//get a payment plans....
print_r($result);

Subaccount Management

The following implementation shows how to create a subaccount on the rave dashboard Use the Playground Directory to view Responses and samples of use.

require("Flutterwave-Rave-PHP-SDK/library/Subaccount.php");
use Flutterwave\EventHandlers\EventHandlers\EventHandlers\EventHandlers\EventHandlers\Subaccount;

$data = array(
    "account_bank"=> "044",
    "account_number"=> "0690000037",
    "business_name"=> "Eternal Blue",
    "business_email"=> "[email protected]",
    "business_contact"=> "Anonymous",
    "business_contact_mobile"=> "090890382",
    "business_mobile"=> "09087930450",
    "country"=> "NG",
    "meta"=> array(
        array(
            "meta_name"=> "mem_adr",
            "meta_value"=> "0x16241F327213"
        )
    ),
    "split_type"=> "percentage",
    "split_value"=> 0.5
);

$fetch_data = array("id" => "RS_9247C52A37C5EB15C7E8E974CD1B35D7");
$update_data = array("id" => "2755","business_name"=>"Mad O!","business_email"=> "[email protected]",
"account_bank"=> "044","account_number"=> "0690000040","split_type"=> "flat","split_value"=> "200");

$subaccount = new Subaccount();
$createSubaccount = $subaccount->createSubaccount($data);
$getSubaccounts = $subaccount->getSubaccounts();
$fetchSubaccount = $subaccount->fetchSubaccount($fetch_data);
$updateSubaccount = $subaccount->updateSubaccount($update_data);
print_r($createSubaccount);

Transfer Recipient

The following implementation shows how to create a transfer recipient on the rave dashboard. Use the Playground Directory to view Responses and samples of use.

require("Flutterwave-Rave-PHP-SDK/library/Recipient.php");
use Flutterwave\EventHandlers\EventHandlers\EventHandlers\EventHandlers\EventHandlers\Recipient;

$data = array(
    "account_bank"=> "044",
    "account_number"=> "0690000036",
);
$fetchdata = array(
  'id' => '6153'
);
$deldata = array(
  'id'=>'7236'
);

$payment = new Recipient();
$recipient1 = $payment->createRecipient($data);//Create a recipient for transfer
$recipients = $payment->listRecipients();// get all existing recipients
$recipient = $payment->fetchBeneficiary($fetchdata);//fetch a specific recipient.
$deleteRecipient = $payment->deleteBeneficiary($deldata);//delete recipient
print_r($recipient1);

Subscriptions

The following implementation shows how to activate a subscription, fetch a subscription, get all subscriptions.

require("Flutterwave-Rave-PHP-SDK/library/Subscription.php");
use Flutterwave\EventHandlers\EventHandlers\EventHandlers\EventHandlers\EventHandlers\Subscription;

$id = 1112 //Id of subscription plan
//$cid = 2222
$subscription = new Subscription();
$resultGet = $subscription->getAllSubscription();//gets all existing subscription
$resultActivate = $subscription->activateSubscription($id);// activates a subscription plan
$resultCancel = $subscription->cancelSubscription($cid);// activates a subscription plan

//returns the result 
print_r($result);

Bills

The following implementation shows how to pay for any kind of bill from Airtime to DSTv payments to Tolls. Please view the rave documentation section on Bill payment for different types of bill services you can pass into the payBill method as an$array.

visit: https://developer.flutterwave.com/v3.0/reference#buy-airtime-bill

require("Flutterwave-Rave-PHP-SDK/library/Bill.php");
use Flutterwave\EventHandlers\EventHandlers\EventHandlers\EventHandlers\EventHandlers\Bill;

$data = array(
    "country"=> "NG",
	"customer"=> "+23490803840303",
	"amount"=> 500,
	"recurrence"=> "ONCE",
	"type"=> "AIRTIME",
	"reference"=> "9300049645534545454332433"
);

//sample payload for bulkBill()
$bulkdata = array(
    "bulk_reference"=>"edf-12de5223d2f3243474543",
    "callback_url"=>"https://webhook.site/96374895-154d-4aa0-99b5-709a0a128674",
    "bulk_data"=> array(
        array(
        "country"=> "NG",
        "customer"=> "+23490803840303",
        "amount"=> 500,
        "recurrence"=> "WEEKLY",
        "type"=> "AIRTIME",
        "reference"=>"930049200929"
        ),
        array(
        "country"=>"NG",
        "customer"=> "+23490803840304",
        "amount"=> 500,
        "recurrence"=> "WEEKLY",
        "type"=>"AIRTIME",
        "reference"=>"930004912332434232"
        )
    ),
);

$getdata = array(
    //"reference"=>"edf-12de5223d2f32434753432"
     "id"=>"BIL136",
     "product_id"=>"OT150"
);

$payment = new Bill();
$result = $payment->payBill($data);//create a bill paymenr
$bulkresult = $payment->bulkBill($bulkdata);//create bulk bill payment....
$getresult = $payment->getBill($getdata);// get bulk result....
$getAgencies = $payment->getAgencies();
$getBillCategories = $payment->getBillCategories();
print_r($result);

Ebills

The following implementation shows how to create a electronic receipt.

require("Flutterwave-Rave-PHP-SDK/library/Ebill.php");
use Flutterwave\EventHandlers\EventHandlers\EventHandlers\EventHandlers\EventHandlers\Ebill;

$data = array(
    "narration"=> "mndkn blls",
    "number_of_units"=> 2,//should be a string
    "currency"=> "NGN",
    "amount"=> 200,//should be a string
    "phone_number"=> "09384747474",
    "email"=>"[email protected]",
    "tx_ref"=> "akhlm-pstmn-1094434370393",
    "ip"=> "127.9.0.7",
    "custom_business_name"=> "John Madakin",
    "country"=> "NG"
);

$update = array(
    "reference"=>"RVEBLS-2B93A7039017-90937",//on creation of order, this is the flw_ref
    "currency"=> "NGN",
    "amount"=> "4000"
);

$payment = new Ebill();
$result = $payment->order($data);//create an order reciept
$updateResult = $payment->updateOrder($update);//create bulk bill payment....
print_r($result);

Virtual Accounts

The following implementation shows how to create a virtual Account. Please view the documentation for more options that can be added in the payload https://developer.flutterwave.com/reference#create-a-virtual-account-number

require("Flutterwave-Rave-PHP-SDK/library/VirtualAccount.php");
use Flutterwave\EventHandlers\EventHandlers\EventHandlers\EventHandlers\EventHandlers\VirtualAccount;

//sample payload for payBill()
$data = array(
  "email"=> "[email protected]",
  "duration"=> 5,
  "frequency"=> 5,
  "amount"=>"22000",
  "is_permanent"=> true,
  "tx_ref"=> "jhn-mdkn-101923123463"
);

$bulkdata = array(
  "accounts"=> 5,
  "email"=> "[email protected]",
  "is_permanent"=> true,
  "tx_ref"=> "jhn-mndkn-012439283422"
);

$batch = array('batch_id' => 'RND_2641579516055928');

$getdata = array(
    "order_ref"=>"URF_1590362018488_8875935"
);

$account = new VirtualAccount();
$result = $account->createVirtualAccount($data);//create a virtak account
$bulkAccounts = $account->createBulkAccounts($bulkdata);//create bulk v accounts
$virtualAccounts = $account->getBulkAccounts($batch);//list all bulk accounts
$virtualAccount = $account->getAccountNumber($getdata);//get an account.
print_r($result);

Tokenized Charge

Once the charge and validation process is complete for the first charge on the card, you can make use of the token for subsequent charges.

require("Flutterwave-Rave-PHP-SDK/library/TokenizedCharge.php");
use Flutterwave\EventHandlers\EventHandlers\EventHandlers\EventHandlers\EventHandlers\TokenizedCharge;

$data = array(
     "token"=> "flw-t1nf-1ff187b04cecb4acff4ac62c2b6f7784-m03k",
     "currency"=> "NGN",
     "country"=> "NG",
     "amount"=> 30300,
     "email"=> "[email protected]",
     "first_name"=> "Anonymous",
     "last_name"=> "customer",
     "client_ip" =>"154.123.220.1",
     "device_fingerprint" =>"62wd23423rq324323qew1" 
    );

$payment = new TokinizedCharge();
$result = $payment->tokenCharge($data);//initiates the charge
$verify = $payment->verifyTransaction();
print_r($result);

View Transactions

List all transactions on your account. You could do a specific query using customer_email or customer_fullname to make specifc search. View all successfull or failed transactions for a particular period, month or year

require("Flutterwave-Rave-PHP-SDK/library/Transactions.php");
use Flutterwave\EventHandlers\EventHandlers\EventHandlers\EventHandlers\EventHandlers\Transactions;

$data = array(
'amount'=> 1000
);
$fetch_data = array(
'id'=>'345522'
);
$time_data = array(
  'id'=>'3434'
);

$history = new Transactions();
$transactions = $history->viewTransactions();
$transactionfee = $history->getTransactionFee($data);
$verifyTransaction = $history->verifyTransaction($fetch_data);
$timeline = $history->viewTimeline($time_data);
print_r($transactions);

Voucher payment

Collect ZAR payments offline using Vouchers

require("Flutterwave-Rave-PHP-SDK/library/VoucherPayment.php");

use Flutterwave\EventHandlers\EventHandlers\EventHandlers\EventHandlers\EventHandlers\VoucherPayment;
//The data variable holds the payload
$data = array(
        //"public_key": "FLWPUBK-6c4e3dcb21282d44f907c9c9ca7609cb-X"//you can ommit the public key as the key is take from your .env file
        //"tx_ref": "MC-15852309v5050e8",
        "amount"=> "100",
        "type"=> "voucher_payment",
        "currency"=> "ZAR",
        "pin"=> "19203804939000",
        "email"=>"[email protected]",
        "phone_number" =>"0902620185",
        "account_bank" => "058",
        "fullname" => "Ekene Eze",
        "client_ip" =>"154.123.220.1",
        "device_fingerprint" =>"62wd23423rq324323qew1",
        "meta" => array(
            "flightID"=> "123949494DC"
        )     
    );

$payment = new VoucherPayment();
$result = $payment->voucher($data);
if(isset($result['data'])){
  $id = $result['data']['id'];
  $verify = $payment->verifyTransaction($id);
}
print_r($result);

You can also find the class documentation in the docs folder. There you will find documentation for the Rave class and the EventHandlerInterface.

Testing

All of the SDK's tests are written with PHP's phpunit module. The tests currently test: Account, Card, Transfer, Preauth, Subaccount, Subscriptions and Paymentplan

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

Comments
  • Failed to install having issues with monolog/monolog 2.0.2

    Failed to install having issues with monolog/monolog 2.0.2

    Trying to install the package in my project

    `our requirements could not be resolved to an installable set of packages.

    Problem 1 - Installation request for flutterwavedev/flutterwave-v3 ^1.0 -> satisfiable by flutterwavedev/flutterwave-v3[1.0.0]. - Conclusion: remove monolog/monolog 2.0.2 - Conclusion: don't install monolog/monolog 2.0.2 - flutterwavedev/flutterwave-v3 1.0.0 requires monolog/monolog 1.* -> satisfiable by monolog/monolog[1.0.0, 1.0.0-RC1, 1.0.1, 1.0.2, 1.1.0, 1.10.0, 1.11.0, 1.12.0, 1.13.0, 1.13.1, 1.14.0, 1.15.0, 1.16.0, 1.17.0, 1.17.1, 1.17.2, 1.18.0, 1.18.1, 1.18.2, 1.19.0, 1.2.0, 1.2.1, 1.20.0, 1.21.0, 1.22.0, 1.22.1, 1.23.0, 1.24.0, 1.25.0, 1.25.1, 1.25.2, 1.25.3, 1.25.4, 1.25.5, 1.26.0, 1.3.0, 1.3.1, 1.4.0, 1.4.1, 1.5.0, 1.6.0, 1.7.0, 1.8.0, 1.9.0, 1.9.1, 1.x-dev]. - Can only install one of: monolog/monolog[1.0.0, 2.0.2]. - Can only install one of: monolog/monolog[1.0.0-RC1, 2.0.2]. - Can only install one of: monolog/monolog[1.0.1, 2.0.2]. - Can only install one of: monolog/monolog[1.0.2, 2.0.2]. - Can only install one of: monolog/monolog[1.1.0, 2.0.2]. - Can only install one of: monolog/monolog[1.10.0, 2.0.2]. - Can only install one of: monolog/monolog[1.11.0, 2.0.2]. - Can only install one of: monolog/monolog[1.12.0, 2.0.2]. - Can only install one of: monolog/monolog[1.13.0, 2.0.2]. - Can only install one of: monolog/monolog[1.13.1, 2.0.2]. - Can only install one of: monolog/monolog[1.14.0, 2.0.2]. - Can only install one of: monolog/monolog[1.15.0, 2.0.2]. - Can only install one of: monolog/monolog[1.16.0, 2.0.2]. - Can only install one of: monolog/monolog[1.17.0, 2.0.2]. - Can only install one of: monolog/monolog[1.17.1, 2.0.2]. - Can only install one of: monolog/monolog[1.17.2, 2.0.2]. - Can only install one of: monolog/monolog[1.18.0, 2.0.2]. - Can only install one of: monolog/monolog[1.18.1, 2.0.2]. - Can only install one of: monolog/monolog[1.18.2, 2.0.2]. - Can only install one of: monolog/monolog[1.19.0, 2.0.2]. - Can only install one of: monolog/monolog[1.2.0, 2.0.2]. - Can only install one of: monolog/monolog[1.2.1, 2.0.2]. - Can only install one of: monolog/monolog[1.20.0, 2.0.2]. - Can only install one of: monolog/monolog[1.21.0, 2.0.2]. - Can only install one of: monolog/monolog[1.22.0, 2.0.2]. - Can only install one of: monolog/monolog[1.22.1, 2.0.2]. - Can only install one of: monolog/monolog[1.23.0, 2.0.2]. - Can only install one of: monolog/monolog[1.24.0, 2.0.2]. - Can only install one of: monolog/monolog[1.25.0, 2.0.2]. - Can only install one of: monolog/monolog[1.25.1, 2.0.2]. - Can only install one of: monolog/monolog[1.25.2, 2.0.2]. - Can only install one of: monolog/monolog[1.25.3, 2.0.2]. - Can only install one of: monolog/monolog[1.25.4, 2.0.2]. - Can only install one of: monolog/monolog[1.25.5, 2.0.2]. - Can only install one of: monolog/monolog[1.26.0, 2.0.2]. - Can only install one of: monolog/monolog[1.3.0, 2.0.2]. - Can only install one of: monolog/monolog[1.3.1, 2.0.2]. - Can only install one of: monolog/monolog[1.4.0, 2.0.2]. - Can only install one of: monolog/monolog[1.4.1, 2.0.2]. - Can only install one of: monolog/monolog[1.5.0, 2.0.2]. - Can only install one of: monolog/monolog[1.6.0, 2.0.2]. - Can only install one of: monolog/monolog[1.7.0, 2.0.2]. - Can only install one of: monolog/monolog[1.8.0, 2.0.2]. - Can only install one of: monolog/monolog[1.9.0, 2.0.2]. - Can only install one of: monolog/monolog[1.9.1, 2.0.2]. - Can only install one of: monolog/monolog[1.x-dev, 2.0.2]. - Installation request for monolog/monolog (locked at 2.0.2) -> satisfiable by monolog/monolog[2.0.2].`

    Don't really understand why this is happening

    opened by Francis-nova 9
  • Error installing in Laravel 9

    Error installing in Laravel 9

    I cannot install this package in Laravel 9 Here is the error am getting

        - flutterwavedev/flutterwave-v3 1.0.0 requires monolog/monolog 1.* -> found monolog/monolog[1.0.0-RC1, ..., 1.x-dev] but the package is fixed to 2.6.0 (lock file version) by a partial update and that version does not match. Make sure you list it as an argument for the update command.
        - flutterwavedev/flutterwave-v3 1.0.1 requires vlucas/phpdotenv ^2.5 -> found vlucas/phpdotenv[v2.5.0, ..., 2.6.x-dev] but the package is fixed to v5.4.1 (lock file version) by a partial update and that version does not match. Make sure you list it as an argument for the update command.
        - Root composer.json requires flutterwavedev/flutterwave-v3 ^1.0 -> satisfiable by flutterwavedev/flutterwave-v3[1.0.0, 1.0.1].
    
    opened by Stancobridge 6
  • Pls update package on composer platform

    Pls update package on composer platform

    Thanks for this package, it has really been helpful, can you guys pls update the package on Composer platform, several of the dependencies there are preventing installation using composer and I can see on the repo here that the composer.json file is more up to date.

    Thanks

    opened by spectrummfb 5
  • How can i integrate the sdk in laravel

    How can i integrate the sdk in laravel

    It is pretty clear how to integrate php libraries/sdk using something like composer require xyz/zyx. How can i do this same using with this sdk because it is not in the documentation

    opened by os-kingsley 4
  • Flutterwave require(Flutterwave-Rave-PHP-SDK/library/MobileMoney.php): Failed to open stream: No such file or directory

    Flutterwave require(Flutterwave-Rave-PHP-SDK/library/MobileMoney.php): Failed to open stream: No such file or directory

    I think this packages has an issue. Am using Laravel 9.5 with PHP 8.1. I have tried a lot of solutions but I seem stuck

    codesnipet

    This is my Laravel code This is the Error i get through my API request

    fluttwaveerror

    Please any one with a solution

    opened by Deepcodeinnovations 3
  • Improve PHPUnit version semver and array syntax

    Improve PHPUnit version semver and array syntax

    Changed log

    • Adding the ^4.8.36 for the PHP 5.4 versions during PHPUnit tests.
    • Replace the short array syntax with array syntax since this SDK requires php-5.4 version at least.
    opened by peter279k 3
  • Please upgrade the Monolog library to version 2.x

    Please upgrade the Monolog library to version 2.x

    The SDK still loads Monolog 1.x, which is an old version of the library, and it can't be used in any environment which requires the newer version. I would recommend to change file composer.json to reference Monolog 2.x and adjust your code to use the new version.

    The changes should be minimal, as Monolog 2.x is backward compatible and includes better support for PHP 7. You can find a list of the most important changes here: https://github.com/Seldaek/monolog/blob/master/UPGRADE.md. Such update would allow to use the Flutterwave SDK in modern PHP applications.

    opened by daigo75 3
  • Class not found || failed to open stream: No such file or directory.

    Class not found || failed to open stream: No such file or directory.

    Please do you have any workaround for the installation?

    I installed the package this way composer require flutterwavedev/flutterwave-v3 but still I can't seem to get beyond the error Class "Flutterwave\Bill" not found.

    Also, I can't find this file in the installation dir so I end up with, require(Flutterwave-Rave-PHP-SDK/library/Bill.php): failed to open stream: No such file or directory.

    is this the official SDK?`

    I have checked the entire README file and also this page https://developer.flutterwave.com/reference/endpoints/bills#validate-a-bill-service but I can't find a solution

    opened by Chamberlainfrancis 2
  • Verify Transaction

    Verify Transaction

    I tried to verify Transaction $verify = $verify = $payment->verifyTransaction($id); but i keep getting Array ( [status] => error [message] => No transaction was found for this id [data] => )

    even when i passed the ID directly into the function i still get the same error.

    opened by towoju5 2
  • Issue with RootPackageLoader.php on line 162

    Issue with RootPackageLoader.php on line 162

    I tried using composer to install your dependencies but got the error: require-dev.mikey179/vfsStream is invalid, it should not contain uppercase characters. Please use mikey179/vfsstream instead.

    opened by Laivee 1
  • Errors in library

    Errors in library

    Hi.

    You guys have really done a great job by developing this awesome platform. On the contrary you gave me spitting headache trying to figure why your code does not work. So many bugs in it trying to interface it with laravel application.

    In EventHandlerController under onSuccessful($transactionData), $transactionData->status returns successful not success.

    $payment->logger->warning('Stop!!! Please pass the txref parameter!'); not $payment->logger->warn('Stop!!! Please pass the txref parameter!'); the method warn was never implemented.

    The are tons of these errors but this are the few I can mention for now.

    I look forward to the fix. Thanks, and God bless y'all.

    opened by habideen 1
  • No Responsive Display On Mobile Devices

    No Responsive Display On Mobile Devices

    HI, and how do you do @flutterwave?

    I find it difficult to make the payment dialog fit to screen size on mobile device. I have to zoom in before I can see anything on the screen because it loads very small on mobile devices. The screen size is normal on desktop device or larger screens and I have no issue with it.

    Could you help me with that, please? I really need it.

    opened by habideen 0
Releases(1.0.4)
Owner
Flutterwave
Flutterwave
Standardized wrapper for popular currency rate APIs. Currently supports FixerIO, CurrencyLayer, Open Exchange Rates and Exchange Rates API.

?? Wrapper for popular Currency Exchange Rate APIs A PHP API Wrapper to offer a unified programming interface for popular Currency Rate APIs. Dont wor

Alexander Graf 24 Nov 21, 2022
A simple but extensible economy engine for PocketMine-MP, using label-oriented APIs.

Capital A simple but very extensible economy plugin for PocketMine-MP. How is Capital different from other economy plugins? Capital introduces a label

Jonathan Chan Kwan Yin 37 Dec 19, 2022
A Magento 2 module that enables configurable CORS Headers on the GraphQL and REST APIs

Magento 2 CORS Magento Version Support Ever try to work with the Magento GraphQL API or REST API from your browser and see the following? Access to XM

Graycore, LLC 62 Dec 8, 2022
Scalable and durable data imports for publishing and consuming APIs

Porter Scalable and durable data imports for publishing and consuming APIs Porter is the all-purpose PHP data importer. She fetches data from anywhere

null 596 Jan 6, 2023
Collect - REDAXO-Addon für APIs und Feeds auf Basis von YForm

Collect sammelt anhand unterschiedlicher APIs und Schnittstellen in regelmäßigen Abständen Social Media Posts, RSS-Einträge, Videos und Playlists und andere Inhalte.

alex+ Informationsdesign 5 Jun 23, 2022
This document provides the details related to Remittance API. This APIs is used to initiate payment request from Mobile client/others exchange house.

City Bank Remittance API This is where your description should go. Limit it to a paragraph or two. Consider adding a small example. Installation You c

MD ARIFUL HAQUE 2 Oct 2, 2022
Dobren Dragojević 6 Jun 11, 2023
Easy to use utility functions for everyday PHP projects. This is a port of the Lodash JS library to PHP

Lodash-PHP Lodash-PHP is a port of the Lodash JS library to PHP. It is a set of easy to use utility functions for everyday PHP projects. Lodash-PHP tr

Lodash PHP 474 Dec 31, 2022
PHP Text Analysis is a library for performing Information Retrieval (IR) and Natural Language Processing (NLP) tasks using the PHP language

php-text-analysis PHP Text Analysis is a library for performing Information Retrieval (IR) and Natural Language Processing (NLP) tasks using the PHP l

null 464 Dec 28, 2022
php-echarts is a php library for the echarts 5.0.

php-echarts 一款支持Apache EChart5.0+图表的php开发库 优先ThinkPHP5/6的开发及测试。 Apache EChart5.0已经最新发布,在视觉效果、动画效果和大数据展示方面已经远超之前的版本; 故不考虑EChart5.0之前版本的兼容问题;建议直接尝试5.0+

youyiio 5 Aug 15, 2022
Minimalist PHP frame for Core-Library, for Developing PHP application that gives you the full control of your application.

LazyPHP lightweight Pre-Made Frame for Core-library Install Run the below command in your terminal $ composer create-project ryzen/lazyphp my-first-pr

Ry-Zen 7 Aug 21, 2022
Gettext is a PHP (^7.2) library to import/export/edit gettext from PO, MO, PHP, JS files, etc.

Gettext Note: this is the documentation of the new 5.x version. Go to 4.x branch if you're looking for the old 4.x version Created by Oscar Otero http

Gettext 651 Dec 29, 2022
Columnar analytics for PHP - a pure PHP library to read and write simple columnar files in a performant way.

Columnar Analytics (in pure PHP) On GitHub: https://github.com/envoymediagroup/columna About the project What does it do? This library allows you to w

Envoy Media Group 2 Sep 26, 2022
:date: The VObject library for PHP allows you to easily parse and manipulate iCalendar and vCard objects

sabre/vobject The VObject library allows you to easily parse and manipulate iCalendar and vCard objects using PHP. The goal of the VObject library is

sabre.io 532 Dec 25, 2022
Small convention based CQRS library for PHP

LiteCQRS for PHP Small naming-convention based CQRS library for PHP (loosely based on LiteCQRS for C#) that relies on the MessageBus, Command, EventSo

Benjamin Eberlei 560 Nov 20, 2022
Experimental library for forking PHP

Spork: PHP on a Fork <?php $manager = new Spork\ProcessManager(); $manager->fork(function() { // do something in another process! return 'Hel

Kris Wallsmith 588 Nov 20, 2022
Collection pipeline library for PHP

Knapsack Collection pipeline library for PHP Knapsack is a collection library for PHP >= 5.6 that implements most of the sequence operations proposed

Dušan Kasan 540 Dec 17, 2022
A PHP library to play with the Raspberry PI's GPIO pins

php-gpio php-gpio is a simple PHP library to play with the Raspberry PI's GPIO pins. It provides simple tools such as reading & writing to pins. [UPDA

Ronan Guilloux 266 Oct 17, 2022
PHP library for dealing with European VAT

ibericode/vat This is a simple PHP library to help you deal with Europe's VAT rules. Fetch VAT rates for any EU member state using ibericode/vat-rates

ibericode 389 Dec 31, 2022