# Commerce Unified Payment Protocol Specifications (CUPP)

The Commerce Unified Payment Protocol (CUPP) aims to provide a standardized way to handle payments across UPI, IMPS, and other fiat networks in India. Below are the detailed specifications and code implementation in Node.js.

#### Overview of Commerce Unified Payment Protocol (CUPP)

**Objective:** To provide a standardized method for handling payments across UPI, IMPS, and other fiat networks in India, ensuring secure, transparent, and efficient transactions.

#### Key Components

1. **Payment Request Generation**
2. **Transaction Monitoring**
3. **Payment Confirmation**
4. **Notification Mechanism**
5. **Security Measures**
6. **Merchant Dashboard**

#### Detailed Specifications

**1. Payment Request Generation**

**Specifications:**

* Generate unique payment requests using UPI IDs, QR codes, or unique transaction IDs.
* Ensure that each transaction is identifiable through a unique identifier (e.g., transaction ID).

**Endpoints:**

* `POST /payment-intent`: Generate a payment request.

**2. Transaction Monitoring**

**Specifications:**

* Monitor UPI or IMPS networks for transactions corresponding to the generated payment requests.
* Use webhooks to receive notifications about transaction statuses.

**Endpoints:**

* `POST /webhook` Endpoint to receive transaction notifications.

**3. Payment Confirmation**

**Specifications:**

* Verify the transaction details with the UPI or IMPS or other networks.
* Ensure the transaction is confirmed before notifying the merchant.

**Endpoints:**

* `GET /payment-intent/:id` Verify the transaction status.

**4. Notification Mechanism**

**Specifications:**

* Notify the merchant of the payment status through webhooks or API calls.
* Ensure reliable delivery of notifications.

**Endpoints:**

* `POST /notify-merchant`: Notify the merchant about the transaction status.

**5. Security Measures**

**Specifications:**

* Encrypt sensitive data.
* Use secure methods for storing and transmitting transaction data.
* Implement multi-factor authentication (MFA) for accessing sensitive operations.

**6. Merchant Dashboard**

**Specifications:**

* Provide a dashboard for merchants to view transaction history, generate payment requests, and manage their accounts.

**Endpoints:**

* `GET /transactions`: Retrieve transaction history for a merchant.
* `POST /payment-intent`: Generate a new payment request.

//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

## CUPP Architecture

1. **Operator**: The central entity that manages payment requests and transactions.
2. **PaymentIntent**: Represents an intent to transfer funds from a customer to a merchant.
3. **PaymentMethod**: Defines various payment methods such as UPI, IMPS, etc.
4. **Webhook**: Mechanism to notify the merchant about transaction status updates.
5. **Security**: Ensures all transactions and communications are secure.

#### API Specifications

### **1. Create PaymentIntent**

**Endpoint**: `POST /payment-intent`

**Description**: Creates a new payment intent for a payment.

**Parameters**:

* `amount` (required): The amount to be paid.
* `currency` (required): The currency code (e.g., INR).
* `payment_method` (required): The payment method (UPI, IMPS, NEFT, RTGS, NETBANKING, etc).
* `merchant_id` (required): The identifier for the merchant.
* `callback_url` (optional): The URL to notify the merchant of the payment status.

**Response**:

* `payment_intent_id`: Unique identifier for the payment intent.
* `merchant_discount_rate`: Fee % charged by intermediaries for processing this payment.
* `payment_details`: Details or URL for completing the payment.

### **2. Get P**ayment**Intent Status**

**Endpoint**: `GET /payment-intent/:id`

**Description**: Retrieves the status of a payment intent.

**Parameters**:

* `id` (required): Unique identifier for the payment intent.

**Response**:

* `payment_intent_id`: Unique identifier for the payment intent.
* `status`: Status of the payment intent (e.g., PENDING, SUCCESS, FAILED).
* `status_message`: Message of the failed payment intent.
* `amount`: The amount involved in the payment.
* `currency` : The currency code of the amount (e.g., INR).
* `merchant_discount_rate`: Fee % charged by intermediaries for processing this payment.
* `settled_amount`: The amount being settled after deducting MDR.
* `settled_currency`: The currency code of the settled amount (e.g., INR).
* `merchant_id` : The identifier for the merchant.
* `callback_url` : The URL to notify the merchant of the payment status.
* `payment_method`: The payment method used.
* `payment_details`: Details or URL for completing the payment.
* `transaction_id`: The transaction ID from the payment network.

### **3. Webhook for Payment Status**

**Endpoint**: `POST /webhook`

**Description**: Endpoint to receive notifications about transaction status updates.

**Response**:

* `transaction_id` : Unique identifier for the transaction.
* `payment_intent_id` : Unique identifier for the payment intent.
* `status` : Status of the transaction (e.g., SUCCESS, FAILED).
* `amount` : The amount that was transacted.

### **4. Notification Mechanism**

**Description:**

* Notify the merchant of the payment status through webhooks or API calls to callback\_url.
* Ensure reliable delivery of notifications.

**Endpoints:**

* `POST /notify-merchant`: Notify the merchant about the transaction status.

**Parameters:**

* `transaction_details`: Details of the transaction.

### **5. Security Measures**

**Description:**

* Encrypt sensitive data.
* Use secure methods for storing and transmitting transaction data.
* Implement multi-factor authentication (MFA) for accessing sensitive operations.

### **6. Merchant Dashboard**

**Description:** Provide a dashboard for merchants to view transaction history, generate payment requests, and manage their accounts.

**Endpoints:**

* `GET /transactions`: Retrieve transaction history for a merchant.
* `POST /payment-intent`: Generate a new payment request.

###

#### Payment Transaction Results

When the payment is successful, a `Transferred` event is emitted by the network with details about:

* The operator address
* The unique id of the `PaymentIntent`
* The merchant (recipient) address
* The payer (sender) address
* The input currency/token that was spent by the payer
* The amount of the input currency/token spent by the payer

In the case of errors, a specific error type is returned with details about what went wrong.

#### Implementation in Node.js

Below is the Node.js implementation of the Commerce Unified Payment Protocol (CUPP) with the concepts of Operator, PaymentIntent, and Webhooks.

**Dependencies**

Install the required dependencies:

```bash
npm install express axios body-parser crypto mongoose
```

**Server Setup**

Create a server with the specified endpoints:

```javascript
const express = require('express');
const axios = require('axios');
const bodyParser = require('body-parser');
const crypto = require('crypto');
const mongoose = require('mongoose');

const app = express();
app.use(bodyParser.json());

// Connect to MongoDB
mongoose.connect('mongodb://localhost:27017/cupp', { useNewUrlParser: true, useUnifiedTopology: true });

// Define schemas
const MerchantSchema = new mongoose.Schema({
    id: String,
    webhook_url: String,
});

const PaymentIntentSchema = new mongoose.Schema({
    payment_intent_id: String,
    amount: Number,
    currency: String,
    payment_method: String,
    merchant_id: String,
    status: String,
    transaction_id: String,
    callback_url: String,
});

const Merchant = mongoose.model('Merchant', MerchantSchema);
const PaymentIntent = mongoose.model('PaymentIntent', PaymentIntentSchema);

// Endpoint to create a payment intent
app.post('/payment-intent', async (req, res) => {
    const { amount, currency, payment_method, merchant_id, callback_url } = req.body;
    const payment_intent_id = crypto.randomBytes(16).toString('hex');

    // Generate UPI URL or IMPS details based on payment_method
    let payment_details = '';
    if (payment_method === 'UPI') {
        const upi_id = 'merchant@upi';
        payment_details = `upi://pay?pa=${upi_id}&pn=MerchantName&am=${amount}&cu=INR&tn=${payment_intent_id}`;
    } else if (payment_method === 'IMPS') {
        // Generate IMPS payment details
        payment_details = `IMPS details for transaction ${payment_intent_id}`;
    }

    const paymentIntent = new PaymentIntent({
        payment_intent_id,
        amount,
        currency,
        payment_method,
        merchant_id,
        status: 'PENDING',
        callback_url: callback_url || '',
    });
    await paymentIntent.save();

    res.json({ payment_intent_id, payment_details });
});

// Endpoint to get payment intent status
app.get('/payment-intent/:id', async (req, res) => {
    const { id } = req.params;
    const paymentIntent = await PaymentIntent.findOne({ payment_intent_id: id });
    if (!paymentIntent) {
        return res.status(404).send('Payment Intent not found');
    }
    res.json(paymentIntent);
});

// Endpoint to handle payment status webhooks
app.post('/webhook', async (req, res) => {
    const { transaction_id, payment_intent_id, status, amount } = req.body;
    const paymentIntent = await PaymentIntent.findOne({ payment_intent_id });
    if (paymentIntent) {
        paymentIntent.status = status;
        paymentIntent.transaction_id = transaction_id;
        await paymentIntent.save();
        if (paymentIntent.callback_url) {
            notifyMerchant(paymentIntent);
        }
    }
    res.status(200).send('Event received');
});

// Notify merchant about transaction status
async function notifyMerchant(paymentIntent) {
    const { merchant_id, status, amount, transaction_id, callback_url } = paymentIntent;
    const merchant = await Merchant.findOne({ id: merchant_id });
    if (merchant) {
        axios.post(callback_url, {
            transaction_id,
            payment_intent_id: paymentIntent.payment_intent_id,
            status,
            amount,
        }).then(response => {
            console.log('Merchant notified successfully');
        }).catch(error => {
            console.log('Failed to notify merchant');
        });
    }
}

// Start the server
const port = 3000;
app.listen(port, () => {
    console.log(`Server running on port ${port}`);
});
```

#### Conclusion

By implementing the concepts of Operator, PaymentIntent, and Webhooks, the Commerce Unified Payment Protocol (CUPP) can provide a robust and standardized way to handle payments across UPI, IMPS, and other fiat networks in India. This approach ensures that transactions are secure, transparent, and efficient, making it easier for merchants to integrate and manage payments.&#x20;
