bnjunge / MPESA-API-Tutorial

This is a Daraja API MPESA tutorial repo
MIT License
52 stars 67 forks source link

json response is None #5

Closed wwmwabini closed 3 years ago

wwmwabini commented 3 years ago

Am doing the MPESA intergration using Flask. I have followed each of the steps provided in the SurvTech Youtube videos and am getting expected outputs when registering URLs and when running simulation link. But my confirmation and validation URLs are returning None data type instead of the JSON with data. SO my confirm.json and validate.json have the words null instead of a details of a simulated transaction.

Am using localhost and tunneling requests using ngrok

Below is my code.

from flask import Flask, json, request
import requests
#import request
#import json
from requests.auth import HTTPBasicAuth
app = Flask(__name__)
consumer_key = 'mykey'
consumer_secret = 'mysecret'
api_URL = "https://sandbox.safaricom.co.ke/oauth/v1/generate?grant_type=client_credentials"
short_code = '600730'
#base_url = 'http://127.0.0.1/5003'
base_url = 'http://f3b896e27adb.ngrok.io'
@app.route("/")
def home():
    return "Hello World"
@app.route("/mpesa/access_token")
def get_access_token():
    data = (requests.get(api_URL, auth=HTTPBasicAuth(consumer_key, consumer_secret))).json()

    return data['access_token']
@app.route("/mpesa/register_urls/", methods=['GET', 'POST'])
def register_urls():
    mpesa_endpoint = 'https://sandbox.safaricom.co.ke/mpesa/c2b/v1/registerurl'
    access_token = get_access_token()
    req_headers = {
        "Authorization": "Bearer %s" %access_token
    }
    req_body = {
      "ShortCode": short_code,
      "ResponseType": "Completed ",
      "ConfirmationURL": base_url + "/confirmation/",
      "ValidationURL": base_url + "/validation/"}

    response = requests.post(mpesa_endpoint,
                             json=req_body,
                             headers=req_headers)
    return response.json()
@app.route('/confirmation/', methods=['GET', 'POST'])
def confirm():
    #data = request.get_json()
    data = request.json
    print(data)
    file = open('confirm.json', 'a')
    file.write(json.dumps(data))
    file.close()
    return {
        "ResultCode": 0,
        "ResultDesc": "Accepted"
    }
@app.route('/validation/', methods=['GET', 'POST'])
def validate():
    #data = request.get_json()
    data = request.json
    print(data)
    file = open('validate.json','a')
    file.write(json.dumps(data))
    file.close()
    return {
        "ResultCode": 0,
        "ResultDesc": "Accepted"
    }
@app.route('/simulation/')
def simulate():
    mpesa_sim_url = "https://sandbox.safaricom.co.ke/mpesa/c2b/v1/simulate"
    access_token = get_access_token()
    req_headers = {
        "Authorization": "Bearer %s" %access_token
    }
    req_body = {
        "ShortCode": "600730",
        "CommandID": "CustomerPayBillOnline",
        "BillRefNumber": "TestPay1",
        "Msisdn": "254708374149",
        "Amount": 100
                }

    sim_response = requests.post(mpesa_sim_url,
                             json=req_body,
                             headers=req_headers)
    return sim_response.json()
if __name__ == "__main__":
    app.run(debug=True, port=5003`

Sample response when I register URLs is

{
    "ConversationID": "",
    "OriginatorCoversationID": "",
    "ResponseDescription": "success"
}

Sample response when simulate transaction is

{
    "ConversationID": "AG_20210120_000044361980da3823ea",
    "OriginatorCoversationID": "19750-8617908-1",
    "ResponseDescription": "Accept the service request successfully."
}

What could I be missing that causes no data to be returned?

joseph-kangara commented 3 years ago

make sure to return a json response. if doesn't work, use a different domain