Skip to main content

Official Python SDK for Lipana M-Pesa API

Project description

Lipana Python SDK

Official Python SDK for the Lipana M-Pesa API. Type-safe, well-documented, and production-ready.

Version: 1.0.1
PyPI: https://pypi.org/project/lipana/
Documentation: https://lipana.dev/docs

Installation

pip install lipana

Or using poetry:

poetry add lipana

Quick Start

import os
from lipana import Lipana

# Initialize the SDK
lipana = Lipana(
    api_key=os.getenv('LIPANA_SECRET_KEY'),  # Use secret key for server-side
    environment='production'  # or 'sandbox' for testing
)

# Create a payment link
payment_link = lipana.payment_links.create(
    title='Premium Subscription',
    description='Monthly subscription to our premium features',
    amount=5000,
    currency='KES',
    allow_custom_amount=False,
    success_redirect_url='https://yourwebsite.com/success'
)

print(f'Payment link created: {payment_link["url"]}')

# Initiate STK push payment
stk_response = lipana.transactions.initiate_stk_push(
    phone='+254712345678',
    amount=5000
)

print(f'STK push initiated: {stk_response["transactionId"]}')

Features

  • Type Hints: Full type hint support for better IDE autocomplete
  • Error Handling: Comprehensive error handling with detailed error messages
  • Pythonic API: Clean, Pythonic interface following PEP 8 conventions
  • Webhooks: Built-in webhook signature verification utilities

API Reference

Transactions

# List all transactions
transactions = lipana.transactions.list(
    status='success',
    limit=50,
    start_date='2024-01-01',
    end_date='2024-12-31'
)

# Get a specific transaction
transaction = lipana.transactions.retrieve('txn_123456')

# Initiate STK push
stk_response = lipana.transactions.initiate_stk_push(
    phone='+254712345678',
    amount=5000
)

Payment Links

# Create a payment link
payment_link = lipana.payment_links.create(
    title='Premium Subscription',
    amount=5000,
    currency='KES'
)

# List payment links
payment_links = lipana.payment_links.list(
    status='active',
    limit=10
)

# Update a payment link
updated_link = lipana.payment_links.update('link_123456', {
    'status': 'inactive'
})

# Delete a payment link
lipana.payment_links.delete('link_123456')

Webhooks

# Get webhook settings
settings = lipana.webhooks.get_settings()

# Update webhook settings
lipana.webhooks.update_settings(
    webhook_url='https://yourwebsite.com/webhooks',
    enabled=True
)

# Verify webhook signature
is_valid = lipana.webhooks.verify(
    request_body,
    request_headers['x-lipana-signature'],
    os.getenv('LIPANA_WEBHOOK_SECRET')
)

API Keys

# List all API keys
api_keys = lipana.api_keys.list()

# Create a new API key
api_key = lipana.api_keys.create(
    name='Production Key',
    environment='production'
)

Error Handling

from lipana import Lipana, LipanaError

try:
    payment = lipana.transactions.initiate_stk_push(
        phone='+254712345678',
        amount=5000
    )
except LipanaError as error:
    if error.is_authentication_error():
        print(f'Authentication failed: {error.message}')
    elif error.is_validation_error():
        print(f'Validation error: {error.errors}')
    elif error.is_rate_limit_error():
        print('Rate limit exceeded')
    elif error.is_server_error():
        print(f'Server error: {error.message}')
    else:
        print(f'Error: {error.message}')

Configuration

Environment

The SDK supports two environments:

  • production: For live transactions (default)

    • Base URL: https://api.lipana.dev/v1
  • sandbox: For testing and development

    • Base URL: https://api-sandbox.lipana.dev/v1
lipana = Lipana(
    api_key=os.getenv('LIPANA_SECRET_KEY'),
    environment='sandbox'  # or 'production'
)

Custom Base URL

You can override the default base URL:

lipana = Lipana(
    api_key=os.getenv('LIPANA_SECRET_KEY'),
    base_url='https://custom-api.example.com/api'
)

Examples

Flask Webhook Handler

from flask import Flask, request, jsonify
from lipana import Lipana, LipanaError
import os

app = Flask(__name__)
lipana = Lipana(
    api_key=os.getenv('LIPANA_SECRET_KEY'),
    environment='production'
)

@app.route('/webhooks/lipana', methods=['POST'])
def webhook_handler():
    signature = request.headers.get('x-lipana-signature')
    secret = os.getenv('LIPANA_WEBHOOK_SECRET')
    
    if lipana.webhooks.verify(request.json, signature, secret):
        event = request.json.get('event')
        data = request.json.get('data')
        
        if event == 'transaction.success':
            print(f'Transaction succeeded: {data}')
        elif event == 'transaction.failed':
            print(f'Transaction failed: {data}')
        
        return jsonify({'received': True}), 200
    else:
        return jsonify({'error': 'Invalid signature'}), 401

Django View

from django.http import JsonResponse
from django.views.decorators.csrf import csrf_exempt
from lipana import Lipana
import os

lipana = Lipana(
    api_key=os.getenv('LIPANA_SECRET_KEY'),
    environment='production'
)

@csrf_exempt
def create_payment_link(request):
    if request.method == 'POST':
        try:
            payment_link = lipana.payment_links.create(
                title=request.POST.get('title'),
                amount=float(request.POST.get('amount')),
                currency='KES'
            )
            return JsonResponse(payment_link)
        except Exception as e:
            return JsonResponse({'error': str(e)}, status=500)
    return JsonResponse({'error': 'Method not allowed'}, status=405)

Requirements

  • Python >= 3.8
  • requests >= 2.28.0

Version History

1.0.1 (Current)

  • ✅ Updated base URLs to use /v1 endpoint
  • ✅ Production: https://api.lipana.dev/v1
  • ✅ Sandbox: https://api-sandbox.lipana.dev/v1

1.0.0

  • 🎉 Initial release
  • ✅ Full Python SDK implementation
  • ✅ All API endpoints supported
  • ✅ Webhook signature verification
  • ✅ Comprehensive error handling
  • ✅ Type hints support

License

MIT

Support

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

lipana-1.0.1.tar.gz (11.8 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

lipana-1.0.1-py3-none-any.whl (12.1 kB view details)

Uploaded Python 3

File details

Details for the file lipana-1.0.1.tar.gz.

File metadata

  • Download URL: lipana-1.0.1.tar.gz
  • Upload date:
  • Size: 11.8 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.9.6

File hashes

Hashes for lipana-1.0.1.tar.gz
Algorithm Hash digest
SHA256 a21b103576fe6e0db5991606d497a8c9044da460a8c86de094dc72b010e4a05e
MD5 8631bb7425c6df3dc8daa15e33f80f72
BLAKE2b-256 0dd57b8340acd3d2d9d7dee3dea537c14afcb5337f7745d9bd06316fa3e33bc6

See more details on using hashes here.

File details

Details for the file lipana-1.0.1-py3-none-any.whl.

File metadata

  • Download URL: lipana-1.0.1-py3-none-any.whl
  • Upload date:
  • Size: 12.1 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.9.6

File hashes

Hashes for lipana-1.0.1-py3-none-any.whl
Algorithm Hash digest
SHA256 7ff3ed3b29c62fb656712a4db56acf55e5255dd98208b673efca70fcb6f41dee
MD5 ca4ea84ea9ece39fa0bc08330479649c
BLAKE2b-256 0eec0ccaccad941fa2d3407de010fb7fcdda1a9a0eec6726f9c7b821d645d7b6

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page