📜  mpesa paypal - Python (1)

📅  最后修改于: 2023-12-03 14:44:24.426000             🧑  作者: Mango

M-Pesa PayPal Integration using Python

Introduction

M-Pesa is a popular mobile payment service in Kenya that allows users to send and receive money, pay bills, and purchase goods and services using their mobile phones. PayPal is a global payment system that allows users to make online payments, transfer money, and accept payments. In this tutorial, we will demonstrate how to integrate M-Pesa and PayPal using Python.

Requirements
  • Python 3.x
  • mpesa-python-sdk library: A Python wrapper for the M-Pesa API
  • paypalrestsdk library: A Python wrapper for the PayPal API
Setup
  • Install the mpesa-python-sdk and paypalrestsdk libraries using pip:
pip install mpesa-python-sdk paypalrestsdk
  • Import the necessary modules:
from mpesa.api.client import MpesaApiClient
from paypalrestsdk import Payment
M-Pesa Integration
  • Initialize the M-Pesa API client:
mpesa_client = MpesaApiClient(
    consumer_key='<your_mpesa_consumer_key>',
    consumer_secret='<your_mpesa_consumer_secret>',
    environment='sandbox'
)
  • Create a function that will initiate an M-Pesa transaction:
def initiate_mpesa_transaction(amount, recipient):
    response = mpesa_client.initiate_payment(
        amount=amount,
        phone_number=recipient,
        reference='payment'
    )
    transaction_id = response['ConversationID']
    return transaction_id
PayPal Integration
  • Initialize the PayPal API client:
paypal_client = paypalrestsdk.configure({
    'mode': 'sandbox',
    'client_id': '<your_paypal_client_id>',
    'client_secret': '<your_paypal_client_secret>'
})
  • Create a function that will create a PayPal payment:
def create_paypal_payment(amount):
    payment = Payment({
        'intent': 'sale',
        'payer': {
            'payment_method': 'paypal'
        },
        'redirect_urls': {
            'return_url': '<your_return_url>',
            'cancel_url': '<your_cancel_url>'
        },
        'transactions': [{
            'amount': {
                'total': amount,
                'currency': 'USD'
            }
        }]
    })
    if payment.create():
        return payment.id
    else:
        return None
Integration
  • Combine the M-Pesa and PayPal functions into a single function:
def initiate_payment(amount, recipient):
    mpesa_transaction_id = initiate_mpesa_transaction(amount, recipient)
    paypal_payment_id = create_paypal_payment(amount)
    return mpesa_transaction_id, paypal_payment_id
Conclusion

In this tutorial, we demonstrated how to integrate M-Pesa and PayPal using Python, using the mpesa-python-sdk and paypalrestsdk libraries. By combining the two, developers can enable their applications to accept mobile money payments and online payments from users.