# Mpesa.Gate
`Mpesa.Gate` is a .NET library for calling Safaricom M-PESA APIs:
- STK Push (M-PESA Express)
- C2B
- B2C
- account balance
- reversals
- Dynamic QR.
## Why use Mpesa.Gate?
- **Token caching:** `MpesaApiService` retains a successfully generated OAuth access token until it expires, avoiding an unnecessary token request before every API call when the same service instance is reused.
- **Typed request and response models:** the library provides models for each supported API, reducing manual JSON construction and making integrations easier to understand.
- **Built-in M-PESA password generation:** `MpesaHelper.GenerateMpesaPassword` creates the timestamp and Base64 STK password together, preventing a common source of STK Push errors.
- **One client for core payment flows:** use the same service for STK Push, C2B, B2C, reversals, account balance, and Dynamic QR.
- **.NET-friendly HTTP integration:** use the service directly or register its typed `HttpClient` through ASP.NET Core dependency injection.
## Add the library to an application
This project is not currently published as a NuGet package. Add it to your solution and reference it from the calling project:
```bash
git clone
github.com
dotnet add .csproj reference Mpesa.Gate/Mpesa.Gate.csproj
```
Keep M-PESA credentials, passkeys, and operator passwords in user secrets, environment variables, or a secure secret store. Do not place production credentials in source code.
## Option 1: Use `MpesaApiService` directly
This is a good fit for console applications, background jobs, or a small integration where you create the service yourself.
```csharp
using Mpesa.Gate.Common;
using Mpesa.Gate.Models.LipaNaMpesa;
using Mpesa.Gate.Models.OAuth;
using Mpesa.Gate.Services;
// `configuration` is an IConfiguration instance supplied by the host application.
var consumerKey = configuration["Mpesa:ConsumerKey"]!;
var consumerSecret = configuration["Mpesa:ConsumerSecret …