image/svg+xml

Blog

A blog for entrepreneurs, innovators and changemakers to learn, scale and grow.

Introducing Xendit Python Library

Share on facebook
Share on twitter
Share on linkedin
Share on whatsapp
Phyton-logo

At Xendit, we focus on providing a smooth and positive experience for developers to integrate with Xendit quickly and simply. Our APIs are built to be user friendly, with SDKs in various languages such as PHP, Java, and NodeJS. We are pleased to share our latest release of Python language, with our Python library supporting the following APIs:

Accept Payments
  • Credit/Debit Cards API
  • e-Wallets API
  • QR Codes API
  • Direct Debit API
  • Virtual Accounts API
  • Retail Outlets API
  • Invoices API
  • Recurring API
  • Payouts API
  • Disbursements API
  • Batch Disbursements API

Xendit products are easy to use with fast and simple integration, try it out completely free! If you are currently using Python as your development environment, consider our Python library for a fuss-free integration to accept payments, send and manage invoices, send transfers and more! Our Python library also enables you to handle the low level HTTP calls for improved productivity, and so you can focus on building your own product.

Demo: Accept Payments via OVO e-wallet using Python

As an example, we will demonstrate an integration with Xendit Python Library with Flask, but you can use any framework of your choice. Here, we will be creating a form where users can input their details, for payment via their OVO e-Wallet, and processed with Xendit API. The same approach can be applied to other Xendit API products such as Cards, QR Codes, Direct Debit, etc. To see the full code, you can access it here.

Setup

Install Flask

First, we must create the project folder and add the required dependencies. Make sure that you have Python 3.7 or later in your environment. Python 3.7 ship with pip (Python Package Manager), so you should be able to use it immediately to install Xendit library.

mkdir sample-xendit-flask

pip install flask xendit-python
 

Create Xendit Account

You can register an account if you do not have one yet. Registration is FREE and you can try out all of our products in Test mode for FREE. Register here!

Setup Callback URL

Callback is a mechanism for Xendit to notify your application when payments have been completed or failed asynchronously. In order to setup callback, you’ll need a callback URL. Here’s how you can setup callback URL in 3 simple steps:

  1. Create temporary URL using webhook.site or ngrok
  2. Visit Xendit dashboard and go to Callback Settings page
  3. Save the URL in OVO paid section

In the latter part of the tutorial, we will explain how to integrate ngrok into our application.

Python Callback

Accept OVO Payments

Create Simple Payment Page

Let’s create a simple payment page to allow users to input their data to accept payments via OVO. 

Flask can render webpages from HTML using `render_template` in `templates` folder.  Let’s start by creating a `index.html` file. In `index.html`, we’ll create a simple payment page consists of form to allow user to input their name, amount, and phone number.

<!DOCTYPE html>
<html>
<head>
  <title>Sample Xendit Python</title>
</head>
<style>
  label {
    float: left;
    width: 10%;
  }
 
  input::-webkit-outer-spin-button,
  input::-webkit-inner-spin-button {
    -webkit-appearance: none;
    margin: 0;
  }
</style>
<body>
    <div>
      <h2>Pay using OVO</h2>
      <form action="/pay" method="post">
        <label for="name">Name: </label>
        <input type="text" id="name" name="name"><br>
        <label for="amount">Amount: </label>
        <input type="amount" id="amount" name="amount"><br>
        <label for="phone_number">Phone Number: </label>
        <input type="number" id="phone_number" name="phone_number"><br>
        <button type="submit">Submit</button>
      </form>
    </div>
</body>
</html> 

Next, we will create `app.py` file for our Flask application. Our Flask app will do these 3 things:

  • Render the HTML files
  • Process the payment creation
  • Handle webhook event

So the basic structure for the `app.py` would look like the following code:

import os
import time
 
from xendit import Xendit, XenditError
import xendit
from flask import Flask, request, render_template
 
app = Flask(__name__)
 
 
@app.route("/")
def index():
    return {}
 
 
@app.route("/pay", methods=["POST"])
def pay():
    return {}
 
@app.route("/webhook", methods=["GET"])
def catch_webhook():
    return {}
 
 
if __name__ == "__main__":
    app.run(debug=True)
 

To render the HTML file, we need to fill the `index()` function:

@app.route("/")
def index():
    return render_template("index.html") 

Let’s run `python.app.py` and the new payment page will look like this :

Python webpage

Integrate with eWallets API

Now we are ready to integrate the simple payment page with Xendit eWallets API to accept payments via OVO. Note that most Xendit APIs can only be processed through the backend and eWallets API is no exception.

Let’s start by getting the form’s entry in the `pay()` function and construct the arguments:

@app.route("/pay", methods=["POST"])
def pay():
    name = request.form.get("name")
    amount = request.form.get("amount")
    phone = request.form.get("phone_number")
    args = {
        "external_id": f"ovo-pay-{int(time.time())}",
        "amount": amount,
        "phone": phone,
    }
 

After that we will create a Xendit Instance to process the arguments. For the API Key, you can get in your Dashboard and store it in your environment. In this example, we already stored the api_key in `XENDIT_API_KEY` environment variable:

    xendit_instance = Xendit(api_key=os.getenv("XENDIT_API_KEY"))
    try:
        ovo_payment = xendit_instance.EWallet.create_ovo_payment(**args)
        return vars(ovo_payment)
    except XenditError as e:
        return vars(e) 

The completed functions would look like this:

@app.route("/pay", methods=["POST"])
def pay():
    name = request.form.get("name")
    amount = request.form.get("amount")
    phone = request.form.get("phone_number")
    args = {
        "external_id": f"ovo-pay-{int(time.time())}",
        "amount": amount,
        "phone": phone,
    }
    xendit_instance = Xendit(api_key=os.getenv("XENDIT_API_KEY"))
    try:
        ovo_payment = xendit_instance.EWallet.create_ovo_payment(**args)
        return vars(ovo_payment)
    except XenditError as e:
        return vars(e) 

Handle Callback (Optional)

If you use webhook.site as your callback url, you can skip this part. But if you want to receive the callback in the app directly, you need to use tools like ngrok so our running application can receive requests from Xendit server.

To see the our received request, we can print the request that the Xendit server sent in the `catch_webhook` method.

@app.route("/webhook", methods=["POST"])
def catch_webhook():
    print(request.json)
    return {} 

If you don’t have ngrok yet, you can download it from their website and follow the provided instructions to set up your ngrok. After that, we can start the ngrok application. Because our Flask default port is 5000, we need to run ‘ngrok http 5000’ in the terminal. The following screen would appear in the terminal after we successfully run the ngrok.

Notice the “https://4954c293a52d.ngrok.io” URL. It’s the base URL that we will use for our webhook. Now we can insert the url into our dashboard. Don’t forget that we designate `/webhook` as our endpoint, so we need to insert the full URL here.

Testing

Now that we have integrated with eWallets API, let’s test our implementation. Run the application using `python main.py`. Xendit provides you Testing Scenarios to test positive and negative scenarios. In this example, we’ll test the positive scenario as follow:

Webpage Test Python

Once the form has been submitted, your server will receive success response like this:

HTTP/1.1 200 OK
Content-Type: application/json

{
   “amount”: 50000,
   “business_id”: “5ed75086a883856178afc12e”,
   “created”: “2020-07-16T10:08:13.490Z”,
   “ewallet_type”: “OVO”,
   “external_id”: “ovo-pay-1594894091”,
   “phone”: “08123123123”,
   “status”: “PENDING”
}
 

User will be redirected to their OVO app to authorize payment. Once payment has been authorized, Xendit will notify the application via callback. The completed payment payload will look like this:

POST https://4954c293a52d.ngrok.io HTTP/1.1
Content-Type: application/json
X-Callback-Token: OTY1YTAyY2Q0Nzk4Y2NkNWM5MmNlNDQzNTMxNTEwMTMzMDYzMzE1

{
   “event”: “ewallet.payment”,
   “id”: “a962e7ab-9bb6-4e39-aa67-e43c565d7a7d”,
   “amount”: 50000,
   “business_id”: “5ed75086a883856178afc12e”,
   “created”: “2020-07-16T10:08:13.490Z”,
   “ewallet_type”: “OVO”,
   “external_id”: “ovo-pay-1594894091”,
   “phone”: “08123123123”,
   “status”: “COMPLETED”
}
 

Summary

We have successfully created a demo of how you can quickly and simply use Xendit’s Python library to accept e-Wallet payments. Start using Xendit products with our Python library. Visit PyPI or our Github library to see further guides.

Feel free to contribute or raise any requests, bugs, or comments by opening a Github issue or submit a pull request.

Share on facebook
Share on twitter
Share on linkedin
Share on whatsapp

Related posts