# Rocketfuel SDK nodejs

## Rocketfuel Node.js SDK Integration Guide <a href="#undefined" id="undefined"></a>

This document provides a step-by-step guide for integrating Rocketfuel’s Node.js SDK (`rocketfuel-sdk`) to generate invoices and perform purchase checks in your application.

### Prerequisites <a href="#undefined" id="undefined"></a>

* Node.js installed
* An active Rocketfuel account with access credentials:
  * `CLIENT_ID`
  * `CLIENT_SECRET`
  * `MERCHANT_ID`

1. **You can installed the Rocketfuel Node.js SDK:**

<pre class="language-bash"><code class="lang-bash"><strong>npm install @rkfl/transact-server
</strong></code></pre>

```javascript
import { Rocketfuel } from '@rkfl/transact-server';
```

2. **Reading Credentials from Environment Variables**

Use environment variables for security and flexibility.

```javascript
export const CLIENT_ID = process.env.CLIENT_ID;
export const CLIENT_SECRET = process.env.CLIENT_SECRET;
export const MERCHANT_ID = process.env.MERCHANT_ID;
```

3. **Initializing the Rocketfuel Client**

Initialize the `RocketfuelClient` with appropriate parameters:

```javascript
const client = new Rocketfuel({
  clientId: CLIENT_ID,
  clientSecret: CLIENT_SECRET,
  merchantId: MERCHANT_ID,
  environment: 'sandbox', // or 'production'
});
```

## Functions

### 1. Generate Order

```javascript
export const generateUUID = async (req, res) => {
  try {
    const payload = req.body;
    console.log(payload);

    // Call Rocketfuel purchase check API
    const result = await client.createOrder(payload);
    console.log('Hosted Page Result:', result.uuid);

    // Send success response with uuid and it can be used with the frontend sdk
    res.json({ success: true, uuid: result.uuid });
  } catch (err) {
    console.log('Error in generateInvoice:', err);

    // Send failure response with error message
    res.status(500).json({ success: false, error: err.message || 'Internal Server Error' });
  }
};
```

#### Cart payload example

```json
{
  "merchant_id": "b682f8e6-4df8-ae7f-6f94era353d2", // required
  "amount": "59.99", // required
  "cart": [
    {
      "id": "vid1", // required
      "price": 19.99,   // required
      "name": "Amazing Nature Documentary",  // required
      "quantity": 2,    // required
      "key": 101, // optional
      "totalPrice": 39.98, // optional
      "isSubscription": false, // optional
      "frequency": "monthly", // optional
      "subscriptionPeriod": "1m", // optional
      "merchantSubscriptionId": "sub-12345", // optional
      "autoRenewal": true, // optional
      "isSubscriptionRenewal": false, // optional
      "subscriptionId": null, // optional
      "refundable": true // optional (default true if omitted)
    },
  ],
  "currency": "USD", // required
  "order": "ORD-2024-0001", // optional
  "redirectUrl": "https://example.com/return", // optional
  "customerInfo": {
    "name": "John Doe", // optional (whole object)
    "email": "john.doe@example.com", // optional
    "phone": "+1234567890", // optional
    "address": "123 Main Street, NY", // optional
    "allowLoginWithoutEmail": true, // optional
    "userIdentifier": "user-001" // optional
  },
  "shippingAddress": { // optional (whole object)
    "firstname": "John", // optional
    "lastname": "Doe", // optional
    "phoneNo": "+1234567890", // optional
    "address1": "123 Main Street",
    "address2": "Apt 4B", // optional
    "state": "NY",
    "city": "New York",
    "zipcode": "10001", // optional
    "country": "USA",
    "landmark": "Near Central Park", // optional
    "email": "john.doe@example.com" // optional
  },
  "customParameter": { // optional
    "returnMethod": "POST",
    "params": [
      { "name": "submerchant", "value": "streamflix" }
    ]
  },
  "feeConfiguration": { // optional
    "type": "PERCENT",
    "value": 2.5 // optional (default 0 if omitted)
  },
  "siteInfo": { // optional
    "siteUrl": "https://exmaple.com", // optional
    "siteName": "StreamFlix", // optional
    "siteLogo": "https://exmaple.com/logo.png" // optional
  },
}
 
```

#### Root Level Fields

| Field            | Type   | Required | Description                                              |
| ---------------- | ------ | -------- | -------------------------------------------------------- |
| merchant\_id     | string | ✅ Yes    | Unique identifier of the merchant.                       |
| amount           | string | ✅ Yes    | Total amount of the transaction.                         |
| cart             | array  | ✅ Yes    | List of items in the cart.                               |
| currency         | string | ✅ Yes    | Currency code (e.g., USD).                               |
| order            | string | ❌ No     | Merchant’s order reference/ID.                           |
| redirectUrl      | string | ❌ No     | URL where the customer will be redirected after payment. |
| customerInfo     | object | ❌ No     | Information about the customer.                          |
| shippingAddress  | object | ❌ No     | Shipping address details.                                |
| customParameter  | object | ❌ No     | Custom key-value pairs for callback or extra data.       |
| feeConfiguration | object | ❌ No     | Fee-related configuration for the transaction.           |
| siteInfo         | object | ❌ No     | Website or platform information.                         |

#### Cart Object (cart\[])

| Field                  | Type         | Required | Description                                        |
| ---------------------- | ------------ | -------- | -------------------------------------------------- |
| id                     | string       | ✅ Yes    | Unique identifier for the product/item.            |
| price                  | number       | ✅ Yes    | Price of a single unit.                            |
| name                   | string       | ✅ Yes    | Name/description of the product.                   |
| quantity               | number       | ✅ Yes    | Number of units purchased.                         |
| key                    | number       | ❌ No     | Custom product key/reference.                      |
| totalPrice             | number       | ❌ No     | Total price (price \* quantity).                   |
| isSubscription         | boolean      | ❌ No     | Whether this item is a subscription.               |
| frequency              | string       | ❌ No     | Subscription frequency (e.g., monthly).            |
| subscriptionPeriod     | string       | ❌ No     | Subscription period (e.g., 1m).                    |
| merchantSubscriptionId | string       | ❌ No     | Merchant’s subscription reference ID.              |
| autoRenewal            | boolean      | ❌ No     | Whether subscription will auto-renew.              |
| isSubscriptionRenewal  | boolean      | ❌ No     | Marks if this is a renewal payment.                |
| subscriptionId         | string\|null | ❌ No     | Unique identifier of the subscription (if exists). |
| refundable             | boolean      | ❌ No     | Whether item is refundable (default: true).        |

#### Customer Info (customerInfo)

| Field                  | Type    | Required | Description                            |
| ---------------------- | ------- | -------- | -------------------------------------- |
| name                   | string  | ❌ No     | Customer’s full name.                  |
| email                  | string  | ❌ No     | Customer’s email address.              |
| phone                  | string  | ❌ No     | Customer’s phone number.               |
| address                | string  | ❌ No     | Customer’s address.                    |
| allowLoginWithoutEmail | boolean | ❌ No     | Allow login without requiring email.   |
| userIdentifier         | string  | ❌ No     | Custom unique identifier for customer. |

#### Shipping Address (shippingAddress)

| Field     | Type   | Required | Description                       |
| --------- | ------ | -------- | --------------------------------- |
| firstname | string | ❌ No     | Recipient’s first name.           |
| lastname  | string | ❌ No     | Recipient’s last name.            |
| phoneNo   | string | ❌ No     | Recipient’s phone number.         |
| address1  | string | ✅ Yes    | Street address line 1.            |
| address2  | string | ❌ No     | Street address line 2 (optional). |
| state     | string | ✅ Yes    | State/Province.                   |
| city      | string | ✅ Yes    | City name.                        |
| zipcode   | string | ❌ No     | Postal code.                      |
| country   | string | ✅ Yes    | Country name.                     |
| landmark  | string | ❌ No     | Landmark for easier delivery.     |
| email     | string | ❌ No     | Recipient’s email.                |

#### Custom Parameter (customParameter)

| Field        | Type   | Required | Description                          |
| ------------ | ------ | -------- | ------------------------------------ |
| returnMethod | string | ❌ No     | Callback method (e.g., POST).        |
| params       | array  | ❌ No     | Extra parameters as key-value pairs. |

**Params Object**

| Field | Type   | Required | Description      |
| ----- | ------ | -------- | ---------------- |
| name  | string | ✅ Yes    | Parameter key.   |
| value | string | ✅ Yes    | Parameter value. |

#### Fee Configuration (feeConfiguration)

| Field | Type   | Required | Description                  |
| ----- | ------ | -------- | ---------------------------- |
| type  | string | ❌ No     | Type of fee (e.g., PERCENT). |
| value | number | ❌ No     | Fee value (default: 0).      |

#### Site Info (siteInfo)

| Field    | Type   | Required | Description     |
| -------- | ------ | -------- | --------------- |
| siteUrl  | string | ❌ No     | Website URL.    |
| siteName | string | ❌ No     | Website name.   |
| siteLogo | string | ❌ No     | Logo image URL. |

### 2. Transaction lookup

The `transactionLookup` Function is an asynchronous method that lets you retrieve details about a specific transaction from Rocketfuel’s API. You provide a transaction ID (`txId`) and specify the type of ID (`'ORDERID'` or `'TXID'`). The function ensures you have a valid access token, then makes a POST request to the transaction lookup endpoint.

* **Input parameters:**
  * `txId`: The identifier for the transaction you want to look up.
  * `type`: (Optional) Specifies if `txId` it is an order ID (`'ORDERID'`) or transaction ID (`'TXID'`). Defaults to `'ORDERID'`.
* **Purpose:**\
  Use this to verify transaction status, get payment info, or troubleshoot payments.

**Usage Example**

Assuming you have an instance of your SDK client (e.g., named `client`) that includes the `transactionLookup` method:

```javascript
async function checkTransaction(txId) {
  try {
    const result = await client.transactionLookup(txId, 'ORDERID');
    console.log('Transaction Details:', result);
    // Process the transaction details as needed
  } catch (error) {
    console.error('Error fetching transaction details:', error.message);
  }
}

// Example call:
checkTransaction('12345ABC');
```

* Replace `'12345ABC'` with the actual order ID or transaction ID.
* Change `'ORDERID'` to `'TXID'` If you are using the transaction ID.\\

### 3. Webhook Signature Verification

The `verifyWebhookSignature` Function is a synchronous method that ensures the authenticity and integrity of incoming webhook payloads sent by Rocketfuel. It uses **RSA-SHA256** to verify that the payload hasn’t been tampered with and was genuinely sent from Rocketfuel’s backend.

{% hint style="info" %}
For more information, you can refer to this link to retrieve the transaction status for any received webhooks: [RocketFuel Webhook Documentation](https://docs.rocketfuel.inc/developer-guides/api-reference/payins/rocketfuel-ui-integration/webhooks#markdown-header-rocketfuel-webhook-and-events)
{% endhint %}

**Input Parameters**

* **`body`**: The full parsed JSON object received in the webhook request. It must contain:

**Purpose**

Use this function to **verify that a webhook is valid and trusted** before processing its contents. It prevents spoofed requests, data tampering, and unauthorized events.

**Usage Example**

Assuming you have an instance of your SDK client (e.g., named `client`) that includes the `verifyWebhookSignature` method:

```ts
function handleWebhook(req, res) {
  const isValid = client.verifyWebhookSignature(req.body);

  if (!isValid) {
    console.warn('Webhook signature verification failed');
    return res.status(403).send('Invalid signature');
  }

  const payload = JSON.parse(req.body.data.data);
  console.log('Verified Webhook Payload:', payload);

  // Process your payload
  res.status(200).send('Webhook received');
}
```

> Make sure `req.body` is already parsed into an object. If you're using Express, use a raw body parser middleware to retain the exact content for verification if needed.

### 4. Age Verification Status

The `verifyAgeVerification` function is an asynchronous method that checks the status of an age verification request by using the unique **audit ID** generated during the verification process. It communicates with RocketFuel’s backend to determine whether the user has successfully completed age verification.\
Use this function to confirm whether a user has passed or failed age verification. This is essential when handling age-restricted products or services, ensuring compliance with legal and regulatory requirements.

**Input Parameters**

* **auditId**: `string`\
  The unique identifier of the audit log that was created when the age verification attempt was initiated.

**Usage Example**

Assuming you have an instance of your SDK client (e.g., named `client`) that includes the `verifyAgeVerification` method:

```javascript
async function checkAgeVerification(auditId: string) {
  try {
    const result = await client.verifyAgeVerification(auditId);
    console.log("✅ User age verified successfully:", result);
  } catch (error) {
    console.error("Error verifying age:", error);
  }
}

```

**Response**

```json
{
    "id": "d27d3b78-cd99-42f9-87f6-2a17b01f7820",
    "status": "status_verified",
    "verifiedOn": "2025-09-10T17:59:37.002Z",
    "createdAt": "2025-09-10T17:59:21.122Z",
    "timezone": "UTC"
}
```

| Field        | Type                  | Description                                                                     |
| ------------ | --------------------- | ------------------------------------------------------------------------------- |
| `id`         | string                | Unique identifier of the verification record (audit ID).                        |
| `status`     | string                | Current verification status (see **Status Values** below).                      |
| `verifiedOn` | string (ISO datetime) | Timestamp when the user was successfully verified (only available if verified). |
| `createdAt`  | string (ISO datetime) | Timestamp when the verification request was created.                            |
| `timezone`   | string                | Timezone used in the verification process.                                      |

| Status             | Description                                                                |
| ------------------ | -------------------------------------------------------------------------- |
| `expired`          | The verification session expired before completion.                        |
| `status_initiated` | Age verification process has started but not yet completed.                |
| `status_verified`  | User successfully completed age verification.                              |
| `status_failed`    | Age verification attempt failed.                                           |
| `widget_started`   | The verification widget was launched, but final status not yet determined. |

**📌 Notes**

* This function returns `true` if the signature is valid, otherwise `false`.
* Your webhook endpoint must always return a successful response (e.g., HTTP 200), as Rocketfuel verifies the endpoint only once during registration through the merchant dashboard.
