Speed up your coding career with in depth case studies and coding tutorials from proven coders.

Paystack Inline: How to accept payments with just HTML

by Jeremiah Succeed on October 11, 2019
Paystack Inline: How to accept payments with just HTML

In this guide, you’ll learn how to integrate paystack payment system on your website, using the inline method.

If you read the introduction of the Paystack Master Series, then you should have a paystack account by now.

Just a reminder;

Before you can start integrating Paystack, you will need a Paystack account. Create a free account now if you haven’t already done so.

Let Dive In

Paystack has some approaches to integrate their API and collect payments on your websites. But this guide explains the Paystack Inline.

Paystack Inline

This is the simplest approach to accept credit card payment on any website. It can be integrated with a line of code thereby making it the easiest way to start accepting payments.

You don’t need to write any backend codes; Just plain HTML and JavaScript. So, anyone with a basic knowledge of HTML and JavaScript can easily do the integration.

Also, you can start and end the payment flow on the same page, you don’t have to redirect the user.

Let’s get started.

Create a new HTML file and enter the code below:

<form >
  <script src="https://js.paystack.co/v1/inline.js"></script>
  <button type="button" onclick="payWithPaystack()"> Pay </button> 
</form>

Now, the code above displays a Paystack Pay button. But, the Pay button is yet to do what is expected. If you click on it, nothing happens.

Normally, by clicking the Pay button, a nice looking Paystack Payment UI dialog will display for the users to enter their card details.

To do this, you need to add the payWithPaystack() JavaScript function below the form.

Here is the payWithPaystack JavaScript function provided by Paystack.

<!-- place below the html form -->
<script>
function payWithPaystack(){
  var handler = PaystackPop.setup({
    key: 'pk_test_86d32aa1nV4l1da7120ce530f0b221c3cb97cbcc',
    email: 'customer@email.com',
    amount: 10000,
    currency: "NGN",
    ref: ''+Math.floor((Math.random() * 1000000000) + 1), // generates a pseudo-unique reference. Please replace with a reference you generated. Or remove the line entirely so our API will generate one for you
    metadata: {
      custom_fields: [
        {
        display_name: "Mobile Number",
        variable_name: "mobile_number",
        value: "+2348012345678"
        }
      ]
    },
    callback: function(response){
        alert('success. transaction ref is ' + response.reference);
    },
    onClose: function(){
        alert('window closed');
    }
  });
  handler.openIframe();
}
</script>

Note that, you’ll need to replace the key: value ‘paste your key here’ with the public key on your Paystack Account Settings. Please use the public test key for testing purposes.

Now, if you click on the Pay button, the Payment Form will pop out.

Paystack payment form

You can test the payment with your debit card. Afraid? then use the test card option.

The test card option only works if you’re using the test public key. However don’t forget to replace the test public key with the live public key on a live website.

When a payment is successful, the browser will show an alert, indicating a successful transaction, with a reference key.

If you did everything correctly, great then, for you’ve just learned how to integrate the Paystack payment system on a website.

You can see how everything works on a single page. Also, notice the callback and onClose object key. The callback allows you to control the user experience within a callback function if the payment is successful.

Want to see how to control the user experience or see a custom real-world example? Then let build a simple payment page for a cheap Microphone I bought on AliExpress.

Microphone Payment Page

To have a good user experience, we will need two HTML pages.

microphone.html
success.html

The microphone.html is the actual microphone payment page. On this page we are going to display the product, price, customer information form, and a buy button.

The success.html is where the user will be redirected to after making a payment.

Now, create a page and name it microphone.html and enter the code below:

<html>
<head>
    <title>XIAOKOA Microphone Payment Page</title>
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css">
    <style>
    body {
        background-color: #f2f2f2;
    }
    </style>
</head>
<body>
    <div class="row  p-3 col-9 mx-auto bg-white mt-5">
        <div class="col-7">
            <h3>XIAOKOA CK Flexible USB Condenser Microphone</h3>
            <div class="row mt-4">
                <div class="col-7">
                    <img src="https://ae01.alicdn.com/kf/HTB1_hadX.CF3KVjSZJnq6znHFXap.jpg" class="img-fluid">
                </div>
                <div class="col-4 offset-1">
                  <h4>NGN 3300</h4> <strike>NGN 6600</strike>    -  <i>50%</i>
                </div>
            </div>
        </div>
        <div class="col-3 pt-3">
            <form id="paymentForm" class="form-horizontal">
                <input type="hidden" id="amount" value="3300">

                <div class="form-group">
                    <label for="firstname">First Name</label>
                    <input type="text" id="firstname" class="form-control" required/>
                </div> 
                <div class="form-group">
                    <label for="lastname">Last Name</label>
                    <input type="text" id="lastname" class="form-control" required/>
                </div> 
                <div class="form-group">
                    <label for="mobile">Mobile number</label>
                    <input type="text" id="mobile" class="form-control" required/>
                </div> 
                <div class="form-group">
                    <label for="email">Email Address</label>
                    <input type="email" id="email" class="form-control" required />
                </div>   
                <div class="form-submit">
                    <button type="submit" class="btn btn-success btn-lg"> BUY NOW</button> 
                </div>
            </form>
            <em>Ships to Nigeria</em>
        </div>
    </div>

</body>
</html>

I make use of bootstrap CDN to add some styling which works with an internet connection.

If you save and preview on a browser you’ll have a result similar to this:

Let’s now add the necessary payWithPaystack JavaScript function with a small change to how the function is been called.

Just the way we did it before, add the following JavaScript below the form.

<script src="https://js.paystack.co/v1/inline.js"></script>
<script>
  var form = document.getElementById('paymentForm');
  form.addEventListener('submit', payWithPaystack, false);

  function payWithPaystack(e) {
    e.preventDefault();
    var handler = PaystackPop.setup({
      key: 'pk_test_88cee3604d34e1fdccc09b0b58e3d8fb54881f83',
      email: document.getElementById('email').value,
      amount: document.getElementById('amount').value * 100,
      firstname: document.getElementById("firstname").value,
      lastname: document.getElementById("lastname").value,
      currency: "NGN",
      metadata: {
        custom_fields: [
          {
          display_name: "Mobile Number",
          variable_name: "mobile_number",
          value: document.getElementById('mobile').value
          }
        ]
      },
      callback: function(response) {
        window.location.href = 'success.html?ref=' + response.reference;
      },
      onClose: function() {
        alert('window closed');
      }
    });
    handler.openIframe();
  }
</script>

You’ll notice a few changes as compared to the one we use in the initial integration.

This time, we changed the way the payWithPaystack function is been called. Instead of adding an onclick attribute to the BUY button, we set an addEventListener to invoke the function when a user tries to submit the form.

form.addEventListener('submit', payWithPaystack, false);

Using document.getElementById to get the email, firstname, lastname, and mobile number from the form. This user information will be sent to your Paystack dashboard.

email: document.getElementById('email').value,
firstname: document.getElementById("firstname").value,
lastname: document.getElementById("lastname").value
...
value: document.getElementById('mobile').value

Also, the alert function was replaced with a redirection link to success.html which also pass along the payment reference.

window.location.href = 'success.html?ref=' + response.reference;

Create a file and name it success.html, then add the following code.

<div class="row p-5 col-9 mx-auto bg-white mt-5">
    <h1>Thank you for your patronage, you order will be shipped shortly.</h2>
</div>

I decided to exclude the other necessary HTML elements. If you noticed, I still used bootstrap.

Save your work and test. The process should be similar to the display below.

That’s it, we just built a simple payment page using Paystack.

Some Extras

I want to explain some important information if you’ll be taking Paystack seriously.

Amount

As a good observer, you’ll notice that in the first example we paid N100, but in the code the amount is 10000 (ten thousand Naira in figure).

amount: 10000,
...

Why?

From the Paystack documentation, the $amount is in Nigeria Kobo, so always add double zeros on any amount you are charging the customer. e.g 100000 for N1000.

That is the reason why I multiplied the amount by 100 in the microphone page example;

amount: document.getElementById('amount').value * 100,

Custom Fields

The custom field allows you to send some information with the payment.

custom_fields: [
  {
    display_name: "Mobile Number",
    variable_name: "mobile_number",
    value: document.getElementById('mobile').value
  }
]

An example: We asked the user to enter their mobile number in the microphone page, this mobile number will be sent as part of the transaction details to your dashboard.

image-showing-custom-mobile-number

If you’re selling multiple products, it will be good you know which product was purchased. These custom fields allow you to pass this data across.

Here is a plain to the eyes example:

HTML:

<input type="text" id="mobile" required/>
<input type="hidden" id="product-item" value="USB Microphone" />

JavaScript:

custom_fields: [
  {
    display_name: "Mobile Number",
    variable_name: "mobile_number",
    value: document.getElementById('mobile').value
  },
  {
    display_name: "Product Item",
    variable_name: "product_item",
    value: document.getElementById('product-item').value
  }
]

You can add as many as you want.

Here is a client site I help setup paystack. This site is on the blogger platform.

Support

I’d like to thank SitePoint for sponsoring this site. They provide fresh monthly Web design and development books and videos from experts like Chris Coyier and Tiffany Brown for a small fee of $9 monthly. They’ve been my favourite learning resource for years now, I’d certainly recommend them.

Reply

Thank you for taking the time to read. If you want to reply to this post, kindly reply the thread on Twitter.