Azampay: A Convenient Payment Service Provider in Tanzania
Tags: webdev, laravel, tutorial, php
Published: 2023-06-07 19:23:40

Introduction:

In today's fast-paced digital world, payment service providers play a vital role in facilitating secure and convenient transactions. One such provider making waves in Tanzania is [Azampay](https://developerdocs.azampay.co.tz/redoc). In this blog post, we will explore the features and benefits of Azampay and demonstrate how to integrate it into a [Laravel](https://laravel.com/docs/10.x) application using the open-source package created by [Alpha Olomi](https://alphaolomi.github.io/).

## Getting Started:

To get started with Azampay, you'll need to sign up for an account on their [website](https://developerdocs.azampay.co.tz/redoc). Once you've registered, you will receive API credentials, including a `AZAMPAY_CLIENT_ID` and `AZAMPAY_CLIENT_SECRET`. These credentials are essential for authenticating your requests and ensuring the security of your transactions. Edit your `.env` file and add the following credentials:

```dosini
AZAMPAY_APP_NAME="your_app_name"
AZAMPAY_CLIENT_ID="your_client_id"
AZAMPAY_CLIENT_SECRET="your_client_secret"
AZAMPAY_ENVIRONMENT="sandbox"
AZAMPAY_TOKEN="Your_Token"
```

<br>

## Usage in Laravel:

To simplify the integration process for Laravel developers, Alpha Olomi, an independent open-source maintainer, has created a package called [laravel-azampay](https://github.com/alphaolomi/laravel-azampay). This package provides a seamless way to incorporate Azampay into your Laravel application.

To begin, you can install the package via [Composer](https://getcomposer.org/) by running the following command in your terminal:

```bash
composer require alphaolomi/laravel-azampay
```

Next, you'll need to publish the package's configuration file using the artisan command:

```bash
php artisan vendor:publish --provider="AlphaOlomi\Azampay\AzampayServiceProvider"
```

This will create a `azampay.php` file in your Laravel project's `config` directory. Open this file and update the `client_id` and `client_key` fields with the credentials provided by Azampay config.

Once you have configured the package, you can start using it in your application.

```bash
php artisan serve
```

Now, You can initiate a payment by calling the `Azampay` facade's checkout methods example th e `mobileCheckout` method, passing the required parameters such as the account number ,provider, reference ID etc. The package handles the communication with Azampay's API.

There are two ways to initiate a payment. You can either use the `Azampay` facade directly or inject the `Azampay` class into your controller. 


The following code snippet demonstrates how to initiate a payment using the `Azampay` facade. The `mobileCheckout` method accepts the amount and reference ID as parameters and initiates a payment. It returns a response object. Azampay supports two payment methods: `mobileCheckout` and `bankCheckout`. The `mobileCheckout` method is used to initiate payments via mobile money, while the `bankCheckout` method is used to initiate payments via bank transfers.

Example: Using Facades,

```php
use Alphaolomi\Azampay\Facades\Azampay;

$data = Azampay::mobileCheckout([
    'amount' => 10000,
    'currency' => 'TZS',
    'accountNumber' => '0747991498',
    'externalId' => '08012345678', // your reference ID
    'provider' => 'Mpesa', // Mpesa, 
]);


// response
array:3 [▼
  "success" => true
  "transactionId" => "b85e971981844a6f8888b42579655b8f"
  "message" => "Your request has been received and is being processed."
]
```


## Persistening your transactions using SQLite in Development:


Make sure you have the [SQLite](https://www.sqlite.org/index.html) extension installed on your machine. If you're using a Mac, you can install it using [Homebrew](https://brew.sh/).

```bash
brew install sqlite
```

If you're using Windows, you can download the [SQLite](https://www.sqlite.org/download.html) extension from the official website.

Once you have installed the SQLite extension, you can create a database file in your project's `database` directory. You can do this by running the following command in your terminal.

### Setup

```bash
touch database/database.sqlite
```


<!-- edit .env to use sqlite -->

```bash
DB_CONNECTION=sqlite
DB_DATABASE=/absolute/path/to/database.sqlite
```

<!-- make model -->

```bash
php artisan make:model Transaction -m
```

This will make a model and migration file for you. Open the migration file and update the `up` method as follows:


In the migration file, update the `up` method as follows:

```php
public function up()
{
    Schema::create('transactions', function (Blueprint $table) {
        $table->id();
        $table->string('transaction_id');
        $table->string('external_id');
        $table->string('amount');
        $table->string('currency');
        $table->string('account_number');
        $table->string('provider');
        $table->string('status');
        $table->string('message');
        $table->timestamps();
    });
}
```

Now, run the migration command to create the `transactions` table in your database:

```bash
php artisan migrate
```

In your, `Transaction` model, add the following code:   

```php
<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;

class Transaction extends Model
{
    use HasFactory;

    protected $fillable = [
        'transaction_id',
        'external_id',
        'amount',
        'currency',
        'account_number',
        'provider',
        'status',
        'message',
    ];
}
```

Now, you can update your controller to persist the transaction data in the database. The following code snippet demonstrates how to do this:

```php
<?php

namespace App\Http\Controllers;

use App\Models\Transaction;

class TransactionController extends Controller
{
    public function store(Request $request)
    {
        $data = Azampay::mobileCheckout([
            'amount' => 10000,
            'currency' => 'TZS',
            'accountNumber' => '0747991498',
            'externalId' => '08012345678', // your reference ID
            'provider' => 'Mpesa', // Mpesa, 
        ]);

        Transaction::create([
            'transaction_id' => $data['transactionId'],
            'external_id' => $data['externalId'],
            'amount' => $data['amount'],
            'currency' => $data['currency'],
            'account_number' => $data['accountNumber'],
            'provider' => $data['provider'],
            'status' => $data['success'] ? 'success' : 'failed',
            'message' => $data['message'],
        ]);

        return $data;
    }
}
```


Note: You could use events to handle the persistence of transactions. This would allow you to decouple the persistence logic from the controller and keep your code clean and maintainable.


To simplify the initial setup and testing,we will use  SQLite for persistance in development. SQLite is a file-based database engine that requires no additional configuration, making it perfect for local development and small-scale projects.

If you wish to use a different database driver for production, you can update the database configuration in your Laravel project's `.env` file.

## Final Remarks:

In this blog post, we explored Azampay as a payment service provider in Tanzania. We elaborated using  `laravel-azampay` package created by Alpha Olomi, which simplifies the integration of Azampay into Laravel applications.

By following the steps outlined in this post, you can easily get started with Azampay, initiate payments, and persist transaction details into your database. The open-source nature of the `laravel-azampay` package allows for community contributions and enhancements, making it an ideal choice for developers.

Integrating Azampay into your applications empowers you to offer secure and seamless payment experiences.