What You'll Learn
Understanding STK Push Integration
STK (Sim ToolKit) Push is a payment method that allows businesses to initiate M-Pesa payment requests directly to a customer's mobile phone. When a customer clicks "Pay" on your website or application, SWIFT-WALLET sends a secure payment prompt to their phone. The customer enters their PIN, and within seconds, the payment is processed.
This integration guide will walk you through implementing STK Push in your application using SWIFT-WALLET's API. Whether you're building an e-commerce platform, a booking system, or a donation page, this guide has everything you need to get started.
Key Benefits
- Instant payment processing without redirecting customers
- High success rate with automatic retry logic
- Real-time callbacks for payment status updates
- Support for multiple payment channels (Paybill, Till Number)
- Built-in security and fraud prevention
Prerequisites and Setup
Before you can integrate SWIFT-WALLET STK Push, you'll need:
- SWIFT-WALLET Account: Sign up at swiftwallet.co.ke/signup.php
- API Keys: Obtain your API key from the dashboard under Settings → API Keys
- Payment Channels: Configure at least one payment channel (Paybill or Till Number)
- Callback URL: A secure HTTPS endpoint to receive payment status updates
- Development Environment: PHP 7.4+, Node.js 14+, or Python 3.8+
Important
Your callback URL must be publicly accessible via HTTPS. Use tools like ngrok for local development testing.
Step 1: Create Your SWIFT-WALLET Account
Visit the signup page and create your account. Once registered, you'll gain access to:
- Your dashboard with real-time transaction monitoring
- API credentials for integration
- Payment channel configuration tools
- Transaction history and analytics
Step 2: Configure Payment Channels
Log into your dashboard and navigate to Channels. Add your payment channels:
- Paybill: Safaricom Paybill number with account number
- Till Number: Safaricom Till Number
Pro Tip
You can configure multiple channels, and SWIFT-WALLET will automatically route payments based on availability and success rate.
API Authentication
All API requests to SWIFT-WALLET require authentication using your API key. There are three ways to authenticate:
Method 1: Authorization Header (Recommended)
Authorization: Bearer YOUR_API_KEY
Method 2: Query Parameter
?api_key=YOUR_API_KEY
Method 3: Request Body
{
"api_key": "YOUR_API_KEY"
}
Security Best Practice
Never expose your API key in client-side code. Store it as an environment variable and only use it in server-side requests.
Making Your First STK Push Request
Once you have your API credentials, you can initiate STK Push requests. The basic flow is:
- Collect customer phone number (format: 254XXXXXXXXX)
- Collect payment amount
- Send request to SWIFT-WALLET API
- Store the transaction reference
- Await callback with payment status
STK Push Endpoint
POST https://swiftwallet.co.ke/v3/stk-initiate/
Request Parameters
| Parameter | Type | Required | Description |
|---|---|---|---|
phone_number |
string | Yes | Customer phone number (254XXXXXXXXX) |
amount |
number | Yes | Amount to charge (KES) |
reference |
string | Yes | Unique transaction reference |
callback_url |
string | Yes | HTTPS URL for status updates |
description |
string | No | Transaction description |
Handling Callbacks
Once an STK Push is initiated, SWIFT-WALLET will send real-time callbacks to your callback URL whenever the payment status changes:
- Submitted: Request has been sent to the customer's phone
- Pending: Customer has not yet completed the payment
- Success: Payment completed successfully
- Failed: Payment was not completed (user cancelled, insufficient funds, etc.)
Callback Data Structure
Callbacks include transaction details, status, M-Pesa receipt, phone number, and timestamp for your records.
Error Handling and Best Practices
Common Error Codes
- 400: Invalid request parameters
- 401: Invalid or missing API key
- 402: Insufficient wallet balance (for B2C)
- 404: Invalid endpoint or resource not found
- 429: Rate limit exceeded
- 500: Internal server error
Best Practices
- Always validate phone numbers before sending requests
- Implement retry logic for network failures
- Store transaction references in your database
- Set up webhook signature verification
- Handle timeouts gracefully (STK Push expires after 60 seconds)
- Log all transactions for auditing purposes
Code Examples
PHP Example
function initiateSTKPush($phoneNumber, $amount, $reference, $description = '') {
$url = 'https://swiftwallet.co.ke/v3/stk-initiate/';
$data = [
'api_key' => getenv('SWIFT_WALLET_API_KEY'),
'phone_number' => $phoneNumber,
'amount' => $amount,
'reference' => $reference,
'callback_url' => 'https://yoursite.com/callback',
'description' => $description
];
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
curl_setopt($ch, CURLOPT_HTTPHEADER, [
'Content-Type: application/json'
]);
$response = curl_exec($ch);
curl_close($ch);
return json_decode($response, true);
}
// Usage
$result = initiateSTKPush(
'254712345678',
1000,
'ORDER-12345',
'Payment for Order #12345'
);
if ($result['success']) {
echo "STK Push sent successfully! Transaction: " . $result['transaction_id'];
} else {
echo "Error: " . $result['message'];
}
JavaScript (Node.js) Example
const axios = require('axios');
async function initiateSTKPush(phoneNumber, amount, reference, description = '') {
try {
const response = await axios.post(
'https://swiftwallet.co.ke/v3/stk-initiate/',
{
api_key: process.env.SWIFT_WALLET_API_KEY,
phone_number: phoneNumber,
amount: amount,
reference: reference,
callback_url: 'https://yoursite.com/callback',
description: description
},
{
headers: {
'Content-Type': 'application/json'
}
}
);
return response.data;
} catch (error) {
console.error('STK Push Error:', error.response.data);
throw error;
}
}
// Usage
initiateSTKPush('254712345678', 1000, 'ORDER-12345', 'Payment for Order #12345')
.then(result => {
console.log('STK Push sent!', result.transaction_id);
})
.catch(error => {
console.error('Payment failed:', error.message);
});
Python Example
import requests
import os
def initiate_stk_push(phone_number, amount, reference, description=''):
url = 'https://swiftwallet.co.ke/v3/stk-initiate/'
payload = {
'api_key': os.getenv('SWIFT_WALLET_API_KEY'),
'phone_number': phone_number,
'amount': amount,
'reference': reference,
'callback_url': 'https://yoursite.com/callback',
'description': description
}
response = requests.post(url, json=payload)
return response.json()
# Usage
result = initiate_stk_push(
'254712345678',
1000,
'ORDER-12345',
'Payment for Order #12345'
)
if result.get('success'):
print(f"STK Push sent! Transaction ID: {result['transaction_id']}")
else:
print(f"Error: {result['message']}")
Callback Handler Example (PHP)
// Callback handler endpoint
function handleCallback() {
$payload = file_get_contents('php://input');
$data = json_decode($payload, true);
// Verify webhook signature (optional but recommended)
// $signature = $_SERVER['HTTP_X_SWIFT_SIGNATURE'];
// verifySignature($signature, $payload);
$transactionId = $data['transaction_id'];
$status = $data['status'];
$reference = $data['reference'];
// Update your database
updateTransactionStatus($reference, $status, $data);
// Send confirmation to customer
if ($status === 'success') {
sendConfirmationEmail($reference);
}
// Return 200 OK to acknowledge receipt
http_response_code(200);
echo json_encode(['status' => 'received']);
}
Testing in Production
Before going live with your STK Push integration, follow these testing guidelines:
- Use Test Credentials: Start with SWIFT-WALLET's sandbox environment
- Test Different Scenarios: Success, cancellation, timeout, insufficient funds
- Verify Callbacks: Ensure your callback URL receives all status updates
- Check Error Handling: Test with invalid phone numbers and amounts
- Monitor Dashboard: Use the dashboard to verify transaction flow
Ready to Go Live?
Once testing is complete, switch to production API keys and start accepting real payments. Our support team is available 24/7 if you need assistance.