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)
Please create an Account on (https://www.pythonanywhere.com/login/)
On above dashboard please click on Web From Main Menu Links at the Top, You will get a screen like below
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.
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
CREATE TABLE products ( product_name VARCHAR(50), product_desc TEXT, product_cost VARCHAR(50), image_url VARCHAR(200));
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');
We now go to set up our Python Files, From the Dashboard Click on Consoles Menu, From this Page click on Bash
pip install pymysql
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
You are Done.
My API is Up on this Link (https://modcom1.pythonanywhere.com/api/all)
[
{
"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"
}
]