A modern, type-safe M-Pesa payment integration using tRPC, React, and TypeScript for seamless mobile payments.
Features β’ Installation β’ Tech Stack β’ Architecture β’ Environment Setup β’ API Documentation
Here is a quick look up of the Result
-
Secure M-Pesa Integration
- STK Push for direct customer payments
- Secure token-based authentication
- Automatic M-Pesa access token generation
-
Type-Safe API Communication
- End-to-end type safety with tRPC
- Efficient error handling
- Zod schema validation
-
Developer Experience
- Hot module reloading
- TypeScript for enhanced code quality
- Centralized environment configuration
- Node.js (v16 or higher)
- npm or yarn
- M-Pesa Developer Account
# Clone the repository
git clone https://github.com/IsoDevMate/MPESA-DARAJA-WITH-TRPC.git
# Navigate to project directory
cd backend
# Install dependencies
npm install
# Set up environment variables
cp .env.example .env
# Fill in your M-Pesa API credentials
# Start the server
npm start
# Navigate to project directory
cd frontend
# Install dependencies
npm install
# In a new terminal, start the frontend
npm run dev
- React
- TypeScript
- tRPC Client
- Superjson
- Node.js with Express
- tRPC Server
- Zod for validation
- Axios for API requests
- Safaricom Daraja API
- STK Push mechanism
βββββββββββββββββ βββββββββββββββββ ββββββββββββββββββ
β β β β β β
β React Client βββββββΊβ tRPC Server βββββββΊβ M-Pesa API β
β β β β β β
βββββββββββββββββ βββββββββββββββββ ββββββββββββββββββ
β
βββββββββ΄ββββββββ
β β
β Environment β
β Variables β
β β
βββββββββββββββββ
Create a .env
file in the project root with the following variables:
# M-Pesa API Credentials
MPESA_CONSUMER_KEY=your_consumer_key
MPESA_CONSUMER_SECRET=your_consumer_secret
MPESA_PAYBILL=your_paybill_number
MPESA_PASSKEY=your_passkey
# Callback URL
CALLBACKURL=your_callback_url
# Server Configuration
PORT=3000
Endpoint: /trpc/mpesa.stkPush
Method: POST
Input Schema:
{
phone: string; // Format: "0XXXXXXXXX"
amount: number; // Integer value
}
Response Schema:
{
ResponseCode: string;
ResponseDescription: string;
MerchantRequestID: string;
CheckoutRequestID: string;
CustomerMessage: string;
}
- Start the frontend and backend servers
- Click the "Pay with M-Pesa" button
- Check the browser console for the response
- Verify your phone receives the STK push notification
Common Issues:
- "Failed to get access token": Check your M-Pesa consumer key and secret
- "Failed to make payment": Verify the phone number format and amount
- "CORS error": Make sure your frontend URL is allowed in the backend CORS settings
- Fork the repository
- Create your feature branch (
git checkout -b feature/amazing-feature
) - Commit your changes (
git commit -m 'Add some amazing feature'
) - Push to the branch (
git push origin feature/amazing-feature
) - Open a Pull Request
This project is licensed under the MIT License - see the LICENSE file for details.