# UPIDrop — Wix Integration Guide

Connect UPIDrop Zero-Fee UPI payments to your Wix online store or website.

---

## Overview

UPIDrop enables Wix merchants in India to accept UPI payments directly into their current or savings bank account with **zero gateway fees (0%)**, automated reconciliation via SmartTrack, and instant customer checkout.

You can integrate UPIDrop with Wix using two approaches:

| Approach | Best For | Requirement | Setup Time |
| :--- | :--- | :--- | :--- |
| **Method 1: Wix Velo Payment Provider SPI** | Complete Wix Stores checkout integration | Wix Premium Plan (Velo enabled) | ~10 minutes |
| **Method 2: Wix HTML / Custom Element Embed** | Landing pages, one-click buy buttons, donations | Any Wix Plan | ~3 minutes |

---

## Method 1: Wix Velo Payment Provider SPI (Full Store Checkout)

The Service Provider Interface (SPI) allows UPIDrop to function as an official payment provider directly inside the native Wix Stores checkout flow.

### Prerequisites
1. A Wix site with a Premium plan (enabling Velo backend code).
2. A verified UPIDrop merchant account ([https://upidrop.roori.in](https://upidrop.roori.in)).
3. Your UPIDrop **Public Key** (`pk_live_...`) and **Webhook Secret** (`whsec_...`).

---

### Step 1: Enable Velo Developer Mode
1. Open your site in the **Wix Studio** or **Wix Editor**.
2. In the top navigation bar, click **Dev Mode** → **Turn on Dev Mode**.

---

### Step 2: Store Your API Keys in Wix Secrets Manager
Never expose your API credentials in frontend code. Use Wix's built-in Secrets Manager:
1. In the Velo sidebar (left), expand **Developer Tools** → **Secrets Manager**.
2. Click **Store Secret**:
   - Name: `UPIDROP_PUBLIC_KEY`
   - Value: Your public key from UPIDrop (e.g. `pk_live_...`)
3. Click **Store Secret** again:
   - Name: `UPIDROP_WEBHOOK_SECRET`
   - Value: Your webhook secret from UPIDrop (e.g. `whsec_...`)

---

### Step 3: Create the Backend Payment Provider File
1. In the Velo sidebar under **Code**, locate **Backend**.
2. Click the **+** (Add) icon next to Backend → **New .js file**.
3. Name the file: `payment-provider.js` (or `upidrop-provider.js`).
4. Download the ready-to-use SPI file:
   👉 **[Download upidrop-wix-spi.js](https://upidrop.roori.in/plugins/wix/upidrop-wix-spi.js)**
5. Paste the following SPI implementation into your backend file:

```javascript
/**
 * UPIDrop Wix Velo Payment Provider SPI
 * Connects Wix checkout to UPIDrop Zero-Fee UPI Gateway
 */

import { fetch } from 'wix-fetch';
import { getSecret } from 'wix-secrets-backend';

const UPIDROP_API = 'https://upidrop-pg.upidrop-payment-gateway.workers.dev';
const UPIDROP_CHECKOUT = 'https://upidrop.roori.in/pay.html';

/**
 * Called by Wix when customer chooses UPIDrop at checkout
 */
export async function createPayment(paymentId, orderInfo, paymentGatewayInfo) {
    try {
        const publicKey = await getSecret('UPIDROP_PUBLIC_KEY');

        const buyer = orderInfo.buyerInfo || {};
        const customerName = [buyer.firstName, buyer.lastName].filter(Boolean).join(' ') || 'Customer';

        const response = await fetch(`${UPIDROP_API}/api/v1/orders`, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                'X-API-Key': publicKey,
            },
            body: JSON.stringify({
                amount: orderInfo.amount.value,
                currency: orderInfo.amount.currency || 'INR',
                customer_name: customerName,
                customer_email: buyer.email || '',
                customer_phone: buyer.phone || '',
                item_description: `Wix Order #${paymentId.slice(0, 8)}`,
                metadata: {
                    wix_payment_id: paymentId
                }
            }),
        });

        const data = await response.json();

        if (!response.ok || !data.orderId) {
            return {
                pluginTransactionId: paymentId,
                reasonCode: 5001,
                errorCode: 'ORDER_CREATION_FAILED',
                errorMessage: data.error || 'Failed to create UPIDrop order',
            };
        }

        // Return hosted checkout redirect URL
        const redirectUrl = `${UPIDROP_CHECKOUT}?orderId=${data.orderId}&token=${data.token}`;

        return {
            pluginTransactionId: data.orderId,
            redirectUrl: redirectUrl,
        };
    } catch (err) {
        return {
            pluginTransactionId: paymentId,
            reasonCode: 5000,
            errorCode: 'INTEGRATION_ERROR',
            errorMessage: err.message || 'Unknown network error',
        };
    }
}

/**
 * Called by Wix to check payment status (polling)
 */
export async function getPaymentStatus(pluginTransactionId) {
    try {
        const response = await fetch(`${UPIDROP_API}/api/v1/orders/${pluginTransactionId}/public`);
        const data = await response.json();

        if (!data || !data.order) {
            return { status: 'Undefined' };
        }

        const statusMap = {
            'paid': 'Approved',
            'late_success': 'Approved',
            'pending': 'Pending',
            'payment_detected': 'Pending',
            'pending_verification': 'Pending',
            'rejected': 'Declined',
            'expired': 'Expired',
        };

        return {
            status: statusMap[data.order.status] || 'Pending',
            amount: { 
                value: data.order.amount ? data.order.amount.toString() : '0', 
                currency: data.order.currency || 'INR' 
            },
        };
    } catch (err) {
        return { status: 'Undefined' };
    }
}

/**
 * UPIDrop payments settle directly to your bank account via UPI.
 * Refunds are processed manually by the merchant.
 */
export async function refundPayment(pluginTransactionId, refundAmount) {
    return {
        pluginRefundId: `refund_${pluginTransactionId}`,
        reasonCode: 3001,
        errorCode: 'REFUND_NOT_SUPPORTED',
        errorMessage: 'UPIDrop settlements go directly to your bank account. Please refund manually through your UPI app.',
    };
}
```

---

### Step 4: Enable Provider in Wix Dashboard
1. Go to your **Wix Dashboard** → **Settings** → **Accept Payments**.
2. Click **See More Payment Options**.
3. Under custom providers, locate **UPIDrop** and click **Connect**.
4. Set provider title to: `UPI (Google Pay, PhonePe, Paytm, BHIM)`.

---

## Method 2: Wix HTML Embed (For Landing Pages & Courses)

If you don't require full shopping cart integration and simply want a "Buy Now with UPI" button on any Wix page:

### Step 1: Add an Embed Element
1. In the Wix Editor, click the **+** (Add Elements) button on the left.
2. Select **Embed Code** → **Embed HTML**.
3. Position and resize the iframe container on your page.

### Step 2: Paste the Embed Code
Click **Enter Code** and paste the following snippet:

```html
<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <script src="https://upidrop.roori.in/sdk/upidrop.js"></script>
  <style>
    body {
      margin: 0;
      padding: 10px;
      font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
      display: flex;
      justify-content: center;
      align-items: center;
      background: transparent;
    }
    .pay-btn {
      background: linear-gradient(135deg, #10b981 0%, #059669 100%);
      color: white;
      border: none;
      padding: 14px 28px;
      border-radius: 12px;
      font-size: 16px;
      font-weight: 700;
      cursor: pointer;
      box-shadow: 0 4px 14px rgba(16, 185, 129, 0.35);
      transition: transform 0.15s ease, box-shadow 0.15s ease;
      display: inline-flex;
      align-items: center;
      gap: 8px;
    }
    .pay-btn:hover {
      transform: translateY(-2px);
      box-shadow: 0 6px 20px rgba(16, 185, 129, 0.45);
    }
    .pay-btn:active {
      transform: translateY(0);
    }
  </style>
</head>
<body>

  <button class="pay-btn" onclick="startUPIPayment()">
    <span>⚡</span> Pay ₹499 via UPI
  </button>

  <script>
    // Initialize UPIDrop SDK with your Public Key
    UPIDrop.init({
      publicKey: 'YOUR_UPIDROP_PUBLIC_KEY', // Replace with your pk_live_... key
      apiBase: 'https://upidrop-pg.upidrop-payment-gateway.workers.dev'
    });

    function startUPIPayment() {
      UPIDrop.checkout({
        amount: 499.00,
        description: 'Course Access / Product',
        customerName: 'Customer',
        onSuccess: function(data) {
          alert('Payment Successful! UTR: ' + (data.utr || 'Auto-verified'));
          // Redirect customer to members area or thank you page
          window.top.location.href = 'https://yourwebsite.com/thank-you';
        },
        onCancel: function() {
          console.log('Customer closed UPIDrop checkout modal.');
        }
      });
    }
  </script>

</body>
</html>
```

4. Replace `YOUR_UPIDROP_PUBLIC_KEY` with your actual Public Key from your dashboard.
5. Click **Update** and publish your Wix site!

---

## Webhook Auto-Reconciliation

If you run external automation (Make.com, Zapier, or a custom server):
1. In your **UPIDrop Dashboard** → **Settings** → **Webhook URL**, configure your listener endpoint.
2. When SmartTrack verifies a payment, UPIDrop delivers the `order.paid` event.
3. Your server validates the signature and automatically provisions access for the buyer.

---

## Summary Checklist

- [ ] Velo Dev Mode turned on in Wix.
- [ ] Stored `UPIDROP_PUBLIC_KEY` and `UPIDROP_WEBHOOK_SECRET` in Secrets Manager.
- [ ] Created `payment-provider.js` with UPIDrop SPI code.
- [ ] Enabled UPIDrop under **Wix Dashboard** → **Accept Payments**.
- [ ] Tested checkout flow with a live UPI transaction.

---

## Developer Support

- **Dashboard**: [https://upidrop.roori.in](https://upidrop.roori.in)
- **API Reference**: [https://upidrop.roori.in/docs/api-reference.md](https://upidrop.roori.in/docs/api-reference.md)
- **Email Support**: [rohitmore3192@gmail.com](mailto:rohitmore3192@gmail.com)
