# How to Migrate to Paid Community Features with Alipay in awesome-gpt-image-2: A 3-Phase Implementation Guide

> Implement paid community features with Alipay using the awesome-gpt-image-2 migration strategy. This 3-phase guide ensures secure, isolated, and duplicate-free transactions.

- Repository: [苍何/awesome-gpt-image-2](https://github.com/freestylefly/awesome-gpt-image-2)
- Tags: migration-guide
- Published: 2026-09-02

---

**The migration strategy uses a three-phase rollout (Preparation → Activation → Production Validation) that keeps paid community features completely isolated from existing points/VIP systems, with Alipay credentials secured in Vercel environment variables and idempotent order handling to prevent duplicate charges.**

The `freestylefly/awesome-gpt-image-2` repository implements paid community access through a decoupled payment architecture that protects existing users while enabling new revenue streams. This guide walks through the complete migration strategy based on the actual source code implementation, including database migrations, API endpoints, and fail-safe operational procedures.

## Understanding the Paid Community Architecture

The paid community system operates independently from the existing points and VIP subscription logic. This isolation ensures zero disruption to current users while enabling flexible monetization.

The core components include:

- A dedicated `community_orders` table with distinct status states (`PENDING`, `PAID`, `CLOSED`, `REFUNDED`, `REVOKED`)
- Supabase RPCs for order management and rate limiting
- Alipay website-payment integration with asynchronous notification handling
- Admin controls for QR-code management, refunds, and access revocation

All configuration is controlled through a single feature flag: `COMMUNITY_PAYMENT_ENABLED`.

## Phase 1: Preparation — Deploy Without Activation

The preparation phase establishes infrastructure without exposing payment functionality to end users.

### Deploy Database Objects

Apply the Supabase migration script to create the required schema:

```bash

# Run against your Supabase project

supabase/migrations/20260722090000_paid_community.sql

```

This migration creates:
- The `community_orders` table with proper indexes and RLS policies
- RPC functions for order retrieval and rate-limit tracking
- Helper functions for access verification

### Verify Feature Flag State

Ensure the system remains inactive during preparation:

```bash
COMMUNITY_PAYMENT_ENABLED=false

```

### Test Public Endpoints

Verify these read-only APIs respond correctly before activation:

| Endpoint | Purpose | Expected Response |
|----------|---------|-------------------|
| `GET /api/community/config` | Exposes payment availability and terms version | JSON with `enabled: false` |
| `GET /api/community/status` | Returns current user's order status | Authenticated users only |
| `GET /api/community/q` | Serves the protected QR-code image | 404 or placeholder until QR uploaded |

The `/community` and `/community/result` pages should render in read-only mode, showing informational content without payment options.

## Phase 2: Activation — Enable Alipay Integration

Activation connects live Alipay credentials and exposes payment flows to qualified users.

### Obtain Alipay Credentials

Register a website-payment application in the [Alipay Open Platform](https://open.alipay.com/). Required credentials:

- `ALIPAY_APP_ID` — Your application identifier
- `ALIPAY_PRIVATE_KEY` — RSA private key for signing requests
- `ALIPAY_PUBLIC_KEY` — Alipay's public key for verification
- `ALIPAY_SELLER_ID` — Merchant account identifier

### Secure Environment Configuration

Store credentials exclusively in **Vercel Sensitive Environment Variables**:

```

ALIPAY_APP_ID=your_app_id_here
ALIPAY_PRIVATE_KEY=-----BEGIN RSA PRIVATE KEY-----\n...\n-----END RSA PRIVATE KEY-----
ALIPAY_PUBLIC_KEY=-----BEGIN PUBLIC KEY-----\n...\n-----END PUBLIC KEY-----
ALIPAY_SELLER_ID=your_seller_id

```

**Never commit these values to the repository.** The codebase contains only placeholder configurations.

### Enable Payment Flow

Set the activation flag as documented in [`docs/paid-community.md`](https://github.com/freestylefly/awesome-gpt-image-2/blob/main/docs/paid-community.md):

```bash
COMMUNITY_PAYMENT_ENABLED=true

```

### Upload Protected QR Code

Admin users must upload the never-published community QR code:

```js
// POST /api/admin/community/qr
const formData = new FormData();
formData.append('qrImage', fileInput.files[0]);

await fetch('/api/admin/community/qr', {
  method: 'POST',
  body: formData
});

```

Source: [`api/admin/community/qr.js`](https://github.com/freestylefly/awesome-gpt-image-2/blob/main/api/admin/community/qr.js)

## Phase 3: Production Validation — Verify End-to-End Flows

Complete validation ensures payment processing, fulfillment, and administrative controls operate reliably.

### Test Live Checkout Flow

Initiate a real payment using the checkout endpoint. Client-side implementation:

```js
async function startPaidCommunityCheckout() {
  const response = await fetch('/api/community/alipay/checkout', {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify({
      acceptedTerms: true,
      termsVersion: '2024-08-01'   // Must match COMMUNITY_TERMS_VERSION
    })
  });
  const data = await response.json();
  if (data.ok && !data.paid) {
    // Render Alipay redirect form
    document.body.innerHTML = data.paymentHtml;
  }
}

```

Source: [`api/community/alipay/checkout.js`](https://github.com/freestylefly/awesome-gpt-image-2/blob/main/api/community/alipay/checkout.js)

The checkout handler in [`api/community/alipay/checkout.js`](https://github.com/freestylefly/awesome-gpt-image-2/blob/main/api/community/alipay/checkout.js) implements **idempotent order handling**—it queries for existing active orders via `getActiveCommunityOrder` before creating new ones, preventing duplicate charges.

### Verify Alipay Notification Handling

Confirm asynchronous payment confirmation works correctly. The notify handler:

```js
// api/community/alipay/notify.js (simplified)
export default async function handler(req, res) {
  const { out_trade_no, trade_status } = req.body;
  if (trade_status === 'TRADE_SUCCESS') {
    await markOrderPaid(out_trade_no); // Updates status to PAID
  }
  res.status(200).send('success');
}

```

Source: [`api/community/alipay/notify.js`](https://github.com/freestylefly/awesome-gpt-image-2/blob/main/api/community/alipay/notify.js)

**Critical:** Alipay requires the literal string response `'success'` (not JSON) for webhook acknowledgment.

### Validate Refund and Revoke Operations

| Operation | Endpoint | Behavior |
|-----------|----------|----------|
| Refund | `POST /api/admin/community/refund` | Order → `REFUNDED`, user retains access until finalization |
| Revoke | `POST /api/admin/community/revoke` | Order → `REVOKED`, **no automatic refund** |

Revocation example:

```js
// api/admin/community/revoke.js
await supabase
  .from('community_orders')
  .update({ status: 'REVOKED' })
  .eq('id', orderId);

```

Source: [`api/admin/community/revoke.js`](https://github.com/freestylefly/awesome-gpt-image-2/blob/main/api/admin/community/revoke.js)

### Emergency Rollback Procedure

If any validation step fails:

```bash
COMMUNITY_PAYMENT_ENABLED=false

```

This immediately halts new purchases without affecting existing paid users.

## Key Implementation Safeguards

The migration strategy incorporates multiple protective mechanisms:

**Isolation from existing systems** — The paid community uses separate `community_orders` tables and RPCs, leaving points/VIP users unaffected.

**Idempotent order creation** — The `getActiveCommunityOrder` check in [`api/community/alipay/checkout.js`](https://github.com/freestylefly/awesome-gpt-image-2/blob/main/api/community/alipay/checkout.js) prevents duplicate orders for the same user.

**Robust state machine** — Status transitions (`PENDING` → `PAID` → `REFUNDED`/`REVOKED`/`CLOSED`) are enforced consistently across all endpoints.

**Rate limiting** — `applyCommunityRateLimit` and `takeCommunityRateLimit` in [`api/_lib/community.js`](https://github.com/freestylefly/awesome-gpt-image-2/blob/main/api/_lib/community.js) protect checkout APIs from abuse.

**Configuration security** — Sensitive credentials exist only in Vercel's encrypted environment; repository contains safe defaults.

## Core Business Logic Reference

The [`api/_lib/community.js`](https://github.com/freestylefly/awesome-gpt-image-2/blob/main/api/_lib/community.js) module centralizes paid community operations:

- Order retrieval and status checking
- Rate-limit enforcement
- Configuration exposure with safe defaults
- Terms version validation

Alipay-specific utilities in [`api/_lib/alipay.js`](https://github.com/freestylefly/awesome-gpt-image-2/blob/main/api/_lib/alipay.js) handle:

- Amount formatting (yuan to fen conversion)
- Payment subject string construction
- Configuration validation helpers

## Summary

- **Three-phase migration** (Preparation → Activation → Production Validation) enables safe rollout of paid community features
- **Complete decoupling** from points/VIP systems protects existing functionality
- **Idempotent checkout** prevents duplicate charges through `getActiveCommunityOrder` checks
- **Secure credential management** via Vercel Sensitive Environment Variables keeps Alipay keys out of version control
- **Emergency rollback** via `COMMUNITY_PAYMENT_ENABLED=false` provides immediate circuit-breaking capability

## Frequently Asked Questions

### What happens to existing free community users during migration?

Existing users remain completely unaffected. The paid community system uses separate database tables (`community_orders`) and API endpoints, with no interaction with the points or VIP subscription logic. Free community features continue operating normally alongside paid features.

### How does the system prevent duplicate Alipay charges?

The checkout handler in [`api/community/alipay/checkout.js`](https://github.com/freestylefly/awesome-gpt-image-2/blob/main/api/community/alipay/checkout.js) implements idempotent order creation. Before generating a new order, it calls `getActiveCommunityOrder` to check for existing `PENDING` or `PAID` orders. If a paid order exists, the endpoint returns the existing status without creating a duplicate transaction.

### What's the difference between refunding and revoking a paid community membership?

**Refunds** (`POST /api/admin/community/refund`) process through Alipay's refund API, move the order to `REFUNDED` status, and the user retains access until the refund finalizes. **Revocations** (`POST /api/admin/community/revoke`) immediately set status to `REVOKED` for policy violations but do **not** trigger automatic refunds—administrators must process refunds separately if warranted.

### Where should Alipay credentials be stored for production deployments?

Store all sensitive credentials exclusively in **Vercel Sensitive Environment Variables**: `ALIPAY_APP_ID`, `ALIPAY_PRIVATE_KEY`, `ALIPAY_PUBLIC_KEY`, and `ALIPAY_SELLER_ID`. The repository contains only placeholder values and safe defaults (`COMMUNITY_PAYMENT_ENABLED=false`). Never commit private keys or live credentials to Git.