import requests
from django.http import JsonResponse
from requests.auth import HTTPBasicAuth


def get_access_token(request):
    consumer_key = 'ovVH1R7FRfarkHwP7c7sta517O0KJfsk8TjsLtgv0sjwI0kt' 
    consumer_secret = 'zU6LTbXsjwqnaxG31bdEiw9FIFeyGHGZHg7m3D6CskMeYgNAuYxISsPs22Gt5o8x'
    api_URL = "https://sandbox.safaricom.co.ke/oauth/v1/generate?grant_type=client_credentials"
    headers = {'Content-Type': 'application/json'}
    auth = (consumer_key, consumer_secret)
    try:
        r = requests.get(api_URL, auth=HTTPBasicAuth(consumer_key, consumer_secret))
        json_response = (r.json())
        my_access_token = json_response["access_token"]
        access_token = my_access_token
        return JsonResponse({'access_token' :access_token})
    except requests.exceptions.RequestException as e:
        return JsonResponse({'error':str(e)})   
