DEV Community

Odipo Otieno
Odipo Otieno

Posted on

User subscriptions to my project using mpesa

Sources: pypi.org (1)

To create a user subscription to your project using M-Pesa, you can follow these steps:

Install the django-mpesa package by running the following command in your terminal:

pip install django-mpesa
Enter fullscreen mode Exit fullscreen mode

Add 'mpesa' to your INSTALLED_APPS setting in your Django project's settings.py file.
Add the following M-Pesa configuration variables to your project's settings.py file:

CONSUMER_KEY = '<Your consumer key from daraja>'
CONSUMER_SECRET = '<Your consumer secret from daraja>'
HOST_NAME = '<Your hostname e.g https://myhostname>'
PASS_KEY = '<Your pass key from daraja>'
Enter fullscreen mode Exit fullscreen mode

In your Django view, you can use the mpesa_payment view provided by the django-mpesa package to initiate the payment process. Here's an example:

from mpesa.views import mpesa_payment

def subscribe(request):
    # Prepare the payment details
    payment_data = {
        'amount': 100,
        'description': 'Subscription to my project',
        'phone_number': request.user.phone_number,
        'callback_url': 'http://myhostname.com/callback/',
        'account_reference': request.user.username,
    }

    # Redirect the user to the M-Pesa payment page
    return mpesa_payment(request, payment_data)
Enter fullscreen mode Exit fullscreen mode

After the user completes the payment, M-Pesa will send a callback to the callback_url you provided in step 4. You can handle the callback in your view like this:

from mpesa.callbacks import mpesa_payment_callback

@mpesa_payment_callback
def handle_callback(request, payment_data, response_data):
    # Check the status of the payment
    if response_data['ResultCode'] == 0:
        # Payment was successful, so update the user's subscription status
        user = request.user
        user.is_subscribed = True
        user.save()

    return redirect('home')

Enter fullscreen mode Exit fullscreen mode

That's it! With these steps, you should be able to create a user subscription to your project using M-Pesa.

Note: You will need to replace the placeholders (e.g. ) with your actual M-Pesa credentials. Also, make sure to test your implementation thoroughly before deploying it to production.

Top comments (0)