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.0
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/api
  • sandbox: For testing and development

    • Base URL: https://api-sandbox.lipana.dev/api
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.0 (Current)

  • 🎉 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.0.tar.gz (11.7 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.0-py3-none-any.whl (12.0 kB view details)

Uploaded Python 3

File details

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

File metadata

  • Download URL: lipana-1.0.0.tar.gz
  • Upload date:
  • Size: 11.7 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.0.tar.gz
Algorithm Hash digest
SHA256 41a5927670cbe297be4ecbcec4e099fb548d893ce517523563e187ac7a4af6e4
MD5 9ba9aefcb1bd198b215f7a926b4b1579
BLAKE2b-256 21ae780d069afbd5cdc8278c0ce3a168d08f805b4f0b8b8eb6311069a6c8650f

See more details on using hashes here.

File details

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

File metadata

  • Download URL: lipana-1.0.0-py3-none-any.whl
  • Upload date:
  • Size: 12.0 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.0-py3-none-any.whl
Algorithm Hash digest
SHA256 725b5f6429c255656783aeb0b9463732624627f330217ee0f90370450be9a5b9
MD5 151ff0df0130005396433bde3d46e5ed
BLAKE2b-256 dc6b1b6d25590672ea38e8871a8981b842b8f0d29b69fea2e2b16e98aed8092a

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