Skip to content

Instantly share code, notes, and snippets.

@walteranyika
Last active November 17, 2023 11:05
Show Gist options
  • Save walteranyika/ead07918fdf7b3e17e8d6292e34f256c to your computer and use it in GitHub Desktop.
Save walteranyika/ead07918fdf7b3e17e8d6292e34f256c to your computer and use it in GitHub Desktop.
Quick Utility File To Handle STK Puush Mpesa
import json
from base64 import b64encode
from datetime import datetime
import requests
from requests.auth import HTTPBasicAuth
def get_access_token():
url = settings.MPESA_API["CREDENTIALS_URL"]
consumer_key = settings.MPESA_API["CONSUMER_KEY"]
consumer_secret = settings.MPESA_API["CONSUMER_SECRET"]
auth = HTTPBasicAuth(consumer_key, consumer_secret)
try:
response = requests.get(url, auth=auth)
except Exception as err:
raise err
else:
token = response.json()["access_token"]
return token
def generate_password():
timestamp = get_current_timestamp()
biz_short_code = get_business_shortcode()
passkey = settings.MPESA_API["PASS_KEY"]
password_string = biz_short_code + passkey + timestamp
encoded_bytes = password_string.encode("ascii")
password = b64encode(encoded_bytes).decode("utf-8")
return password
def get_current_timestamp():
return datetime.now().strftime('%Y%m%d%H%M%S')
def generate_request_headers():
token = get_access_token()
return {"Authorization": f"Bearer {token}"}
def get_business_shortcode():
return settings.MPESA_API["BIZ_SHORT_CODE"]
def get_payment_url():
return settings.MPESA_API["PAYMENT_URL"]
def get_callback_url():
return settings.MPESA_API["CALLBACK_URL"]
"""
Add this and modify inn your settings.py file
MPESA_API = {
"BIZ_SHORT_CODE": "174379",
"CALLBACK_URL": "xxxx",
"CONSUMER_KEY": "xxxx",
"CONSUMER_SECRET": "xxxx",
"CREDENTIALS_URL": "xxxx",
"PAYMENT_URL": "xxxx",
"PASS_KEY": "xxxxxx"
}
"""
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment