[Python] Flask Integration with Mpesa Express STK results in Wrong credentials

Discussão em 'Python' iniciado por Stack, Março 22, 2025.

  1. Stack

    Stack Membro Participativo

    I am still testing my code under sandbox, therefore, I believe giving the consumer key and consumer secret for my application is not a security issue, because I can always delete and change. The main problem is that the STK Push results in the error: 'errorCode': '500.001.1001', 'errorMessage': 'Wrong credentials'. My full code is shown below and any assistance will be appreciated:

    import base64
    import datetime
    import json
    from requests.auth import HTTPBasicAuth # Correct authentication

    # Credentials
    consumer_key = "VehT7XXDuS8UVeLQkqOe3lTkFc14lFKtyssZBcAzBexwgcJG"
    consumer_secret = "OE9NWfYcW8JKeQ6v7FzObIEG8zjAJpQTDfKFARLAM0WX1Wy3dT9JM12Gxt92oKAz"

    # Business Details (Ensure correctness)
    shortcode = "174379" # 174379 for Safaricom sandbox
    passkey = "bfb279f9aa9bdbcf158e97dd71a467cd2f2c3e6c74a35d8b22a82e1a8ed2c919"

    # Generate timestamp
    timestamp = datetime.datetime.now().strftime("%Y%m%d%H%M%S")
    print(f" Timestamp: {timestamp}")

    # Generate Base64-encoded password
    password = base64.b64encode(f"{shortcode}{passkey}{timestamp}".encode()).decode()

    # Step 1: Get Access Token
    auth_url = "https://sandbox.safaricom.co.ke/oauth/v1/generate?grant_type=client_credentials"

    try:
    auth_response = requests.get(auth_url, auth=HTTPBasicAuth(consumer_key, consumer_secret))
    auth_response.raise_for_status() # Raise exception for HTTP errors
    auth_data = auth_response.json()
    access_token = auth_data.get("access_token")

    if not access_token:
    print("❌ ERROR: Access token missing from response.")
    exit()
    print(f"✅ Access Token: {access_token}")

    except requests.exceptions.RequestException as e:
    print(f"❌ ERROR: Failed to get access token: {e}")
    exit()

    # Step 2: Make STK Push Request
    stk_url = "https://sandbox.safaricom.co.ke/mpesa/stkpush/v1/processrequest"

    headers = {
    "Authorization": f"Bearer {access_token.strip()}",
    "Content-Type": "application/json"
    }

    payload = {
    "BusinessShortCode": shortcode,
    "Password": password,
    "Timestamp": timestamp,
    "TransactionType": "CustomerPayBillOnline",
    "Amount": "1", # Minimum for testing
    "PartyA": "254724290860", # Must be in international format
    "PartyB": shortcode,
    "PhoneNumber": "254724290860",
    "CallBackURL": "https://tobago-repository-hospitals-commented.trycloudflare.com/callback",
    "AccountReference": "Test",
    "TransactionDesc": "Payment"
    }

    print(" Sending STK Push Request...")

    try:
    response = requests.post(stk_url, json=payload, headers=headers)
    response.raise_for_status() # Raise an exception for HTTP errors

    response_json = response.json()
    print(" STK Push Response:", json.dumps(response_json, indent=4))

    except requests.exceptions.HTTPError as e:
    print(f"❌ HTTP ERROR: {e.response.status_code} - {e.response.text}")
    except requests.exceptions.RequestException as e:
    print(f"❌ ERROR: Failed to send STK Push request: {e}")
    except json.JSONDecodeError:
    print(f"❌ ERROR: Failed to parse JSON response:\n{response.text}")

    Continue reading...

Compartilhe esta Página