# PayIn

PayIn is Rocketfuel’s server-side integration flow for securely collecting payments from buyers. The SDK allows you to authenticate requests, create payment orders, open the hosted checkout page, and fetch transaction status using an order ID or Rocketfuel transaction ID.

It also includes utilities for verifying webhook signatures and validating age verification results, helping ensure your backend processes only trusted events.

### 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](/developer-guides/api-reference/payins/rocketfuel-ui-integration/webhooks.md#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.


---

# 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://docs.rocketfuel.inc/plug-ins-and-sdks/javascript-js/rocketfuel-sdk-nodejs/payin.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.
