연동 · AI 빌더

상점을 바이브 코딩하셨나요? 프롬프트 하나로 Peptide-Pay를 추가하세요.

프롬프트를 복사해 Lovable, Bolt, v0, Cursor, Replit 또는 Claude에 붙여넣으세요. AI가 스택을 감지하여 서버 측 결제, 웹훅, 완료 페이지를 추가하고 테스트를 실행합니다. 테스트를 위해 실제 결제를 할 필요는 없습니다.

프롬프트 읽기
지원 도구LovableBoltv0CursorReplitClaude

3단계 작동 방식

  1. 1

    프롬프트 복사하기

    클릭 한 번으로 충분합니다. AI 코딩 도구는 영어 명세서를 가장 정확하게 이해하므로 프롬프트는 의도적으로 영어로 작성되었습니다. AI는 여전히 한국어로 답변해 줍니다.

  2. 2

    AI 도구에 붙여넣기

    AI가 사용자의 스택(Next.js, Vite + Supabase, Express, PHP…)을 감지하고 결제 경로, 서명 확인 기능이 포함된 웹훅, 완료 페이지를 작성합니다. API 키는 서버에 안전하게 보관됩니다.

  3. 3

    테스트 후 라이브 전환

    AI가 테스트 세션을 생성하고 결제 없이도 위조된 웹훅이 거부되는지 증명합니다. 그 후 키를 추가하고 대시보드에 웹훅 URL을 붙여넣은 뒤 “Send test webhook”을 클릭하세요.

AI가 구축하는 항목

  • 카탈로그에서 합계를 재계산하고 /api/v1/checkout/init을 호출하는 서버 호출 구매 버튼
  • 호스팅된 Peptide-Pay 결제 페이지로의 전체 페이지 리다이렉트. 사이트 내 카드 입력 폼 불필요
  • 원시 본문(raw body)에서 x-peptidepay-signature HMAC을 확인하는 웹훅 경로
  • GET /api/v1/sessions/{id}를 통한 주문 확인: 금액과 통화가 일치하는 경우에만 결제 완료 처리
  • 확인을 기다리며 스스로 주문을 결제 완료로 표시하지 않는 성공 페이지
  • 테스트 및 일반적인 오류 처리. AI가 '완료'라고 말하기 전에 오류를 수정하도록 합니다.

지원되는 스택

  • Next.js (App Router 및 Pages Router)
  • Vite / React + Supabase Edge Functions (Lovable, Bolt)
  • Express, Fastify, Hono, Remix, SvelteKit, Nuxt, Astro
  • PHP, Laravel, Django, Rails

WordPress를 사용하시나요? 코드가 필요 없습니다: WooCommerce 플러그인

프롬프트

복사되는 내용 그대로입니다. 일반 텍스트이며 파일로도 제공됩니다: ai-prompt.txt

# TASK: add Peptide-Pay checkout to this project, end to end

You are a senior full-stack engineer working inside my project. Add Peptide-Pay (a hosted checkout for research-peptide stores, https://peptide-pay.com) so that a "Buy" / "Checkout" button takes the buyer to the Peptide-Pay payment page, and my order flips to "paid" automatically once the payment is confirmed.

Follow this spec exactly. Every endpoint, field, header and error below comes from the live API. Do not invent endpoints, fields or SDKs. Talk to me in the language I write to you in, but keep code, file names and env var names in English.

## 0. How it works (read once)

1. My server creates an order (status "pending") and calls POST https://peptide-pay.com/api/v1/checkout/init.
2. Peptide-Pay answers { id: "cs_…", url: "https://peptide-pay.com/session/cs_…", status: "pending", … }.
3. My site sends the buyer to that url (full-page redirect). The buyer pays there. My site never shows a card form.
4. When the payment is confirmed, Peptide-Pay:
   a. sends the buyer back to my success_url (after a 4-second countdown on its page), and
   b. POSTs an "order.paid" webhook to my webhook_url.
5. My server never trusts the redirect or the webhook body alone: it calls GET https://peptide-pay.com/api/v1/sessions/{id} and marks the order paid only if status === "paid" AND amount AND currency match my order.

Funds go straight to the merchant's own 0x wallet (most often on Ethereum as ETH or USDC, sometimes on Polygon). Peptide-Pay never holds a balance for the merchant.

## 1. Detect my stack first, then say it in ONE line

Look at package.json, lockfiles, folders (app/, pages/, src/, supabase/functions/, server/, api/, netlify/functions/), composer.json, requirements.txt. Then print one line, for example:
"Detected: Next.js 15 App Router + Prisma/Postgres. I will create: lib/peptidepay.ts, app/api/peptidepay/checkout/route.ts, app/api/peptidepay/webhook/route.ts, app/api/peptidepay/order-status/route.ts, app/checkout/success/page.tsx."

Pick the matching recipe:

- Next.js App Router → route handlers in app/api/peptidepay/{checkout,webhook,order-status}/route.ts (under src/ if the project has a src/ folder; import with the project's alias, e.g. "@/lib/peptidepay"). If next.config does NOT enable `cacheComponents`, add `export const runtime = "nodejs"` and `export const dynamic = "force-dynamic"` to each; if it does (default in new Next.js 16 apps), add NO route segment config: it breaks the build, and handlers that read the request are already dynamic. Read the webhook body with `await req.text()`. In pages, `searchParams` is a Promise (Next.js 15+): read it, or `useSearchParams()`, inside a `<Suspense>` boundary or `next build` fails.
- Next.js Pages Router → pages/api/peptidepay/*.ts. In the webhook file: `export const config = { api: { bodyParser: false } }` and read the raw body from the stream.
- Vite / React SPA with Supabase (typical Lovable, Bolt, v0 export) → three Supabase Edge Functions: peptidepay-checkout, peptidepay-webhook, peptidepay-order-status (Deno, `Deno.serve`). Put the helper in supabase/functions/_shared/peptidepay.ts. The browser calls them with `supabase.functions.invoke(...)`, so the checkout and order-status functions must answer the CORS preflight (OPTIONS) with Access-Control-Allow-Origin, Access-Control-Allow-Headers: authorization, x-client-info, apikey, content-type. The webhook function MUST run without JWT verification (Peptide-Pay sends no Supabase token): add `[functions.peptidepay-webhook]` + `verify_jwt = false` to supabase/config.toml, or deploy with `supabase functions deploy peptidepay-webhook --no-verify-jwt`. Set secrets with `supabase secrets set PEPTIDEPAY_API_KEY=… PEPTIDEPAY_WEBHOOK_SECRET=…` (in Lovable: Supabase → Edge Function secrets). Store orders in a Postgres table and write it with the service role key inside the functions only.
- Vite / React SPA with NO backend at all → stop and tell me: a payment needs a server. Propose the smallest option the host supports (Supabase Edge Functions, Netlify Functions, Vercel Functions, Cloudflare Workers) and use it. Never call Peptide-Pay from the browser with a key.
- Express / Fastify / Hono / Remix / SvelteKit / Nuxt / Astro SSR → the same three server routes in the framework's idiom. Express: mount `express.raw({ type: "application/json" })` on the webhook route BEFORE any `express.json()`.
- PHP / Laravel / Django / Rails → same three routes. Raw body: Laravel `$request->getContent()`, Django `request.body`, Rails `request.raw_post`, plain PHP `file_get_contents("php://input")`. HMAC: `hash_hmac("sha256", "$t.$raw", $secret)` + `hash_equals`, Python `hmac.new(...).hexdigest()` + `hmac.compare_digest`.
- WordPress / WooCommerce → STOP. Do not write code. Tell me to install the plugin: https://peptide-pay.com/integrate?stack=woocommerce

If the project already has another payment provider, keep it in place and add Peptide-Pay next to it (feature flag or second button). Do not delete working code.

## 2. Environment variables (server only)

PEPTIDEPAY_API_BASE=https://peptide-pay.com
PEPTIDEPAY_API_KEY=sk_live_...          # account mode (recommended once my account is active)
PEPTIDEPAY_WEBHOOK_SECRET=whsec_...     # account mode: verifies webhook signatures
PEPTIDEPAY_WALLET=0x...                 # wallet mode only, when there is no API key yet
APP_URL=https://my-domain.com           # public URL of THIS site, used to build return and webhook URLs (http://localhost:3000 in dev)

Rules:
- Never prefix them with NEXT_PUBLIC_, VITE_, PUBLIC_, REACT_APP_ or EXPO_PUBLIC_. They must never reach the browser bundle.
- Add them to .env.example (empty values) and to .env.local / the host's secret store. Never commit real values. If .gitignore ignores `.env*`, add the line `!.env.example` so the example is committed.

Two modes. The code supports both and picks automatically:
- Account mode: header `Authorization: Bearer <PEPTIDEPAY_API_KEY>`, no `wallet` in the body. Keys live at https://peptide-pay.com/app/api-keys after signing up at https://peptide-pay.com/signup. Webhooks are signed with PEPTIDEPAY_WEBHOOK_SECRET. A new account is reviewed before it can charge: until then checkout/init answers 403 "merchant_pending".
- Wallet mode: no key; send `"wallet": "0x…"` (0x + 40 hex, a personal EVM wallet that accepts Ethereum and Polygon, not an exchange deposit address) in the body. Works immediately, no account. Webhooks arrive UNSIGNED and carry `"unauthenticated_init": true`, which is why step 5 below (confirm with GET /sessions) is mandatory.

If I have neither yet and we are only developing: you may set PEPTIDEPAY_WALLET=0x7521d59b02e26e101abc98354e5c088bf449a157. That is Peptide-Pay's PUBLIC DEMO wallet: it lets you create test sessions, the API will return a warning saying so, and any real money sent to it is lost for me. Tell me loudly to replace it before going live, and never pay a session created with it.

## 3. The API (exact)

POST https://peptide-pay.com/api/v1/checkout/init
Headers: Content-Type: application/json
         Authorization: Bearer sk_live_…      (account mode only)
         Idempotency-Key: order-<my order id>  (recommended: a retry with the same key AND the same body returns the same session)
Body:
{
  "amount_cents": 4999,                 // REQUIRED. Integer, smallest currency unit. Min 100, max 100000000. 49.99 → 4999.
  "currency": "EUR",                    // REQUIRED. One of EUR, USD, GBP, CHF, CAD, AUD, TRY.
  "wallet": "0x…",                      // wallet mode only. Omit in account mode.
  "success_url": "https://my-domain.com/checkout/success?order=ORDER_ID",  // http(s). Peptide-Pay appends NOTHING, so put my order id in it.
  "cancel_url": "https://my-domain.com/cart",                              // http(s)
  "webhook_url": "https://my-domain.com/api/peptidepay/webhook",           // http(s), public. Overrides the dashboard setting for this session.
  "metadata": { "order_id": "ORDER_ID" },  // string values. Echoed back in the webhook.
  "customer_email": "buyer@example.com",   // optional, valid e-mail or omit
  "product_name": "Order #1042",           // optional, shown on the payment page
  "locale": "en"                           // optional: en fr de it es nl pt ru pl tr zh ja ko
}
200 response:
{ "id": "cs_…", "url": "https://peptide-pay.com/session/cs_…", "status": "pending", "amount": 4999, "currency": "EUR",
  "provider": "gateway", "expires_at": "<ISO date, 24 h later>", "tracking_number": "…", "warnings": ["…"] }
"warnings" is optional and non-fatal (e.g. "No webhook_url set", demo wallet). Log it on the server.

GET https://peptide-pay.com/api/v1/sessions/{id}
Headers: Authorization: Bearer sk_live_… (account mode; optional in wallet mode)
200 response: { "id", "status": "pending" | "paid" | "expired" | "failed", "amount", "currency", "paid_at", "paid_provider", "txid", "coin", "expires_at" }

Webhook that Peptide-Pay POSTs to webhook_url:
Headers: Content-Type: application/json
         x-peptidepay-signature: t=<unix seconds>,v1=<hex HMAC-SHA256>   (same value also in x-webhook-signature; absent in wallet mode)
Body: { "event": "order.paid", "session_id": "cs_…", "order_id": "ORDER_ID" | null, "address_in": "…", "status": "paid",
        "amount": 4999, "currency": "EUR", "txid": "0x…" | null, "paid_at": "<ISO>", "attempt": 1,
        "customer_email": "…" | null, "metadata": { … } | null, "unauthenticated_init": true (wallet mode only) }
Signature = hex(HMAC_SHA256(key = PEPTIDEPAY_WEBHOOK_SECRET, message = t + "." + rawBody)). Reject if |now - t| > 300 s.
The dashboard "Send test webhook" button and the test simulator send "event": "webhook.test" (status "test"): answer 200 and change nothing.
Delivery rules: 5-second timeout, redirects are NOT followed (a 301/302/307/308 counts as a failure), private/localhost hosts are refused. Failed deliveries are retried up to 6 attempts in total (after 5 min, 15 min, 1 h, 4 h, 12 h).

## 4. Files to create

### 4.1 Server helper (copy as is; TypeScript, works on Node 20+, Deno, Edge and Bun)
Put it at lib/peptidepay.ts (src/lib/peptidepay.ts if the project uses src/) or supabase/functions/_shared/peptidepay.ts (Supabase). Server-only.

```ts
/* eslint-disable @typescript-eslint/no-explicit-any */
// Peptide-Pay server helper. NEVER import this file from client/browser code.
const env = (k: string): string | undefined =>
  (globalThis as any).Deno?.env?.get(k) ?? (globalThis as any).process?.env?.[k];

export const PP_API_BASE = (env("PEPTIDEPAY_API_BASE") || "https://peptide-pay.com").replace(/\/+$/, "");

export class PeptidePayError extends Error {
  status: number; code: string;
  constructor(status: number, code: string, message: string) { super(message); this.status = status; this.code = code; }
}

function authHeader(): Record<string, string> {
  const key = env("PEPTIDEPAY_API_KEY");
  return key ? { Authorization: `Bearer ${key.trim()}` } : {};
}

export type PPSession = {
  id: string; url?: string; status: "pending" | "paid" | "expired" | "failed";
  amount: number; currency: string; expires_at: string;
  txid?: string | null; paid_at?: string | null; warnings?: string[];
};

export async function createPeptidePaySession(o: {
  orderId: string; amountCents: number; currency: string;
  successUrl: string; cancelUrl: string; webhookUrl?: string;
  customerEmail?: string; productName?: string; locale?: string;
}): Promise<PPSession> {
  const key = env("PEPTIDEPAY_API_KEY");
  const wallet = env("PEPTIDEPAY_WALLET");
  if (!key && !wallet) throw new PeptidePayError(500, "config", "Set PEPTIDEPAY_API_KEY or PEPTIDEPAY_WALLET");
  if (!Number.isInteger(o.amountCents) || o.amountCents < 100) throw new PeptidePayError(400, "amount", "amountCents must be an integer >= 100");
  const body: Record<string, unknown> = {
    amount_cents: o.amountCents,
    currency: o.currency.toUpperCase(),
    success_url: o.successUrl,
    cancel_url: o.cancelUrl,
    metadata: { order_id: String(o.orderId) },
  };
  if (!key) body.wallet = wallet!.trim();
  if (o.webhookUrl) body.webhook_url = o.webhookUrl;
  if (o.customerEmail) body.customer_email = o.customerEmail;
  if (o.productName) body.product_name = o.productName;
  if (o.locale) body.locale = o.locale;
  const res = await fetch(`${PP_API_BASE}/api/v1/checkout/init`, {
    method: "POST",
    headers: { "Content-Type": "application/json", "Idempotency-Key": `order-${o.orderId}`, ...authHeader() },
    body: JSON.stringify(body),
  });
  const data: any = await res.json().catch(() => ({}));
  if (!res.ok) throw new PeptidePayError(res.status, String(data.error ?? "http_" + res.status), String(data.message ?? data.error ?? "Peptide-Pay error"));
  if (Array.isArray(data.warnings) && data.warnings.length) console.warn("[peptide-pay] warnings:", data.warnings);
  return data as PPSession;
}

export async function getPeptidePaySession(id: string): Promise<PPSession> {
  const res = await fetch(`${PP_API_BASE}/api/v1/sessions/${encodeURIComponent(id)}`, {
    headers: { ...authHeader() },
  });
  const data: any = await res.json().catch(() => ({}));
  if (!res.ok) throw new PeptidePayError(res.status, String(data.error ?? "http_" + res.status), String(data.message ?? data.error ?? "Peptide-Pay error"));
  return data as PPSession;
}

/** True only if the session is paid for exactly this amount and currency. */
export function isPaidFor(s: PPSession, amountCents: number, currency: string): boolean {
  return s.status === "paid" && s.amount === amountCents && s.currency === currency.toUpperCase();
}

/** Verifies `x-peptidepay-signature: t=<ts>,v1=<hex>` against the RAW request body. */
export async function verifyPeptidePaySignature(rawBody: string, header: string | null, secret: string, toleranceSec = 300): Promise<boolean> {
  if (!header) return false;
  const parts = Object.fromEntries(header.split(",").map((p) => p.trim().split("=", 2) as [string, string]));
  const t = Number(parts.t);
  const v1 = (parts.v1 || "").toLowerCase();
  if (!Number.isFinite(t) || !/^[0-9a-f]{64}$/.test(v1)) return false;
  if (Math.abs(Math.floor(Date.now() / 1000) - t) > toleranceSec) return false;
  const enc = new TextEncoder();
  const key = await crypto.subtle.importKey("raw", enc.encode(secret), { name: "HMAC", hash: "SHA-256" }, false, ["sign"]);
  const mac = new Uint8Array(await crypto.subtle.sign("HMAC", key, enc.encode(`${t}.${rawBody}`)));
  const expected = Array.from(mac, (b) => b.toString(16).padStart(2, "0")).join("");
  let diff = 0;
  for (let i = 0; i < 64; i++) diff |= expected.charCodeAt(i) ^ v1.charCodeAt(i);
  return diff === 0;
}

/** TESTS ONLY: builds a signature header the way Peptide-Pay does, to test the webhook locally. */
export async function signPeptidePayTestPayload(rawBody: string, secret: string, t = Math.floor(Date.now() / 1000)): Promise<string> {
  const enc = new TextEncoder();
  const key = await crypto.subtle.importKey("raw", enc.encode(secret), { name: "HMAC", hash: "SHA-256" }, false, ["sign"]);
  const mac = new Uint8Array(await crypto.subtle.sign("HMAC", key, enc.encode(`${t}.${rawBody}`)));
  return `t=${t},v1=${Array.from(mac, (b) => b.toString(16).padStart(2, "0")).join("")}`;
}
```

### 4.2 Orders storage
Use the project's existing database (Supabase table, Prisma model, Drizzle, SQL…). The order needs at least:
id, amount_cents (integer), currency, status ('pending' | 'paid' | 'expired' | 'failed'), peptidepay_session_id, paid_at, txid, created_at.
Write one shared function `syncOrderWithPeptidePay(order)`:
- if order.status is 'paid' or there is no peptidepay_session_id → return the order unchanged;
- s = await getPeptidePaySession(order.peptidepay_session_id);
- if isPaidFor(s, order.amount_cents, order.currency) → UPDATE … SET status='paid', paid_at, txid WHERE id = … AND status <> 'paid' (idempotent), then run the paid side effects (e-mail, stock) only if that UPDATE changed a row;
- if s.status is 'expired' or 'failed' → store it;
- if s.status is 'paid' but the amount or currency differs → do NOT mark paid; log it loudly for a human.
If the project has no database at all, tell me, and use the simplest persistence the host supports (a local JSON file is acceptable ONLY for local development).

### 4.3 Checkout endpoint (POST, server)
- Input from the browser: cart lines { productId, quantity } only. NEVER accept a price or total from the browser: recompute the total from the server-side catalog / database.
- Create the order (status 'pending') first, then call createPeptidePaySession with:
  successUrl = `${APP_URL}/checkout/success?order=${order.id}`
  cancelUrl  = `${APP_URL}/cart` if that page exists, otherwise the product page or home page (never a URL that 404s)
  webhookUrl = `${APP_URL}/api/peptidepay/webhook` (Supabase: `https://<project-ref>.supabase.co/functions/v1/peptidepay-webhook`), but ONLY when APP_URL starts with https:// and its host is not localhost / 127.0.0.1; otherwise omit it.
  productName = a short label such as `Order #${order.id}`; locale = the store's language if you know it, else omit.
- Save session.id on the order, return { url: session.url } as JSON.
- On PeptidePayError: log status + code + message on the server, return a short readable error to the browser: 502 if Peptide-Pay answered 5xx, 503 "please retry" if it answered 429, 500 for 401/403 (a configuration problem on my side, log it loudly), 400 otherwise. Never send the API key or the raw upstream response to the browser.

### 4.4 Webhook endpoint (POST, server, public)
1. Read the RAW body as text BEFORE any JSON parsing.
2. If PEPTIDEPAY_WEBHOOK_SECRET is set: verify with verifyPeptidePaySignature(raw, headers["x-peptidepay-signature"] ?? headers["x-webhook-signature"], secret). Invalid or missing → 401, do nothing else.
   If it is not set (wallet mode): continue, but treat the body as a hint only.
3. Parse JSON. If event !== "order.paid" (for example "webhook.test") → 200 { ok: true }.
4. Find the order by session_id (peptidepay_session_id), else by order_id. Unknown → 200 { ok: true, ignored: "unknown order" }.
5. Call syncOrderWithPeptidePay(order). This GET /sessions confirmation is what makes the order paid, never the webhook body itself.
   If Peptide-Pay cannot be reached (network error, 429, 5xx) → answer 500 so the webhook is retried later.
6. Answer 200 within 5 seconds. Send e-mails / heavy work after answering or in a queue.
The route must not redirect (no trailing-slash rewrite, no http→https or www/apex redirect in front of it) and must not require login, cookies or CSRF tokens.

### 4.5 Order-status endpoint (GET, server) + success page
- GET /api/peptidepay/order-status?order=<id> → loads the order; if it is 'pending', calls syncOrderWithPeptidePay(order) (wrap in try/catch: on 429 or network error just return the stored status); returns { status } only (no personal data).
  (Supabase: `supabase.functions.invoke` sends a POST, so let peptidepay-order-status also accept { order } in a JSON body.)
- /checkout/success page: reads ?order=, polls that endpoint every 5 seconds for up to 3 minutes. 'paid' → "Payment confirmed, thank you" + order number. 'pending' → "Waiting for payment confirmation…" with a spinner. After 3 minutes still pending → "Your payment is being confirmed. You will receive an e-mail; you can close this page." 'expired' / 'failed' → link back to the cart. In Next.js use `<Link>` from next/link for internal links, not `<a>`, or `next lint` fails.
- This page is a fallback for the webhook. It must never mark an order paid by itself: only syncOrderWithPeptidePay can.

### 4.6 Buy button (browser)
- On click: disable the button, POST { items } to the checkout endpoint, then `window.location.assign(url)` with the url you got back. Full-page redirect: no iframe, no popup window.
- On error: re-enable the button and show the message under it.
- Next to the button you may add a small line: "Secure checkout by Peptide-Pay".

## 5. Tests you MUST run before saying "done" (no payment needed)

1. Smoke test from a terminal (wallet mode shown; in account mode replace "wallet" with -H "Authorization: Bearer $PEPTIDEPAY_API_KEY"):
   curl -s -X POST https://peptide-pay.com/api/v1/checkout/init -H "Content-Type: application/json" -d '{"wallet":"<PEPTIDEPAY_WALLET>","amount_cents":100,"currency":"USD","success_url":"https://example.com/ok","cancel_url":"https://example.com/cancel"}'
   Expect HTTP 200 with "id": "cs_…" and "status": "pending".
   (On Windows run it from Git Bash or WSL, or use curl.exe with the JSON in a file: -d @body.json.)
2. Run the app (dev server on the port used in APP_URL, e.g. `next dev -p 3100`). Click Buy (or POST to your checkout endpoint with curl and open the returned url). You must land on https://peptide-pay.com/session/cs_… : the page answers 200 and shows the right amount and currency. Do NOT pay. Check the order row: status 'pending', peptidepay_session_id = that cs_ id.
3. curl -s https://peptide-pay.com/api/v1/sessions/<cs_id> → "status":"pending". Open /checkout/success?order=<id> → it shows the waiting state, not "paid".
4. Webhook security, locally (skip the signed part in wallet mode if no secret is set; set a dummy PEPTIDEPAY_WEBHOOK_SECRET=whsec_test_local in .env.local just for this test, restart the dev server, run the checks, then REMOVE it and restart again: in wallet mode real webhooks are unsigned and would be rejected):
   - Build a body {"event":"order.paid","session_id":"<cs_id>","order_id":"<id>","status":"paid","amount":<cents>,"currency":"<the order's currency>"}, sign it with signPeptidePayTestPayload (t = now; simplest: a small .mjs script that copies its 5 lines, since plain Node cannot import a .ts file) and POST it with the header x-peptidepay-signature to the local webhook → expect 200, and the order must STAY 'pending' because GET /sessions still says pending. This proves a forged "paid" webhook cannot mark an order paid.
   - Same body with one character changed after signing → 401.
   - Same body signed with t = now - 600 → 401.
   - {"event":"webhook.test"} correctly signed → 200, nothing changes.
5. Grep the client bundle / source for "sk_live_", "whsec_" and "PEPTIDEPAY_API_KEY": they must appear only in server files and .env files.
6. Run the project's type check, lint and build (e.g. `npx tsc --noEmit`, `npm run lint`, `npm run build`) and fix every error.

## 6. Common mistakes and the exact fix

- 400 "Invalid amount" → amount_cents must be an integer in cents (19.99 € → 1999), at least 100.
- 400 "Currency must be one of …" → use one of EUR, USD, GBP, CHF, CAD, AUD, TRY in upper case.
- 400 "auth_required" → no API key and no valid wallet: check the env var is loaded on the server (restart the dev server after editing .env).
- 400 "success_url must be an http(s) URL" → APP_URL is empty or has no scheme.
- 401 "Invalid or revoked API key" → wrong key, extra spaces/quotes, or the key was rotated. Copy it again from https://peptide-pay.com/app/api-keys.
- 403 "merchant_pending" → the account is not activated yet: wait for activation (or contact support) and use wallet mode meanwhile.
- 429 → rate limits are 60 checkout/init per minute and 30 session reads per minute per IP. Do not poll faster than every 5 seconds.
- 502 "upstream_unavailable" → temporary: retry with the SAME Idempotency-Key.
- CORS error in the browser console → you are calling Peptide-Pay from the browser. Move the call to the server.
- Webhook 401 although the secret is right → the body was parsed or re-serialized before hashing (read raw text first), or the secret has spaces / is missing the whsec_ prefix, or the server clock is off by more than 5 minutes.
- Webhook never arrives → webhook_url points to localhost (refused; use a tunnel such as ngrok or cloudflared, or test with step 5.4), the route redirects (trailing slash, www/apex, http→https), Supabase JWT verification is on, or the handler takes longer than 5 s. The init response "warnings" says "No webhook_url set" when none was found. In wallet mode there is no dashboard: pass webhook_url on every init (needs a public https APP_URL).
- Success page stuck on "waiting" after a real payment → the order-status endpoint is not calling GET /sessions, or compares amount as a decimal instead of integer cents.
- Secrets in the browser → the env var was named NEXT_PUBLIC_… / VITE_…; rename it and rotate the key.
- Small amounts: each payment method on the hosted page has its own minimum, so very small orders show fewer ways to pay.

## 7. When everything passes, print this for me (in my language)

1. The list of files you created or changed, and the result of each test in section 5.
2. What I must do myself, in order:
   a. Create my account at https://peptide-pay.com/signup and copy the sk_live_ key and the whsec_ secret from https://peptide-pay.com/app/api-keys (or, for wallet mode, put my own 0x wallet in PEPTIDEPAY_WALLET instead of the demo wallet).
   b. Add PEPTIDEPAY_API_KEY, PEPTIDEPAY_WEBHOOK_SECRET (or PEPTIDEPAY_WALLET) and APP_URL to my hosting's environment variables / Supabase secrets, then redeploy.
   c. In https://peptide-pay.com/app/settings, paste my webhook URL (https://<my-domain>/api/peptidepay/webhook, or the Supabase function URL), save, and click "Send test webhook": it must turn green.
   d. Place one small real order to see it go from pending to paid.
3. Docs: https://peptide-pay.com/docs · fees: https://peptide-pay.com/fees · this guide: https://peptide-pay.com/integrate/ai

AI가 사용할 정보

API
POST /api/v1/checkout/init, GET /api/v1/sessions/{id}
Currencies
EUR, USD, GBP, CHF, CAD, AUD, TRY
Amount
정수 단위 센트, 100(1.00)부터 시작
Session
24시간 유효
Webhook
HMAC-SHA256 서명, 약 17시간 동안 최대 6회 재시도
Payout
사용자의 0x 지갑으로 직접 전송

수수료 확인하기API 문서 읽기

자주 묻는 질문

어떤 AI 도구에서 이 프롬프트를 사용할 수 있나요?

코드를 수정할 수 있는 모든 AI에서 가능합니다: Lovable, Bolt, v0, Cursor, Replit, Claude Code, Windsurf, GitHub Copilot. 별도의 플러그인 설치 없이 텍스트로 된 명세서만으로 작동합니다.

시작하려면 Peptide-Pay 계정이 필요한가요?

아니요. 지갑 모드에서는 서버가 0x 지갑 주소만 전송하며, 프롬프트는 이를 통해 모든 것을 구축하고 테스트할 수 있습니다. 계정을 만들면 sk_live_ API 키와 whsec_ 비밀 키를 받게 되며 웹훅이 서명됩니다. 새 계정은 결제 수락 전에 검토 과정을 거칩니다.

AI 빌더를 사용해도 API 키가 안전한가요?

프롬프트는 모든 호출을 서버 측에서 처리하도록 유지하고, 비밀 키에 NEXT_PUBLIC_ 및 VITE_ 변수 사용을 금지하며, AI가 완료하기 전에 코드에서 sk_live_ 및 whsec_를 검색하도록 강제합니다.

결제 없이 테스트할 수 있나요?

연동 테스트는 가능합니다. AI가 실제 테스트 세션을 생성하고, 결제 페이지가 열리는지 확인하며, 위조된 '결제 완료' 웹훅이 거부되는지 증명합니다. 별도의 샌드박스 결제 네트워크가 없으므로, 주문이 '결제 완료'로 바뀌는 것을 확인하려면 소액의 실제 결제가 한 번 필요합니다.

Peptide-Pay의 비용은 얼마인가요?

기본적으로 결제당 3%의 Peptide-Pay 수수료가 부과됩니다(일부 계정은 별도 협의 가능). 결제 수단 수수료는 호스팅된 결제 페이지에서 구매자 측에 추가됩니다. 자세한 내용은 수수료 페이지에서 확인하세요.

대금은 어디로 입금되나요?

사용자의 0x 지갑으로 직접 입금됩니다. 주로 Ethereum(ETH 또는 USDC)을 사용하며, 때로는 Polygon을 사용합니다. Peptide-Pay는 사용자의 잔액을 대신 보유하지 않습니다.

상점이 WordPress 기반입니다. 이 프롬프트를 사용해야 하나요?

아니요. WooCommerce는 전용 플러그인이 있어 코딩이 필요 없습니다. 관련 링크는 바로 위에 있습니다.

준비되셨나요? 복사하고, 붙여넣고, 출시하세요.

프롬프트는 무료입니다. Peptide-Pay는 연동 과정이 아닌, 실제 발생한 결제에 대해서만 수수료를 받습니다.