📅  最后修改于: 2023-12-03 14:44:24.426000             🧑  作者: Mango
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.
mpesa-python-sdk
library: A Python wrapper for the M-Pesa APIpaypalrestsdk
library: A Python wrapper for the PayPal APImpesa-python-sdk
and paypalrestsdk
libraries using pip:pip install mpesa-python-sdk paypalrestsdk
from mpesa.api.client import MpesaApiClient
from paypalrestsdk import Payment
mpesa_client = MpesaApiClient(
consumer_key='<your_mpesa_consumer_key>',
consumer_secret='<your_mpesa_consumer_secret>',
environment='sandbox'
)
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_client = paypalrestsdk.configure({
'mode': 'sandbox',
'client_id': '<your_paypal_client_id>',
'client_secret': '<your_paypal_client_secret>'
})
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
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
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.