Using Openpesa PHP package for Payments collection on Mpesa Mobile Wallet
Alpha Olomi
Posted on May 28, 2022
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
- PHP 8 or higher
- Composer
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
Fresh project+ Automatic
Using gitignore.cli to install
npm install -g gitignore.cli
oryarn global add gitignore.cli
composer init
gitignore composer > .gitignore
2. Install package
To install openpesa php package run
composer require openpesa/pesa
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
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
Copy example from openpesa/php-pesa#quick-examples
update credentials
get POST data from submited form (see here
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 🎉
Posted on May 28, 2022
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.