Integrating KNET Payment Gateway into your Next.js application

I am attempting to incorporate the KNET payment gateway into my Next.js application, but I've struggled to locate any comprehensive documentation or examples to guide me through the process. Can someone offer assistance and suggest how to effectively integrate KNET with Javascript?

Answer №1

After conducting further research, I successfully implemented KNET into my Next.js project using the following approach:

import * as crypto from 'crypto'

const pkcs5Pad = (text: string) => {
  const blocksize = 16
  const pad = blocksize - (text.length % blocksize)

  return text + pad.toString().repeat(pad)
}

const aesEncrypt = (text: string, key: string) => {
  const AES_METHOD = 'aes-128-cbc'
  const content = pkcs5Pad(text)

  try {
    const cipher = crypto.createCipheriv(AES_METHOD, new Buffer(key), key)
    let encrypted = cipher.update(content)

    encrypted = Buffer.concat([encrypted, cipher.final()])

    return `${encrypted.toString('hex')}`
  } catch (err) {
    /* empty */
  }
}

const aesDecrypt = (text: string) => {
  const AES_METHOD = 'aes-128-cbc'
  const key = process.env.termResourceKey

  const decipher = crypto.createDecipheriv(
    AES_METHOD,
    new Buffer(key as string),
    key as string
  )
  const encryptedText = new Buffer(text, 'hex')
  let decrypted = decipher.update(encryptedText)

  decrypted = Buffer.concat([decrypted, decipher.final()])

  return decrypted.toString()
}

const initiateKnetPayment = () => {
  const kpayUrl = process.env.kpayUrl // Production URL: https://www.kpay.com.kw/kpg/PaymentHTTP.htm, Test URL: https://www.kpaytest.com.kw/kpg/PaymentHTTP.htm
  const tranportalId = process.env.tranportalId
  const tranportalPassword = process.env.tranportalPassword
  const termResourceKey = process.env.termResourceKey
  const responseUrl = process.env.kpayResponseUrl
  const errorUrl = process.env.kpayErrorUrl

  const paramData = {
    currencycode: '414',
    id: tranportalId,
    password: tranportalPassword,
    action: '1',
    langid: 'AR',
    amt: 20, // amount
    responseURL: responseUrl,
    errorURL: errorUrl,
    trackid: Math.random(),
    udf3: 12345678 // Customer identifier with 8 digits
  }

  let params = ''

  Object.keys(paramData).forEach((key) => {
    params += `${key}=${paramData[key as keyof typeof paramData]}&`
  })

  const encryptedParams = aesEncrypt(params, termResourceKey)

  params = `${encryptedParams}&tranportalId=${tranportalId}&responseURL=${responseUrl}&errorURL=${errorUrl}`

  const url = `${kpayUrl}?param=paymentInit&trandata=${params}`

  Router.push(url)
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Attempting to establish a connection between node.js and mongodb, receiving a positive response but failing to establish a successful connection

I have been working on setting up a mongodb database using mongoose in node.js by following various online tutorials. I have successfully managed to get the mongodb running and listening on port 27017. However, when I run my connection code in node.js, I a ...

The initial storage of a variable results in it being Undefined, but subsequent storage operations are successful. This process involves utilizing jQuery, Ajax, and

This is a snippet from a function: var editid; $("div.editable").click(function(e) { if ($currentInput == null) return; var css = GetCssProperties(); $(this).css(css); editid = $(this).attr("id"); $currentInpu ...

What approach would you take to create a navigation system similar to this?

Could you provide some advice on creating a navigation with similar features? I'm encountering some obstacles and would appreciate any suggestions on how to tackle this challenge. Attached is a transparent PNG showcasing one of the hover states. ...

Creating custom Bootstrap Card Groups by dynamically generating the specified number of cards with Angular directives

I am currently using Angular 9.1.8 for my project. For my Angular component, I have implemented Bootstrap Card Groups and Cards to display a large result set of cards in rows with more than two cards per row. Below are four example cards: <div class=&q ...

Is it preferable to include in the global scope or the local scope?

When it comes to requiring a node module, what is the best approach? Should one declare the module in the global scope for accuracy and clarity, or does declaring it in the local scope make more sense? Consider the following examples: Global: let dns = r ...

Achieve the identical outcome of the code in jQuery using React.js

Hey there! I'm currently exploring how to achieve similar results using React JS. I realize my request might seem a bit trivial, but I'm in the process of understanding how JavaScript and React JS can be connected in practical projects. Feel fr ...

Errors occur when dealing with higher order functions, such as the "map is

Struggling with higher order functions in JavaScript - I keep running into the error 'map is undefined'. Anyone able to offer some assistance? function mapper(f) { return function(a) { return map(a, f); }; } var increment = function(x) { re ...

What are some examples of MySQL node insertion queries with a pair of values?

I need help with my current JavaScript code snippet. var connection = mysql.createConnection({ host: 'localhost', user: 'root', password: 'root', database: 'codify', port: '8889' } ...

Adjusting an element to be at the top of the viewport using JavaScript

Is there a way to position an element at the top of the viewport instead of at the top of the page using a property or function? ...

While the React Router URL is functioning correctly, the corresponding component is not

I am experiencing an issue where React Router is changing the URL but the component is not being updated. I have tried various solutions from StackOverflow, however, none of them seem to work for me. Below is the code I am working with: App.js: function Ap ...

Are you experiencing issues with the AJAX auto-suggestion system displaying duplicate entries?

I've implemented a search bar on my website that allows users to search for specific titles. To enhance the user experience, I added an auto-completion feature using a simple MySQL table with suggested completions. Here's an image of the setup: ...

Exploring jQuery's Array Iteration Feature

Is there a way to create Custom Lists with a User-Friendly approach? For example: var unitA = []; unitA[0] = "Unit A One"; unitA[1] = "Unit A Two"; unitA[2] = "Unit A Three"; var unitB = []; unitB[0] = "Unit B One"; unitB[1] = "Unit B Two"; unitB[2] = " ...

What could be the reason for the page scrolling upwards when clicking on href="#"?

I am encountering an issue with a hyperlink <a href="#" id="someID">Link</a> that is located further down the page. This link is used to trigger an Ajax request, but whenever it is clicked, the page automatically scrolls back to the top. I have ...

Keep using .then() repeatedly for each item until finished

Let's say I have an array var numbers = [0, 1, 2] along with an $http request. My goal is to create a chain of .then() functions following the $http.get() for each item in the numbers array. So essentially, I want the code structure to look like thi ...

Where can I locate htmlWebpackPlugin.options.title in a Vue CLI 3 project or how can I configure it?

After creating my webpage using vue cli 3, I decided to add a title. Upon examining the public/index.html file, I discovered the code snippet <title><%= htmlWebpackPlugin.options.title %></title>. Can you guide me on how to change and cu ...

Continuously running React useEffect even with an empty dependency array

In my React application, I have implemented a hook system. Each sub-hook that is generated within this main hook is assigned a unique ID automatically. This ID is incremented by 1 every time a new sub-hook is created, ensuring uniqueness. const App = ...

Is it possible to make modifications to external Vue.js plugins directly within the component file that is importing them?

For instance, I have integrated vue-charts.js by importing it into my main component: import VueChartjs from 'vue-chartjs'; Vue.component('bar-chart', { extends: VueChartjs.HorizontalBar, ... }) Since VueChartjs is a wrapper for Ch ...

The error message "TypeError XXX is not a function in NodeJS" indicates that

As I attempt to enhance the testability of my NodeJS API by incorporating a service, a peculiar issue arises. Specifically, upon injecting the service (class), an error is triggered stating that the method getTasks() does not exist. ROUTE const TodoServi ...

Maintaining stability in Three.js: How to prevent an object from moving during zoom

In my application, I utilize Three.js for creating a 2D presentation. To achieve this, I set up an Orthographic camera with MapControls. Within the scene, there are various objects that can be panned and zoomed in and out in a 2D space. However, there is o ...

Displaying an 'undefined' message in a JavaScript alert box

Hello! Just made the switch from C#/C++ to JavaScript recently and I'm really enjoying it. I've encountered a behavior that has me scratching my head, can anyone help explain? So here's what's happening: when I run this script, I see ...