A Python library for integrating with various payment gateways in Africa, with initial support for M-Pesa
Project description
Pesa Gateway
A Python library for integrating with various payment gateways in Africa, with initial support for M-Pesa.
Table of Contents
- Features
- Installation
- Configuration
- Usage Examples
- Error Handling
- API Reference
- Contributing
- License
Features
- M-Pesa Integration: Seamless integration with Safaricom's M-Pesa payment gateway
- Easy Configuration: Simple setup with environment variables or direct configuration
- Comprehensive API Coverage: Support for various M-Pesa API endpoints:
- STK Push (Lipa Na M-Pesa Online)
- C2B (Customer to Business)
- B2C (Business to Customer)
- Transaction Status Query
- Account Balance Query
- Phone Number Validation: Built-in validation for East African phone numbers
- Detailed Documentation: Clear examples and usage instructions
- Error Handling: Robust error handling and informative error messages
- Python 3.10+ Support: Built for modern Python applications
Installation
pip install pesa-gateway
Configuration
The library can be configured either through environment variables or by directly passing configuration parameters when initializing the client.
Environment Variables
# Required environment variables for M-Pesa
MPESA_CONSUMER_KEY="your_consumer_key"
MPESA_CONSUMER_SECRET="your_consumer_secret"
MPESA_BUSINESS_SHORT_CODE="your_shortcode"
MPESA_PASS_KEY="your_pass_key"
MPESA_ENVIRONMENT="sandbox" # or "production"
Direct Configuration
from pesagateway import MPesaClient
client = MPesaClient(
consumer_key="your_consumer_key",
consumer_secret="your_consumer_secret",
business_short_code="your_shortcode",
pass_key="your_pass_key",
environment="sandbox" # or "production"
)
Usage Examples
STK Push (Lipa Na M-Pesa Online)
from pesagateway import MPesaClient
client = MPesaClient()
response = client.stk_push(
phone_number="254712345678",
amount=1,
account_reference="TEST",
transaction_desc="Test Payment"
)
C2B (Customer to Business)
response = client.c2b_register_urls(
confirmation_url="https://example.com/confirmation",
validation_url="https://example.com/validation"
)
B2C (Business to Customer)
response = client.b2c_payment(
phone_number="254712345678",
amount=100,
remarks="Salary Payment",
occasion="December Salary"
)
Error Handling
from pesagateway import MPesaError
try:
response = client.stk_push(...)
except MPesaError as e:
print(f"An error occurred: {e}")
Contributing
Contributions are welcome! Please feel free to submit a Pull Request.
- Fork the repository
- Create your feature branch (
git checkout -b feature/AmazingFeature) - Commit your changes (
git commit -m 'Add some AmazingFeature') - Push to the branch (
git push origin feature/AmazingFeature) - Open a Pull Request
License
This project is licensed under the MIT License - see the LICENSE file for details.
API Reference
MPesaClient
Initialization
from pesagateway import MPesaClient
client = MPesaClient(
consumer_key: str,
consumer_secret: str,
business_short_code: str,
pass_key: str,
environment: str = "sandbox"
)
Methods
STK Push
def stk_push(
phone_number: str,
amount: int,
account_reference: str,
transaction_desc: str
) -> dict:
"""
Initiates an STK push request to a customer's phone.
Args:
phone_number: Customer's phone number (format: 254XXXXXXXXX)
amount: Amount to be paid
account_reference: Unique reference for the transaction
transaction_desc: Description of the transaction
Returns:
dict: Response from M-Pesa API containing CheckoutRequestID
"""
C2B URL Registration
def c2b_register_urls(
confirmation_url: str,
validation_url: str
) -> dict:
"""
Registers confirmation and validation URLs for C2B transactions.
Args:
confirmation_url: URL that receives payment notifications
validation_url: URL that validates payment requests
Returns:
dict: Response from M-Pesa API
"""
B2C Payment
def b2c_payment(
phone_number: str,
amount: int,
remarks: str,
occasion: str = None
) -> dict:
"""
Initiates a Business to Customer payment.
Args:
phone_number: Recipient's phone number (format: 254XXXXXXXXX)
amount: Amount to send
remarks: Comments about the transaction
occasion: Optional occasion description
Returns:
dict: Response from M-Pesa API containing transaction details
"""
Query Transaction Status
def query_transaction_status(
checkout_request_id: str
) -> dict:
"""
Checks the status of a transaction.
Args:
checkout_request_id: The CheckoutRequestID from STK push
Returns:
dict: Response containing transaction status
"""
Query Account Balance
def query_account_balance() -> dict:
"""
Queries the account balance for the business.
Returns:
dict: Response containing account balance information
"""
Error Handling
The library defines several error types for specific scenarios:
MPesaError: Base exception class for all M-Pesa related errorsMPesaConnectionError: Raised when there are network connectivity issuesMPesaConfigError: Raised when there are configuration problemsMPesaValidationError: Raised when input validation failsMPesaAPIError: Raised when M-Pesa API returns an error response
Response Objects
All API methods return a dictionary containing the following standard fields:
{
"success": bool, # Whether the request was successful
"message": str, # Human-readable message
"data": dict, # The actual response data from M-Pesa
"error": str | None # Error message if success is False
}
For detailed response formats for each API endpoint, please refer to the M-Pesa API documentation.
Project details
Release history Release notifications | RSS feed
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
Source Distribution
Built Distribution
Filter files by name, interpreter, ABI, and platform.
If you're not sure about the file name format, learn more about wheel file names.
Copy a direct link to the current filters
File details
Details for the file pesa_gateway-0.0.12.tar.gz.
File metadata
- Download URL: pesa_gateway-0.0.12.tar.gz
- Upload date:
- Size: 9.9 kB
- Tags: Source
- Uploaded using Trusted Publishing? Yes
- Uploaded via: twine/6.1.0 CPython/3.12.9
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
c6d8f0ba96f169082c8bb70cd2b63027ee53a29ed66b73ce2a779b905b39117e
|
|
| MD5 |
13bef48130d28cbb61d00de5efde3d50
|
|
| BLAKE2b-256 |
8209c64860a166a6ec374cc572d1ddb9980d255cf9c48fe83af2e87c5c92d181
|
Provenance
The following attestation bundles were made for pesa_gateway-0.0.12.tar.gz:
Publisher:
release.yaml on thaka-creations/pesa-gateway
-
Statement:
-
Statement type:
https://in-toto.io/Statement/v1 -
Predicate type:
https://docs.pypi.org/attestations/publish/v1 -
Subject name:
pesa_gateway-0.0.12.tar.gz -
Subject digest:
c6d8f0ba96f169082c8bb70cd2b63027ee53a29ed66b73ce2a779b905b39117e - Sigstore transparency entry: 193833076
- Sigstore integration time:
-
Permalink:
thaka-creations/pesa-gateway@c19d420acef3ff08da3976f00d94fcb9ace16e99 -
Branch / Tag:
refs/tags/0.0.12 - Owner: https://github.com/thaka-creations
-
Access:
private
-
Token Issuer:
https://token.actions.githubusercontent.com -
Runner Environment:
github-hosted -
Publication workflow:
release.yaml@c19d420acef3ff08da3976f00d94fcb9ace16e99 -
Trigger Event:
push
-
Statement type:
File details
Details for the file pesa_gateway-0.0.12-py3-none-any.whl.
File metadata
- Download URL: pesa_gateway-0.0.12-py3-none-any.whl
- Upload date:
- Size: 9.7 kB
- Tags: Python 3
- Uploaded using Trusted Publishing? Yes
- Uploaded via: twine/6.1.0 CPython/3.12.9
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
997623b63785139c988f1f6d0dfb10beec2b88b635d6380308c77132b94cc9ac
|
|
| MD5 |
134e5ac3c3eadd541533feb39de8ec10
|
|
| BLAKE2b-256 |
1974821bf420d82eaee5e62d44edd37c446fc10ca15cf58c0fa0cbcc9d89ebbb
|
Provenance
The following attestation bundles were made for pesa_gateway-0.0.12-py3-none-any.whl:
Publisher:
release.yaml on thaka-creations/pesa-gateway
-
Statement:
-
Statement type:
https://in-toto.io/Statement/v1 -
Predicate type:
https://docs.pypi.org/attestations/publish/v1 -
Subject name:
pesa_gateway-0.0.12-py3-none-any.whl -
Subject digest:
997623b63785139c988f1f6d0dfb10beec2b88b635d6380308c77132b94cc9ac - Sigstore transparency entry: 193833079
- Sigstore integration time:
-
Permalink:
thaka-creations/pesa-gateway@c19d420acef3ff08da3976f00d94fcb9ace16e99 -
Branch / Tag:
refs/tags/0.0.12 - Owner: https://github.com/thaka-creations
-
Access:
private
-
Token Issuer:
https://token.actions.githubusercontent.com -
Runner Environment:
github-hosted -
Publication workflow:
release.yaml@c19d420acef3ff08da3976f00d94fcb9ace16e99 -
Trigger Event:
push
-
Statement type: