M-Pesa Daraja API Integration for PHP
# M-Pesa Daraja API Integration for PHP
A comprehensive, production-ready PHP library for integrating Safaricom's M-Pesa Daraja API into your applications. This library supports STK Push (Lipa Na M-Pesa Online), STK Query, B2C, C2B, and more.
---
## Table of Contents
- Features
- Requirements
- Installation
- Quick Start
- Configuration
- API Reference
- STK Push
- STK Query
- B2C Payment
- C2B Registration
- Frontend Integration
- Callback Handling
- Security Best Practices
- Error Codes
- Troubleshooting
- Contributing
- License
---
## Features
- ✅ **STK Push** - Initiate mobile money payments (Lipa Na M-Pesa Online)
- ✅ **STK Query** - Check transaction status
- ✅ **B2C Payments** - Send money to customers (salaries, refunds)
- ✅ **C2B Integration** - Receive payments from customers
- ✅ **OAuth Authentication** - Automatic token generation and caching
- ✅ **Comprehensive Logging** - Debug with detailed logs
- ✅ **Error Handling** - Detailed error messages and codes
- ✅ **Phone Number Formatting** - Auto-format to international format
- ✅ **Production Ready** - Follows Daraja API best practices
---
## Requirements
- PHP 7.4 or higher
- cURL extension enabled
- JSON extension enabled
- OpenSSL extension enabled
- M-Pesa Developer Account (
developer.safaricom.co.ke)
---
## Installation
1. **Clone or Download**
```bash
git clone
github.com
```
2. **Configure Credentials**
Edit `config.php` and add your M-Pesa credentials:
```php
$config['consumer_key'] = 'YOUR_CONSUMER_KEY';
$config['consumer_secret'] = 'YOUR_CONSUMER_SECRET';
$config['passkey'] = 'YOUR_PASSKEY';
```
3. **Set Callback URL**
For sandbox: Use a tool like ngrok to expose your localhost
For production: Set your actual domain URL
```php
$config['callback_url'] = '
your-domain.com';
```
4. **Create Logs Directory**
```bash
mkdir logs
chmod 755 logs
```
---
## Quick Start
### 1. Basic STK Push Payment
```php …