Integration Guide

Integration with SWIFT-WALLET STK Push: Complete Developer Guide

January 20, 2025 12 min read SWIFT-WALLET Team

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:

  1. SWIFT-WALLET Account: Sign up at swiftwallet.co.ke/signup.php
  2. API Keys: Obtain your API key from the dashboard under Settings → API Keys
  3. Payment Channels: Configure at least one payment channel (Paybill or Till Number)
  4. Callback URL: A secure HTTPS endpoint to receive payment status updates
  5. 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:

Step 2: Configure Payment Channels

Log into your dashboard and navigate to Channels. Add your payment channels:

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:

  1. Collect customer phone number (format: 254XXXXXXXXX)
  2. Collect payment amount
  3. Send request to SWIFT-WALLET API
  4. Store the transaction reference
  5. 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:

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

Best Practices

  1. Always validate phone numbers before sending requests
  2. Implement retry logic for network failures
  3. Store transaction references in your database
  4. Set up webhook signature verification
  5. Handle timeouts gracefully (STK Push expires after 60 seconds)
  6. 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:

  1. Use Test Credentials: Start with SWIFT-WALLET's sandbox environment
  2. Test Different Scenarios: Success, cancellation, timeout, insufficient funds
  3. Verify Callbacks: Ensure your callback URL receives all status updates
  4. Check Error Handling: Test with invalid phone numbers and amounts
  5. 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.

Start Integrating STK Push Today

Join thousands of developers using SWIFT-WALLET for seamless payment integration.

Start Free Account View API Docs
Complete documentation
Code examples
24/7 support