PAYMENTS

Collect Payments

We are going to send an MPesa checkout for Customer to Business (C2B) payment collection by running a script in the projectName folder, that we set up during the Setup and Dependencies session.

You should have created a payment product on the sandbox dashboard to interact with the Mobile B2C API.

In the projectName folder, create a script MobileC2B.py and copy-paste the code below. In the code we are sending the checkout in the following steps:

  1. Import the AfricasTalkingGateway class installed via pip
  2. Specify a product name, same as your Africa's Talking payment product
  3. Specify the phone number to checkout, the currency code and the amount to checkout
  4. Specify the metadata to be included with the payment notifications
  5. Create a gateway instance and authenticate by passing the username and api_key parameter
  6. Call the initiateMobilePaymentCheckout() method and pass the product name, phone number, currency code, amount and metadata

#-> projectName/MobileC2B.py

    # Import the helper gateway class
    from AfricasTalkingGateway import AfricasTalkingGateway, AfricasTalkingGatewayException
    #Specify your credentials
    username = "MyAfricasTalkingUsername"
    apiKey   = "MyAfricasTalkingApiKey"

    #Create an instance of our awesome gateway class and pass your credentials
    gateway = AfricasTalkingGateway(username, apiKey, "sandbox")

    # Specify the name of your Africa's Talking payment product
    productName  = "My Online Store"

    # The phone number of the customer
    phoneNumber  = "+254711XXXYYY"

    # The 3-Letter ISO currency code for the checkout amount
    currencyCode = "KES"

    # The checkout amount
    amount       = 100.50

    # This metadata will be  included when we send back the final payment notification
    metadata     = {"agentId"   : "654","productId" : "321"}
    try:
        # Initiate the checkout. If successful, you will get back a transactionId
        transactionId = gateway.initiateMobilePaymentCheckout(productName,
                                  phoneNumber,currencyCode,amount,metadata)
        print "The transactionId is " + transactionId

    except AfricasTalkingGatewayException, e:
        print "Received error response: %s" % str(e)

Fire up the simulator, register the same number as the number in your script ('+254711XXXYYY'). When you run your code you should see the Mpesa Checkout appear in the simulator.

Run your code to interact with the simulator:

python MobileC2B.py

results matching ""

    No results matching ""