DEV Community

Alpha Olomi
Alpha Olomi

Posted on

Using Openpesa PHP package for Payments collection on Mpesa Mobile Wallet

Part of upcoming Openpesa Tutorials

Disclaimer: This is more of an exercise than a tutorial.

Hello there,

In this tutorial we will see how to create a checkout page that uses Openpesa PHP package to communicate to Mpesa for payments collection.

  • User will visit a checkout page and see a form
  • User will fill and sumbit the form
  • User will be prompted to enter Mpesa pin from their phone
  • User will be redirected to asante page

Prerequisites

Skills

  • Basic php
  • Basic programming

Required software

Other

  • Internet connection (communication to Mpesa servers)
  • VSCode is recommended
  • Bash compatible shell is convenient

1. Create Fresh project/Setup on existing

Manual (with existing project)

Recommended for beginners

Assuming composer.json is missing

  • composer.json (copy from here)
  • .gitignore (copy from here)
  • composer.lock will be auto generated

Fresh project+ Automatic

Using gitignore.cli to install npm install -g gitignore.cli or yarn global add gitignore.cli

composer init
gitignore composer > .gitignore
Enter fullscreen mode Exit fullscreen mode

2. Install package

To install openpesa php package run

composer require openpesa/pesa
Enter fullscreen mode Exit fullscreen mode

3. Create 3 files

index.php

process.php

asante.php

Where

index.php - checkout form example

process.php - app logic ie. collection funds

asante.php - redirected after sucess payment

For simplicity

Use Boostrap for styling

Use Emmet for fast scaffolding

4. Get Mpesa credentials

For an in depth guide see getting-started-with-mpesa-developer-portal

Mpesa portal link

tl;dr

  • Signup as dev
  • Setup 2FA
  • Create App - get/copy secret key
  • Enable transactions (C2B for our tutorial) for that app
  • View docs => On Session docs - get/copy public key
  • Add testing phone numbers

5. Update pages-files

Remember the

index.php
asante.php
process.php

Focusing on process.php

6. Test it all

Further

  • Use More robust solution alts consider(validations, logging, queues, user data, )
  • Use Database?
  • Handle Logic for failed payments (retry)
  • Why not Laravel?

Happy Coding ๐ŸŽ‰

Top comments (0)