Skip to content

modcomlearning/pythonapi

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

16 Commits
 
 
 
 
 
 

Repository files navigation

Python API to Retrieve Products and Make MPESA Payment.

In this session we are creating an API to used by an Android Mobile App check the Mobile App that uses this API on this link

(https://github.com/modcomlearning/shop)

Step 1

Please create an Account on (https://www.pythonanywhere.com/login/)

q1

Step 2

Once You have an Account please Login to access your Dashboard.

q2

On above dashboard please click on Web From Main Menu Links at the Top, You will get a screen like below

q3

Step 3

Click on 'Add A New Web App' from the left side.

Please Follow the steps as shown in below screenshots until you create a web App.

Next

q3

Next

q4

Select Flask

q5

Select Python 3.9

q6

Next

q7

Next

q8

NB: on above screen please see the link of your API. in my case (modcom1.pythonanywhere.com), this page will also help to be reloading our Page.

Step 4

Creating the Database, From the dashboard, click Databases From the TOP BAR, Setup database passwords and Press Initialize, NB: Please save the host, username, password, and database name

You get into below Page, Here we can see a database with default name i.e yourusername$databasname.

Below page appears,

q10

Click on the defaul database and a console appears, see below screen.

q11

Step 5

After the console finishes loading enter below SQL command to create atable.

CREATE TABLE products ( product_name VARCHAR(50), product_desc TEXT, product_cost VARCHAR(50), image_url VARCHAR(200));

q13

Step 6

After this Insert a New Record to your products table using below command.

insert into  products ( product_name, product_desc, product_cost, image_url) values('Nice Table', 'This is a nice table for your house', '3500', 'https://modcom.co.ke/pics/furniture1.jpeg');

q14

You can now use select query to see the table you just created and its data.

q15

You are Done Setting up a Database! Add more Records using the Insert Query.

Step 7

We now go to set up our Python Files, From the Dashboard Click on Consoles Menu, From this Page click on Bash

q16

q17

Write below command to install pymysql

pip install pymysql

q18

Step 8

Now go to Files Menu. Click on mysite and you will see flask_app.py.

q19

20

In this File enter below code and Save.

from flask import *
import requests
app = Flask(__name__)
import pymysql

# Your routes
@app.route('/api/all')
def all():
    # Change DB connection to yours
    con = pymysql.connect(host='Modcom.mysql.pythonanywhere-services.com', user='Modcom', password='2491Mod@#$',
                          database='Modcom$default')
    cursor = con.cursor(pymysql.cursors.DictCursor)
    sql = "select * from products"
    cursor.execute(sql)
    rows = cursor.fetchall()
    return jsonify(rows)




import datetime
import base64
from requests.auth import HTTPBasicAuth
@app.route('/mpesa_payment', methods = ['POST'])
def mpesa_payment():
        #if request.method == 'POST':
            from flask import request
            json = request.json
            amount = json['amount']
            phone = json['phone']
            # GENERATING THE ACCESS TOKEN
            consumer_key = "GTWADFxIpUfDoNikNGqq1C3023evM6UH"
            consumer_secret = "amFbAoUByPV2rM5A"

            api_URL = "https://sandbox.safaricom.co.ke/oauth/v1/generate?grant_type=client_credentials" #AUTH URL
            r = requests.get(api_URL, auth=HTTPBasicAuth(consumer_key, consumer_secret))

            data = r.json()
            access_token = "Bearer" + ' ' + data['access_token']

            #  GETTING THE PASSWORD
            timestamp = datetime.datetime.today().strftime('%Y%m%d%H%M%S')
            passkey = 'bfb279f9aa9bdbcf158e97dd71a467cd2e0c893059b10f78e6b72ada1ed2c919'
            business_short_code = "174379"
            data = business_short_code + passkey + timestamp
            encoded = base64.b64encode(data.encode())
            password = encoded.decode('utf-8')


            # BODY OR PAYLOAD
            payload = {
                "BusinessShortCode": "174379",
                "Password": "{}".format(password),
                "Timestamp": "{}".format(timestamp),
                "TransactionType": "CustomerPayBillOnline",
                "Amount": amount,  # use 1 when testing
                "PartyA": phone,  # change to your number
                "PartyB": "174379",
                "PhoneNumber": phone,
                "CallBackURL": "https://modcom.co.ke/job/confirmation.php",
                "AccountReference": "account",
                "TransactionDesc": "account"
            }

            # POPULAING THE HTTP HEADER
            headers = {
                "Authorization": access_token,
                "Content-Type": "application/json"
            }

            url = "https://sandbox.safaricom.co.ke/mpesa/stkpush/v1/processrequest" #C2B URL

            response = requests.post(url, json=payload, headers=headers)
            print (response.text)
            response = jsonify({"sucess":"Paid {} - {}".format(phone, amount)})
            response.status_code = 200
            return response

NB: Please note you need to change your Database connections.

You are Done.

Step 9

Go to Web Menu and Reload your application, The Green Button

21

My API is Up on this Link (https://modcom1.pythonanywhere.com/api/all)

Looks something Like below

[
  {
    "image_url": "https://modcom.co.ke/pics/furniture1.jpeg",
    "product_cost": "3500",
    "product_desc": "This is a nice table for your house",
    "product_name": "Nice Table"
  }
]

Thank you, Glad You Manged to Set Up Your API!

Please Follow Our Github Repository For More Codes (https://github.com/modcomlearning)

About

No description, website, or topics provided.

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Languages