# Nodejs Quick Start

## Prerequisite

To follow this tutorial, you need to have nodejs and a text editor of your choice installed on your computer.

## Init a nodejs application

Create a new folder, enter that folder, open your terminal, and run the command below to initialize a nodejs application

```
npm init -y
```

## Install the Dependencies

The following dependencies are needed for our app to work, express is a lightweight nodejs server, while `flow-merchant-sdk-beta` is our official nodejs SDK.

```bash
npm install flow-merchant-sdk-beta express nodemon
```

{% hint style="info" %}
Our SDK should only be used on the server side
{% endhint %}

## Get your Secret key

Your API requests are authenticated using API keys. Any request that doesn't include an API key will return an error.

You can generate an API key from your Dashboard at any time.

## Create Route Handlers

Create a file name  `index.js` this file will contain all our code, open that file with your text editor, and copy and paste the snippet below into that file.

In the code snippet below, created an instance of the flow merchant, passing our secret key as an argument. We created two important route handlers, `/pay` and `/webhook`

```javascript
const express = require("express")
const flowMerchant = require('flow-merchant-sdk-beta')

// initialize with the secret key
const FlowMerchant = new flowMerchant("sk_key_qfbb73swa1t7gl2bpayws4ssdiccr7dt")
const app = express()

// Body parser, reading data from body into req.body
app.use(express.json({ limit: '10mb' }));
app.use(express.urlencoded({ extended: true, limit: '10mb' }));

app.post("/pay", async(req, res) => {
  // payment route
})

app.post("/webhook", async(req, res) => {
  // webhook route
})

const port = process.env.PORT || 5000;

app.listen(port, () => {
  console.log(`App running on port ${port}...`);
});
```

Start the server by running the command below, this command restart the server when ever there is a file change.

```bash
nodemon index.js
```

## Request Payment

Add the following code snippet to the pay route handler, as shown below, In the code snippet we pass the request body into the `FlowMerchant.requestPay` function, that returns a promise.

```javascript
app.post("/pay", async(req, res) => {
    try {
        const body = req.body
        const response = await FlowMerchant.requestPay(body)
        const data = response?.data
        res.send({...data})
    } catch (e) {
        console.error(e)
        res.status(500).send("Error")
    }
})

```

The  `FlowMerchant.requestPay`  the method requires the following properties&#x20;

<table><thead><tr><th width="192">Property</th><th width="109">Required</th><th>Description</th></tr></thead><tbody><tr><td>amount</td><td>Yes</td><td>The amount of tokens needed</td></tr><tr><td>requestedToken</td><td>Yes</td><td><p>An integer that is either 0,1,2,3</p><p>0 : Flow Token,  1 : TUSD, 2 : TEUR, 3 : TGBP.</p></td></tr><tr><td>metadata</td><td>No</td><td>Object of any shape use in identifying a customer</td></tr><tr><td>redirectUrl</td><td>No</td><td>This is the URL you want to redirect the user to when their payment is successful.</td></tr></tbody></table>

A successful request will return a response like the one below, when you get this response you redirect the user to the payment link that has been generated.

```json
{
    "link": "https://flow-merchant.netlify.app/pay/0x4ecc01f88cfbb85d/gycnb87xhl901zvp",
    "transaction": {
        "id": 7,
        "tx_ref": "gycnb87xhl901zvp",
        "address": "0x4ecc01f88cfbb85d",
        "amount": "200",
        "amountPaid": "0",
        "narration": null,
        "source": "api",
        "status": "pending",
        "metadata": null,
        "requestedToken": 2,
        "createdAt": "2023-07-08T22:28:46.803Z",
        "paidAt": "2023-07-08T22:28:46.803Z"
    }
}
```

## Set your webhook endpoint

We use webhooks to send transaction results to your server once payment is made with our smart contract.

To set the webhook URL go to Integration Page and input your URL as shown below

<figure><img src="/files/a5oxEh3G73D5krEeYI6U" alt=""><figcaption><p>Setting Webhook</p></figcaption></figure>

## Verify Payment

Add the following code snippet to the `/webhook` route handler. When a transaction occurs, we send a post requests to the webhook URL, but this message needs to be verified to make sure it's comming from use, the `FlowMerchant.verifyPay` method do the verification for us, it returns a promise, a positive .

```json
app.post("/webhook", async(req, res) => {
    try {
        const response = await FlowMerchant.verifyPay(req.body)
        console.log(response)
        // Update Database
        res.send("success")
    } catch (e) {
        res.status(500).send(e)
    }
})
```

```json
{
  transaction: {
    id: 9,
    tx_ref: 'sgk2yxglzybx2u9q',
    address: '0x4ecc01f88cfbb85d',
    amount: '200',
    amountPaid: '200',
    narration: null,
    source: 'api',
    status: 'paid',
    metadata: { yes: '1' },
    requestedToken: 2,
    createdAt: '2023-07-08T23:39:57.635Z',
    paidAt: '2023-07-08T23:42:06.692Z'
  },
  payment: {
    id: 9,
    paymentId: '33',
    tx_ref: 'sgk2yxglzybx2u9q',
    amount: '200',
    requestedToken: 2,
    userId: null,
    createdAt: '2023-07-08T23:42:06.696Z'
  },
  signature: 'ac7c873cbb85eae4c9f4cb5d0ced8d6954cfbb4dbf6b5050eac76847611aa2d3'
}
```


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://flow-merchant.gitbook.io/flow-merchant/nodejs-quick-start.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
