mirror of
https://github.com/profullstack/logicsrc.git
synced 2026-12-01 09:24:46 +00:00
feat(hire-us): CoinPay hosted checkout sessions for Hire Us
POST /api/hire-us/coinpay-checkout now opens a CoinPay checkout session instead of a single-chain USDC_POL /api/payments/create. The buyer picks any coin the business has a wallet for, or PayPal. Each session sends customer_email (required), account_id (CoinPay OAuth sub when signed in, else the buyer email for guests), property logicsrc.com and the Hire Us metadata. The cs_ id is recorded in the new hire_us_checkouts table. The webhook records session payments from the session fields (checkout_session_id, account_id, customer_email, property), stores the session id on hire_us_payments, marks the checkout paid, and stays idempotent on payment_id across confirmed, forwarded and replays. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
parent
5192684de9
commit
9d06d88e4d
6 changed files with 341 additions and 215 deletions
|
|
@ -42,12 +42,34 @@ function realShaped(status = "confirmed", type = "payment.confirmed") {
|
||||||
|
|
||||||
function memoryStore() {
|
function memoryStore() {
|
||||||
const rows = new Map<string, HireUsPaymentRow>();
|
const rows = new Map<string, HireUsPaymentRow>();
|
||||||
|
const paidSessions: [string, string][] = [];
|
||||||
return {
|
return {
|
||||||
rows,
|
rows,
|
||||||
|
paidSessions,
|
||||||
async insertIfAbsent(row: HireUsPaymentRow) {
|
async insertIfAbsent(row: HireUsPaymentRow) {
|
||||||
if (rows.has(row.payment_id)) return false;
|
if (rows.has(row.payment_id)) return false;
|
||||||
rows.set(row.payment_id, row);
|
rows.set(row.payment_id, row);
|
||||||
return true;
|
return true;
|
||||||
|
},
|
||||||
|
async markCheckoutPaid(sessionId: string, paymentId: string) {
|
||||||
|
paidSessions.push([sessionId, paymentId]);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
const SID = "cs_Ju1h16BXSobdRs7XWg9MUIj0";
|
||||||
|
// A hosted checkout session payment: CoinPay adds the session fields to data.
|
||||||
|
function sessionShaped(status = "confirmed", type = "payment.confirmed") {
|
||||||
|
const base = realShaped(status, type);
|
||||||
|
return {
|
||||||
|
...base,
|
||||||
|
data: {
|
||||||
|
...base.data,
|
||||||
|
checkout_session_id: SID,
|
||||||
|
customer_email: "guest@example.com",
|
||||||
|
account_id: "guest@example.com",
|
||||||
|
property: "logicsrc.com",
|
||||||
|
metadata: { ...base.data.metadata, account_id: "guest@example.com", email: "guest@example.com" }
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
@ -89,4 +111,32 @@ describe("CoinPay webhook (logicsrc Hire Us)", () => {
|
||||||
expect(await settleHireUsWebhook(foreign, store)).toMatchObject({ settled: false, reason: "unknown payment" });
|
expect(await settleHireUsWebhook(foreign, store)).toMatchObject({ settled: false, reason: "unknown payment" });
|
||||||
expect(store.rows.size).toBe(0);
|
expect(store.rows.size).toBe(0);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
it("settles a checkout-session payment from the session fields, once", async () => {
|
||||||
|
const store = memoryStore();
|
||||||
|
const first = await settleHireUsWebhook(sessionShaped(), store);
|
||||||
|
expect(first).toMatchObject({
|
||||||
|
settled: true,
|
||||||
|
duplicate: false,
|
||||||
|
payment_id: PAYMENT_ID,
|
||||||
|
checkout_session_id: SID,
|
||||||
|
account_id: "guest@example.com",
|
||||||
|
email: "guest@example.com"
|
||||||
|
});
|
||||||
|
expect(store.rows.get(PAYMENT_ID)).toMatchObject({ checkout_session_id: SID, property: "logicsrc.com", hours: 10 });
|
||||||
|
expect(store.paidSessions).toEqual([[SID, PAYMENT_ID]]);
|
||||||
|
|
||||||
|
const forwarded = await settleHireUsWebhook(sessionShaped("forwarded", "payment.forwarded"), store);
|
||||||
|
const replay = await settleHireUsWebhook(sessionShaped(), store);
|
||||||
|
expect(forwarded).toMatchObject({ settled: true, duplicate: true });
|
||||||
|
expect(replay).toMatchObject({ settled: true, duplicate: true });
|
||||||
|
expect(store.rows.size).toBe(1);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("does not record a pending session payment", async () => {
|
||||||
|
const store = memoryStore();
|
||||||
|
expect(await settleHireUsWebhook(sessionShaped("pending", "payment.pending"), store)).toMatchObject({ settled: false });
|
||||||
|
expect(store.rows.size).toBe(0);
|
||||||
|
expect(store.paidSessions).toEqual([]);
|
||||||
|
});
|
||||||
});
|
});
|
||||||
|
|
|
||||||
|
|
@ -7,6 +7,7 @@ import { renderPageMarkup } from "@/lib/page-markup";
|
||||||
import { siteFooterHtml } from "@/lib/site-footer";
|
import { siteFooterHtml } from "@/lib/site-footer";
|
||||||
import { choosePaymentRail, signSession, verifyCoinPayWebhook, verifySession } from "@/lib/coinpay";
|
import { choosePaymentRail, signSession, verifyCoinPayWebhook, verifySession } from "@/lib/coinpay";
|
||||||
import { POST as coinpayCheckout } from "@/app/api/hire-us/coinpay-checkout/route";
|
import { POST as coinpayCheckout } from "@/app/api/hire-us/coinpay-checkout/route";
|
||||||
|
import { setHireUsCheckoutStore, type HireUsCheckoutRow } from "@/lib/hire-us-payments";
|
||||||
import { POST as projectRequest } from "@/app/api/hire-us/project-request/route";
|
import { POST as projectRequest } from "@/app/api/hire-us/project-request/route";
|
||||||
import { GET as oauthStart } from "@/app/api/oauth/coinpay/start/route";
|
import { GET as oauthStart } from "@/app/api/oauth/coinpay/start/route";
|
||||||
import { GET as oauthCallback } from "@/app/api/oauth/coinpay/callback/route";
|
import { GET as oauthCallback } from "@/app/api/oauth/coinpay/callback/route";
|
||||||
|
|
@ -128,14 +129,52 @@ describe("payment rail selection", () => {
|
||||||
});
|
});
|
||||||
|
|
||||||
describe("POST /api/hire-us/coinpay-checkout", () => {
|
describe("POST /api/hire-us/coinpay-checkout", () => {
|
||||||
it("does not create checkout without server credentials", async () => {
|
const SID = "cs_Ju1h16BXSobdRs7XWg9MUIj0";
|
||||||
const response = await coinpayCheckout(
|
const recorded: HireUsCheckoutRow[] = [];
|
||||||
|
beforeEach(() => {
|
||||||
|
recorded.length = 0;
|
||||||
|
setHireUsCheckoutStore({ recordOpen: async (row) => void recorded.push(row) });
|
||||||
|
});
|
||||||
|
afterEach(() => setHireUsCheckoutStore(null));
|
||||||
|
|
||||||
|
function configure() {
|
||||||
|
process.env.COINPAY_API_KEY = "cp_test_key";
|
||||||
|
process.env.COINPAY_API_URL = "https://coinpayportal.example";
|
||||||
|
process.env.PUBLIC_URL = "https://logicsrc.test";
|
||||||
|
}
|
||||||
|
|
||||||
|
function mockSessions(answer: Record<string, unknown> = {}, status = 201) {
|
||||||
|
return vi.spyOn(globalThis, "fetch").mockImplementation(async (input) => {
|
||||||
|
const url = typeof input === "string" ? input : input.toString();
|
||||||
|
if (url.endsWith("/api/checkout/sessions")) {
|
||||||
|
return jsonResponse(
|
||||||
|
{
|
||||||
|
success: true,
|
||||||
|
id: SID,
|
||||||
|
url: `https://coinpayportal.example/checkout/${SID}`,
|
||||||
|
status: "open",
|
||||||
|
methods: [{ code: "USDC_POL" }, { code: "BTC" }, { code: "PAYPAL" }],
|
||||||
|
expires_at: "2026-10-21T14:00:00.000Z",
|
||||||
|
...answer
|
||||||
|
},
|
||||||
|
status
|
||||||
|
);
|
||||||
|
}
|
||||||
|
throw new Error(`unexpected fetch ${url}`);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
const post = (body: unknown) =>
|
||||||
|
coinpayCheckout(
|
||||||
new NextRequest("http://localhost/api/hire-us/coinpay-checkout", {
|
new NextRequest("http://localhost/api/hire-us/coinpay-checkout", {
|
||||||
method: "POST",
|
method: "POST",
|
||||||
headers: { "content-type": "application/json" },
|
headers: { "content-type": "application/json" },
|
||||||
body: "{}"
|
body: JSON.stringify(body)
|
||||||
})
|
})
|
||||||
);
|
);
|
||||||
|
|
||||||
|
it("does not create checkout without server credentials", async () => {
|
||||||
|
const response = await post({});
|
||||||
const body = await response.json();
|
const body = await response.json();
|
||||||
|
|
||||||
expect(response.status).toBe(503);
|
expect(response.status).toBe(503);
|
||||||
|
|
@ -143,56 +182,27 @@ describe("POST /api/hire-us/coinpay-checkout", () => {
|
||||||
expect(body).toEqual({ success: false, error: "CoinPay checkout is not configured" });
|
expect(body).toEqual({ success: false, error: "CoinPay checkout is not configured" });
|
||||||
});
|
});
|
||||||
|
|
||||||
it("creates a checkout with card and crypto when both rails are available", async () => {
|
it("opens a hosted checkout session with email, account, property and metadata", async () => {
|
||||||
process.env.COINPAY_API_KEY = "cp_test_key";
|
configure();
|
||||||
process.env.COINPAY_API_URL = "https://coinpayportal.example";
|
const fetchMock = mockSessions();
|
||||||
process.env.COINPAY_BUSINESS_ID = "business-123";
|
|
||||||
process.env.COINPAY_ELIGIBILITY_MERCHANT_ID = "merchant-123";
|
|
||||||
process.env.COINPAY_HIRE_US_BLOCKCHAIN = "USDC_POL";
|
|
||||||
process.env.PUBLIC_URL = "https://logicsrc.test";
|
|
||||||
|
|
||||||
const fetchMock = vi.spyOn(globalThis, "fetch").mockImplementation(async (input) => {
|
const response = await post({ email: "Buyer@Example.com" });
|
||||||
const url = typeof input === "string" ? input : input.toString();
|
|
||||||
if (url.includes("/api/payments/merchant-eligibility")) {
|
|
||||||
return jsonResponse({ success: true, accepts_card: true, accepts_crypto: true, chains: ["USDC_POL"] });
|
|
||||||
}
|
|
||||||
if (url.includes("/api/payments/create")) {
|
|
||||||
return jsonResponse(
|
|
||||||
{ success: true, payment: { id: "pay_123", stripe_checkout_url: "https://checkout.stripe.test/session" } },
|
|
||||||
201
|
|
||||||
);
|
|
||||||
}
|
|
||||||
throw new Error(`unexpected fetch ${url}`);
|
|
||||||
});
|
|
||||||
|
|
||||||
const response = await coinpayCheckout(
|
|
||||||
new NextRequest("http://localhost/api/hire-us/coinpay-checkout", {
|
|
||||||
method: "POST",
|
|
||||||
headers: { "content-type": "application/json" },
|
|
||||||
body: JSON.stringify({ email: "buyer@example.com" })
|
|
||||||
})
|
|
||||||
);
|
|
||||||
const body = await response.json();
|
const body = await response.json();
|
||||||
|
|
||||||
const createCall = fetchMock.mock.calls.find(([input]) =>
|
const [url, init] = fetchMock.mock.calls[0] as unknown as [string, RequestInit];
|
||||||
(typeof input === "string" ? input : input.toString()).includes("/api/payments/create")
|
const createBody = JSON.parse(String(init.body));
|
||||||
);
|
|
||||||
const createBody = JSON.parse((createCall?.[1]?.body as string) ?? "{}");
|
|
||||||
|
|
||||||
expect(response.status).toBe(201);
|
expect(url).toBe("https://coinpayportal.example/api/checkout/sessions");
|
||||||
expect(body.payment.checkout_url).toBe("https://checkout.stripe.test/session");
|
expect(init.headers).toMatchObject({ authorization: "Bearer cp_test_key" });
|
||||||
expect(createCall?.[1]?.headers).toMatchObject({ authorization: "Bearer cp_test_key" });
|
|
||||||
expect(createBody).toMatchObject({
|
expect(createBody).toMatchObject({
|
||||||
business_id: "business-123",
|
amount: 4000,
|
||||||
amount_usd: 4000,
|
currency: "USD",
|
||||||
payment_method: "both",
|
|
||||||
currency: "usdc_pol",
|
|
||||||
blockchain: "USDC_POL",
|
|
||||||
description: "LogicSRC Hire Us - 10 agent-hours @ $400/agent-hour",
|
description: "LogicSRC Hire Us - 10 agent-hours @ $400/agent-hour",
|
||||||
success_url: "https://logicsrc.test/hire-us?payment=success",
|
customer_email: "buyer@example.com",
|
||||||
|
account_id: "buyer@example.com",
|
||||||
|
property: "logicsrc.com",
|
||||||
|
success_url: "https://logicsrc.test/hire-us?payment=success&session={CHECKOUT_SESSION_ID}",
|
||||||
cancel_url: "https://logicsrc.test/hire-us?payment=cancelled",
|
cancel_url: "https://logicsrc.test/hire-us?payment=cancelled",
|
||||||
redirect_url: "https://logicsrc.test/hire-us?payment=coinpay",
|
|
||||||
webhook_url: "https://logicsrc.test/api/webhooks/coinpay",
|
|
||||||
metadata: {
|
metadata: {
|
||||||
product: "logicsrc-hire-us",
|
product: "logicsrc-hire-us",
|
||||||
billing: "metered_hours",
|
billing: "metered_hours",
|
||||||
|
|
@ -200,117 +210,72 @@ describe("POST /api/hire-us/coinpay-checkout", () => {
|
||||||
rate_usd_per_hour: 400,
|
rate_usd_per_hour: 400,
|
||||||
source: "logicsrc.com/hire-us",
|
source: "logicsrc.com/hire-us",
|
||||||
property: "logicsrc.com",
|
property: "logicsrc.com",
|
||||||
|
account_id: "buyer@example.com",
|
||||||
email: "buyer@example.com",
|
email: "buyer@example.com",
|
||||||
buyer_email: "buyer@example.com"
|
buyer_email: "buyer@example.com"
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
expect(createBody.business_id).toBeUndefined();
|
||||||
|
expect(response.status).toBe(201);
|
||||||
|
expect(body.payment).toMatchObject({
|
||||||
|
id: SID,
|
||||||
|
session_id: SID,
|
||||||
|
amount_usd: 4000,
|
||||||
|
checkout_url: `https://coinpayportal.example/checkout/${SID}`,
|
||||||
|
methods: ["USDC_POL", "BTC", "PAYPAL"]
|
||||||
|
});
|
||||||
|
expect(recorded).toEqual([
|
||||||
|
{ session_id: SID, account_id: "buyer@example.com", buyer_email: "buyer@example.com", hours: 10, rate_usd_per_hour: 400, amount_usd: 4000 }
|
||||||
|
]);
|
||||||
});
|
});
|
||||||
|
|
||||||
it("uses card-only checkout when configured crypto is not available", async () => {
|
it("uses the signed-in CoinPay account as account_id", async () => {
|
||||||
process.env.COINPAY_API_KEY = "cp_test_key";
|
configure();
|
||||||
process.env.COINPAY_API_URL = "https://coinpayportal.example";
|
process.env.COINPAY_OAUTH_CLIENT_SECRET = "oauth-secret-for-session-signing";
|
||||||
process.env.COINPAY_BUSINESS_ID = "business-123";
|
const fetchMock = mockSessions();
|
||||||
process.env.COINPAY_ELIGIBILITY_MERCHANT_ID = "merchant-123";
|
const cookie = signSession({ sub: "coinpay-user-9", email: "acct@example.com", exp: Math.floor(Date.now() / 1000) + 600 });
|
||||||
|
|
||||||
vi.spyOn(globalThis, "fetch").mockImplementation(async (input) => {
|
|
||||||
const url = typeof input === "string" ? input : input.toString();
|
|
||||||
if (url.includes("/api/payments/merchant-eligibility")) {
|
|
||||||
return jsonResponse({ success: true, accepts_card: true, accepts_crypto: false, chains: [] });
|
|
||||||
}
|
|
||||||
return jsonResponse(
|
|
||||||
{ success: true, payment: { id: "pay_123", stripe_checkout_url: "https://checkout.stripe.test/card-only" } },
|
|
||||||
201
|
|
||||||
);
|
|
||||||
});
|
|
||||||
|
|
||||||
const response = await coinpayCheckout(
|
const response = await coinpayCheckout(
|
||||||
new NextRequest("http://localhost/api/hire-us/coinpay-checkout", {
|
new NextRequest("http://localhost/api/hire-us/coinpay-checkout", {
|
||||||
method: "POST",
|
method: "POST",
|
||||||
headers: { "content-type": "application/json" },
|
headers: { "content-type": "application/json", cookie: `logicsrc_coinpay_session=${cookie}` },
|
||||||
body: JSON.stringify({ email: "buyer@example.com" })
|
body: "{}"
|
||||||
})
|
})
|
||||||
);
|
);
|
||||||
const body = await response.json();
|
|
||||||
|
|
||||||
expect(response.status).toBe(201);
|
expect(response.status).toBe(201);
|
||||||
expect(body.payment.checkout_url).toBe("https://checkout.stripe.test/card-only");
|
const createBody = JSON.parse(String((fetchMock.mock.calls[0] as unknown as [string, RequestInit])[1].body));
|
||||||
|
expect(createBody).toMatchObject({ account_id: "coinpay-user-9", customer_email: "acct@example.com" });
|
||||||
});
|
});
|
||||||
|
|
||||||
it("falls back when CoinPay returns an invalid checkout amount", async () => {
|
it("requires an email", async () => {
|
||||||
process.env.COINPAY_API_KEY = "cp_test_key";
|
configure();
|
||||||
process.env.COINPAY_API_URL = "https://coinpayportal.example";
|
const fetchMock = vi.spyOn(globalThis, "fetch");
|
||||||
process.env.COINPAY_BUSINESS_ID = "business-123";
|
const response = await post({});
|
||||||
process.env.COINPAY_ELIGIBILITY_MERCHANT_ID = "merchant-123";
|
expect(response.status).toBe(422);
|
||||||
|
expect(fetchMock).not.toHaveBeenCalled();
|
||||||
vi.spyOn(globalThis, "fetch").mockImplementation(async (input) => {
|
|
||||||
const url = typeof input === "string" ? input : input.toString();
|
|
||||||
if (url.includes("/api/payments/merchant-eligibility")) {
|
|
||||||
return jsonResponse({ success: true, accepts_card: true, accepts_crypto: false, chains: [] });
|
|
||||||
}
|
|
||||||
return jsonResponse({ success: true, payment: { id: "pay_123", amount_usd: "not-a-number" } }, 201);
|
|
||||||
});
|
|
||||||
|
|
||||||
const response = await coinpayCheckout(
|
|
||||||
new NextRequest("http://localhost/api/hire-us/coinpay-checkout", { method: "POST", body: "{}" })
|
|
||||||
);
|
|
||||||
const body = await response.json();
|
|
||||||
|
|
||||||
expect(response.status).toBe(201);
|
|
||||||
expect(body.payment.amount_usd).toBe(4000);
|
|
||||||
});
|
});
|
||||||
|
|
||||||
it("prices the checkout from the approved hours", async () => {
|
it("prices the checkout from the approved hours", async () => {
|
||||||
process.env.COINPAY_API_KEY = "cp_test_key";
|
configure();
|
||||||
process.env.COINPAY_API_URL = "https://coinpayportal.example";
|
const fetchMock = mockSessions();
|
||||||
process.env.COINPAY_BUSINESS_ID = "business-123";
|
|
||||||
process.env.COINPAY_ELIGIBILITY_MERCHANT_ID = "merchant-123";
|
|
||||||
process.env.COINPAY_HIRE_US_BLOCKCHAIN = "USDC_POL";
|
|
||||||
|
|
||||||
const fetchMock = vi.spyOn(globalThis, "fetch").mockImplementation(async (input) => {
|
const response = await post({ hours: 25.25, email: "buyer@example.com" });
|
||||||
const url = typeof input === "string" ? input : input.toString();
|
|
||||||
if (url.includes("/api/payments/merchant-eligibility")) {
|
|
||||||
return jsonResponse({ success: true, accepts_card: true, accepts_crypto: true, chains: ["USDC_POL"] });
|
|
||||||
}
|
|
||||||
return jsonResponse({ success: true, payment: { id: "pay_123", amount_usd: 10100 } }, 201);
|
|
||||||
});
|
|
||||||
|
|
||||||
const response = await coinpayCheckout(
|
|
||||||
new NextRequest("http://localhost/api/hire-us/coinpay-checkout", {
|
|
||||||
method: "POST",
|
|
||||||
headers: { "content-type": "application/json" },
|
|
||||||
body: JSON.stringify({ hours: 25.25 })
|
|
||||||
})
|
|
||||||
);
|
|
||||||
const body = await response.json();
|
const body = await response.json();
|
||||||
|
const createBody = JSON.parse(String((fetchMock.mock.calls[0] as unknown as [string, RequestInit])[1].body));
|
||||||
const createCall = fetchMock.mock.calls.find(([input]) =>
|
|
||||||
(typeof input === "string" ? input : input.toString()).includes("/api/payments/create")
|
|
||||||
);
|
|
||||||
const createBody = JSON.parse((createCall?.[1]?.body as string) ?? "{}");
|
|
||||||
|
|
||||||
expect(response.status).toBe(201);
|
expect(response.status).toBe(201);
|
||||||
expect(createBody.amount_usd).toBe(10100);
|
expect(createBody.amount).toBe(10100);
|
||||||
expect(createBody.description).toBe("LogicSRC Hire Us - 25.25 agent-hours @ $400/agent-hour");
|
expect(createBody.description).toBe("LogicSRC Hire Us - 25.25 agent-hours @ $400/agent-hour");
|
||||||
expect(createBody.metadata).toMatchObject({ billing: "metered_hours", hours: 25.25, rate_usd_per_hour: 400 });
|
expect(createBody.metadata).toMatchObject({ billing: "metered_hours", hours: 25.25, rate_usd_per_hour: 400 });
|
||||||
expect(body.payment).toMatchObject({ amount_usd: 10100, hours: 25.25, rate_usd_per_hour: 400 });
|
expect(body.payment).toMatchObject({ amount_usd: 10100, hours: 25.25, rate_usd_per_hour: 400 });
|
||||||
});
|
});
|
||||||
|
|
||||||
it("rejects hours below the minimum engagement or off the quarter-hour", async () => {
|
it("rejects hours below the minimum engagement or off the quarter-hour", async () => {
|
||||||
process.env.COINPAY_API_KEY = "cp_test_key";
|
configure();
|
||||||
process.env.COINPAY_API_URL = "https://coinpayportal.example";
|
|
||||||
process.env.COINPAY_BUSINESS_ID = "business-123";
|
|
||||||
process.env.COINPAY_ELIGIBILITY_MERCHANT_ID = "merchant-123";
|
|
||||||
|
|
||||||
const fetchMock = vi.spyOn(globalThis, "fetch");
|
const fetchMock = vi.spyOn(globalThis, "fetch");
|
||||||
|
|
||||||
for (const hours of [9.75, 12.3, "many", -40]) {
|
for (const hours of [9.75, 12.3, "many", -40]) {
|
||||||
const response = await coinpayCheckout(
|
const response = await post({ hours, email: "buyer@example.com" });
|
||||||
new NextRequest("http://localhost/api/hire-us/coinpay-checkout", {
|
|
||||||
method: "POST",
|
|
||||||
headers: { "content-type": "application/json" },
|
|
||||||
body: JSON.stringify({ hours })
|
|
||||||
})
|
|
||||||
);
|
|
||||||
const body = await response.json();
|
const body = await response.json();
|
||||||
|
|
||||||
expect(response.status).toBe(422);
|
expect(response.status).toBe(422);
|
||||||
|
|
@ -323,32 +288,20 @@ describe("POST /api/hire-us/coinpay-checkout", () => {
|
||||||
expect(fetchMock).not.toHaveBeenCalled();
|
expect(fetchMock).not.toHaveBeenCalled();
|
||||||
});
|
});
|
||||||
|
|
||||||
it("does not create checkout when no payment rail is available", async () => {
|
it("passes CoinPay's refusal through and records nothing", async () => {
|
||||||
process.env.COINPAY_API_KEY = "cp_test_key";
|
configure();
|
||||||
process.env.COINPAY_API_URL = "https://coinpayportal.example";
|
mockSessions({ success: false, id: undefined, url: undefined, code: "NO_PAYMENT_METHODS", error: "No payment methods" }, 400);
|
||||||
process.env.COINPAY_BUSINESS_ID = "business-123";
|
const response = await post({ email: "buyer@example.com" });
|
||||||
process.env.COINPAY_ELIGIBILITY_MERCHANT_ID = "merchant-123";
|
expect(response.status).toBe(400);
|
||||||
|
expect(await response.json()).toEqual({ success: false, error: "No payment methods" });
|
||||||
|
expect(recorded).toEqual([]);
|
||||||
|
});
|
||||||
|
|
||||||
const fetchMock = vi.spyOn(globalThis, "fetch").mockImplementation(async () =>
|
it("refuses a checkout URL on another origin", async () => {
|
||||||
jsonResponse({ success: true, accepts_card: false, accepts_crypto: false, chains: [] })
|
configure();
|
||||||
);
|
mockSessions({ url: "https://evil.example/checkout" });
|
||||||
|
const response = await post({ email: "buyer@example.com" });
|
||||||
const response = await coinpayCheckout(
|
expect(response.status).toBe(502);
|
||||||
new NextRequest("http://localhost/api/hire-us/coinpay-checkout", {
|
|
||||||
method: "POST",
|
|
||||||
headers: { "content-type": "application/json" },
|
|
||||||
body: JSON.stringify({ email: "buyer@example.com" })
|
|
||||||
})
|
|
||||||
);
|
|
||||||
const body = await response.json();
|
|
||||||
|
|
||||||
expect(response.status).toBe(503);
|
|
||||||
expect(body).toEqual({ success: false, error: "CoinPay checkout is not available for this merchant" });
|
|
||||||
expect(
|
|
||||||
fetchMock.mock.calls.some(([input]) =>
|
|
||||||
(typeof input === "string" ? input : input.toString()).includes("/api/payments/create")
|
|
||||||
)
|
|
||||||
).toBe(false);
|
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -1,21 +1,23 @@
|
||||||
import type { NextRequest } from "next/server";
|
import type { NextRequest } from "next/server";
|
||||||
import { json } from "@/lib/http";
|
import { json } from "@/lib/http";
|
||||||
import {
|
import { COINPAY_SESSION_COOKIE, parseJson, verifySession } from "@/lib/coinpay";
|
||||||
COINPAY_SESSION_COOKIE,
|
import { HIRE_US_PRODUCT } from "@/lib/coinpay-webhook";
|
||||||
choosePaymentRail,
|
import { hireUsCheckoutStore } from "@/lib/hire-us-payments";
|
||||||
fetchMerchantEligibility,
|
|
||||||
parseJson,
|
|
||||||
verifySession
|
|
||||||
} from "@/lib/coinpay";
|
|
||||||
|
|
||||||
export const dynamic = "force-dynamic";
|
export const dynamic = "force-dynamic";
|
||||||
|
|
||||||
// POST /api/hire-us/coinpay-checkout — create a CoinPay checkout for approved
|
// POST /api/hire-us/coinpay-checkout — open a CoinPay hosted checkout session for
|
||||||
// Hire Us hours at $400/hour/agent, choosing card/crypto/both based on merchant
|
// approved Hire Us hours at $400/hour/agent. The buyer picks any coin the
|
||||||
// eligibility. Billing is metered: the caller supplies the approved hours and the
|
// business has a wallet for, or PayPal, on CoinPay's page. Billing is metered:
|
||||||
// amount is derived from them, never a fixed recurring figure.
|
// the caller supplies the approved hours and the amount is derived from them.
|
||||||
|
//
|
||||||
|
// Body: { hours?: number (default 10), email?: string }. An email is required
|
||||||
|
// (from the body or the signed-in CoinPay session). account_id is the CoinPay
|
||||||
|
// account when signed in, else the buyer email (guest checkout).
|
||||||
const RATE_USD_PER_HOUR = 400;
|
const RATE_USD_PER_HOUR = 400;
|
||||||
const MINIMUM_HOURS = 10;
|
const MINIMUM_HOURS = 10;
|
||||||
|
const PROPERTY = "logicsrc.com";
|
||||||
|
const EMAIL_RE = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
|
||||||
|
|
||||||
// Hours represent total approved agent-hours, not wall-clock duration.
|
// Hours represent total approved agent-hours, not wall-clock duration.
|
||||||
// Hours are quoted in quarter-hour increments; anything finer is a rounding
|
// Hours are quoted in quarter-hour increments; anything finer is a rounding
|
||||||
|
|
@ -30,21 +32,16 @@ function parseHours(value: unknown): number | null {
|
||||||
|
|
||||||
export async function POST(request: NextRequest) {
|
export async function POST(request: NextRequest) {
|
||||||
const apiKey = process.env.COINPAY_API_KEY;
|
const apiKey = process.env.COINPAY_API_KEY;
|
||||||
const eligibilityApiKey = process.env.COINPAY_ELIGIBILITY_API_KEY || process.env.COINPAY_AGENT_API_KEY || apiKey;
|
const apiUrl = (process.env.COINPAY_API_URL || "https://coinpayportal.com").replace(/\/+$/, "").replace(/\/api$/, "");
|
||||||
const businessId = process.env.COINPAY_BUSINESS_ID || process.env.COINPAY_MERCHANT_ID;
|
const publicUrl = (process.env.PUBLIC_URL || "https://logicsrc.com").replace(/\/+$/, "");
|
||||||
const eligibilityMerchantId = process.env.COINPAY_ELIGIBILITY_MERCHANT_ID || process.env.COINPAY_MERCHANT_ID;
|
|
||||||
const apiUrl = process.env.COINPAY_API_URL || "https://coinpayportal.com";
|
|
||||||
const blockchain = process.env.COINPAY_HIRE_US_BLOCKCHAIN || "USDC_POL";
|
|
||||||
const publicUrl = process.env.PUBLIC_URL || "https://logicsrc.com";
|
|
||||||
|
|
||||||
if (!apiKey || !businessId) {
|
if (!apiKey) {
|
||||||
return json({ success: false, error: "CoinPay checkout is not configured" }, 503);
|
return json({ success: false, error: "CoinPay checkout is not configured" }, 503);
|
||||||
}
|
}
|
||||||
|
|
||||||
try {
|
try {
|
||||||
const body = (await request.json().catch(() => ({}))) as Record<string, unknown>;
|
const body = (await request.json().catch(() => ({}))) as Record<string, unknown>;
|
||||||
// A signed-in CoinPay session (OAuth cookie) identifies the account; the
|
// A signed-in CoinPay session (OAuth cookie) identifies the account.
|
||||||
// webhook maps the settled payment back to it via metadata.account_id.
|
|
||||||
const sessionCookie = request.cookies.get(COINPAY_SESSION_COOKIE)?.value;
|
const sessionCookie = request.cookies.get(COINPAY_SESSION_COOKIE)?.value;
|
||||||
let session: Record<string, unknown> | null = null;
|
let session: Record<string, unknown> | null = null;
|
||||||
try {
|
try {
|
||||||
|
|
@ -52,10 +49,10 @@ export async function POST(request: NextRequest) {
|
||||||
} catch {
|
} catch {
|
||||||
session = null;
|
session = null;
|
||||||
}
|
}
|
||||||
const accountId = typeof session?.sub === "string" ? session.sub : "";
|
const sessionAccount = typeof session?.sub === "string" ? session.sub : "";
|
||||||
const sessionEmail = typeof session?.email === "string" ? session.email : "";
|
const sessionEmail = typeof session?.email === "string" ? session.email : "";
|
||||||
const bodyEmail = typeof body.email === "string" ? body.email.trim().slice(0, 160) : "";
|
const bodyEmail = typeof body.email === "string" ? body.email.trim().slice(0, 160) : "";
|
||||||
const buyerEmail = bodyEmail || sessionEmail;
|
const buyerEmail = (bodyEmail || sessionEmail).toLowerCase();
|
||||||
const hours = body.hours === undefined ? MINIMUM_HOURS : parseHours(body.hours);
|
const hours = body.hours === undefined ? MINIMUM_HOURS : parseHours(body.hours);
|
||||||
|
|
||||||
if (hours === null) {
|
if (hours === null) {
|
||||||
|
|
@ -67,52 +64,53 @@ export async function POST(request: NextRequest) {
|
||||||
422
|
422
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
if (!EMAIL_RE.test(buyerEmail)) {
|
||||||
const amountUsdDue = Math.round(hours * RATE_USD_PER_HOUR * 100) / 100;
|
return json({ success: false, error: "An email address is required for the receipt" }, 422);
|
||||||
const eligibility = await fetchMerchantEligibility(apiUrl, eligibilityApiKey, eligibilityMerchantId);
|
|
||||||
const paymentRail = choosePaymentRail(eligibility, blockchain);
|
|
||||||
|
|
||||||
if (!paymentRail) {
|
|
||||||
return json({ success: false, error: "CoinPay checkout is not available for this merchant" }, 503);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
const checkoutResponse = await fetch(new URL("/api/payments/create", apiUrl), {
|
const accountId = sessionAccount || buyerEmail;
|
||||||
|
const amountUsdDue = Math.round(hours * RATE_USD_PER_HOUR * 100) / 100;
|
||||||
|
|
||||||
|
const checkoutResponse = await fetch(`${apiUrl}/api/checkout/sessions`, {
|
||||||
method: "POST",
|
method: "POST",
|
||||||
headers: {
|
headers: {
|
||||||
authorization: `Bearer ${apiKey}`,
|
authorization: `Bearer ${apiKey}`,
|
||||||
"content-type": "application/json"
|
"content-type": "application/json"
|
||||||
},
|
},
|
||||||
body: JSON.stringify({
|
body: JSON.stringify({
|
||||||
business_id: businessId,
|
amount: amountUsdDue,
|
||||||
amount_usd: amountUsdDue,
|
currency: "USD",
|
||||||
payment_method: paymentRail.method,
|
|
||||||
currency: paymentRail.currency,
|
|
||||||
...(paymentRail.blockchain ? { blockchain: paymentRail.blockchain } : {}),
|
|
||||||
description: `LogicSRC Hire Us - ${hours} agent-hours @ $${RATE_USD_PER_HOUR}/agent-hour`,
|
description: `LogicSRC Hire Us - ${hours} agent-hours @ $${RATE_USD_PER_HOUR}/agent-hour`,
|
||||||
success_url: `${publicUrl}/hire-us?payment=success`,
|
customer_email: buyerEmail,
|
||||||
|
account_id: accountId,
|
||||||
|
property: PROPERTY,
|
||||||
|
success_url: `${publicUrl}/hire-us?payment=success&session={CHECKOUT_SESSION_ID}`,
|
||||||
cancel_url: `${publicUrl}/hire-us?payment=cancelled`,
|
cancel_url: `${publicUrl}/hire-us?payment=cancelled`,
|
||||||
redirect_url: `${publicUrl}/hire-us?payment=coinpay`,
|
expires_in_minutes: 60,
|
||||||
webhook_url: `${publicUrl}/api/webhooks/coinpay`,
|
|
||||||
metadata: {
|
metadata: {
|
||||||
product: "logicsrc-hire-us",
|
product: HIRE_US_PRODUCT,
|
||||||
billing: "metered_hours",
|
billing: "metered_hours",
|
||||||
unit: "agent_hour",
|
unit: "agent_hour",
|
||||||
hours,
|
hours,
|
||||||
rate_usd_per_hour: RATE_USD_PER_HOUR,
|
rate_usd_per_hour: RATE_USD_PER_HOUR,
|
||||||
source: "logicsrc.com/hire-us",
|
source: "logicsrc.com/hire-us",
|
||||||
property: "logicsrc.com",
|
property: PROPERTY,
|
||||||
...(accountId ? { account_id: accountId } : {}),
|
account_id: accountId,
|
||||||
...(buyerEmail ? { email: buyerEmail, buyer_email: buyerEmail } : {})
|
email: buyerEmail,
|
||||||
|
buyer_email: buyerEmail
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
});
|
});
|
||||||
|
|
||||||
const responseText = await checkoutResponse.text();
|
const responseText = await checkoutResponse.text();
|
||||||
const payload = parseJson(responseText);
|
const payload = parseJson(responseText);
|
||||||
|
const sessionId = typeof payload.id === "string" ? payload.id : "";
|
||||||
|
const checkoutUrl = typeof payload.url === "string" ? payload.url : "";
|
||||||
|
|
||||||
if (!checkoutResponse.ok || payload.success !== true) {
|
if (!checkoutResponse.ok || !/^cs_[A-Za-z0-9]{8,64}$/.test(sessionId) || !checkoutUrl) {
|
||||||
console.error("[coinpay] checkout create failed", {
|
console.error("[coinpay] checkout session create failed", {
|
||||||
status: checkoutResponse.status,
|
status: checkoutResponse.status,
|
||||||
|
code: payload.code ?? null,
|
||||||
error: (payload.error as string) || responseText.slice(0, 300)
|
error: (payload.error as string) || responseText.slice(0, 300)
|
||||||
});
|
});
|
||||||
return json(
|
return json(
|
||||||
|
|
@ -120,25 +118,45 @@ export async function POST(request: NextRequest) {
|
||||||
checkoutResponse.ok ? 502 : checkoutResponse.status
|
checkoutResponse.ok ? 502 : checkoutResponse.status
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
// Only ever send buyers to CoinPay's own origin.
|
||||||
|
if (new URL(checkoutUrl, apiUrl).origin !== new URL(apiUrl).origin) {
|
||||||
|
console.error("[coinpay] checkout session url on another origin");
|
||||||
|
return json({ success: false, error: "CoinPay checkout failed" }, 502);
|
||||||
|
}
|
||||||
|
|
||||||
const payment = (payload.payment as Record<string, unknown>) || {};
|
try {
|
||||||
const amountUsd = Number(payment.amount_usd ?? payment.amount ?? amountUsdDue);
|
await hireUsCheckoutStore().recordOpen({
|
||||||
|
session_id: sessionId,
|
||||||
|
account_id: accountId,
|
||||||
|
buyer_email: buyerEmail,
|
||||||
|
hours,
|
||||||
|
rate_usd_per_hour: RATE_USD_PER_HOUR,
|
||||||
|
amount_usd: amountUsdDue
|
||||||
|
});
|
||||||
|
} catch (error) {
|
||||||
|
// The session still settles from its own fields on the webhook.
|
||||||
|
console.error("[coinpay] could not record checkout session", error);
|
||||||
|
}
|
||||||
|
|
||||||
|
const methods = Array.isArray(payload.methods)
|
||||||
|
? payload.methods
|
||||||
|
.map((m) => (typeof m === "string" ? m : String((m as { code?: unknown })?.code ?? "")))
|
||||||
|
.filter(Boolean)
|
||||||
|
: [];
|
||||||
return json(
|
return json(
|
||||||
{
|
{
|
||||||
success: true,
|
success: true,
|
||||||
payment: {
|
payment: {
|
||||||
id: payment.id,
|
id: sessionId,
|
||||||
amount_usd: Number.isFinite(amountUsd) ? amountUsd : amountUsdDue,
|
session_id: sessionId,
|
||||||
|
amount_usd: amountUsdDue,
|
||||||
hours,
|
hours,
|
||||||
rate_usd_per_hour: RATE_USD_PER_HOUR,
|
rate_usd_per_hour: RATE_USD_PER_HOUR,
|
||||||
payment_method: payment.stripe_checkout_url ? "card" : paymentRail.method,
|
payment_method: "checkout",
|
||||||
currency: payment.currency ?? payment.blockchain ?? paymentRail.blockchain ?? paymentRail.currency,
|
methods,
|
||||||
crypto_amount: payment.amount_crypto ?? payment.crypto_amount ?? null,
|
expires_at: payload.expires_at ?? null,
|
||||||
address: payment.payment_address ?? null,
|
status: payload.status ?? "open",
|
||||||
qr_code: payment.qr_code ?? null,
|
checkout_url: checkoutUrl
|
||||||
expires_at: payment.expires_at ?? null,
|
|
||||||
status: payment.status ?? "pending",
|
|
||||||
checkout_url: payment.stripe_checkout_url ?? payload.checkout_url ?? payment.checkout_url ?? null
|
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
201
|
201
|
||||||
|
|
|
||||||
|
|
@ -2,7 +2,8 @@
|
||||||
//
|
//
|
||||||
// CoinPay signs and sends a NESTED body (coinpayportal src/lib/webhooks/service.ts):
|
// CoinPay signs and sends a NESTED body (coinpayportal src/lib/webhooks/service.ts):
|
||||||
// { id: "evt_<paymentId>_<ts>", type: "payment.confirmed",
|
// { id: "evt_<paymentId>_<ts>", type: "payment.confirmed",
|
||||||
// data: { payment_id, status, amount, amount_usd, metadata: {...} },
|
// data: { payment_id, status, amount, amount_usd, checkout_session_id,
|
||||||
|
// customer_email, account_id, property, metadata: {...} },
|
||||||
// created_at, business_id }
|
// created_at, business_id }
|
||||||
// The top-level `id` is the EVENT id, not the payment id. Read `data` first and
|
// The top-level `id` is the EVENT id, not the payment id. Read `data` first and
|
||||||
// fall back to the flat shape only for the legacy test sender.
|
// fall back to the flat shape only for the legacy test sender.
|
||||||
|
|
@ -13,6 +14,11 @@ export interface CoinPayWebhookEvent {
|
||||||
paymentId: string | null;
|
paymentId: string | null;
|
||||||
status: string;
|
status: string;
|
||||||
amountUsd: number | null;
|
amountUsd: number | null;
|
||||||
|
/** Hosted checkout session the payment belongs to (cs_...), when there is one. */
|
||||||
|
checkoutSessionId: string | null;
|
||||||
|
accountId: string | null;
|
||||||
|
customerEmail: string | null;
|
||||||
|
property: string | null;
|
||||||
metadata: Record<string, unknown>;
|
metadata: Record<string, unknown>;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -43,13 +49,19 @@ export function readCoinPayWebhook(payload: Record<string, unknown>): CoinPayWeb
|
||||||
const type = asString(payload.type) ?? asString(payload.event);
|
const type = asString(payload.type) ?? asString(payload.event);
|
||||||
let status = (asString(d.status) ?? "").toLowerCase();
|
let status = (asString(d.status) ?? "").toLowerCase();
|
||||||
if (!status && type && SETTLED_TYPES.has(type)) status = type.slice("payment.".length);
|
if (!status && type && SETTLED_TYPES.has(type)) status = type.slice("payment.".length);
|
||||||
|
const metadata = asRecord(d.metadata) ?? asRecord(payload.metadata) ?? {};
|
||||||
|
const sid = asString(d.checkout_session_id) ?? asString(metadata.checkout_session_id);
|
||||||
return {
|
return {
|
||||||
eventId: nested ? asString(payload.id) : null,
|
eventId: nested ? asString(payload.id) : null,
|
||||||
type,
|
type,
|
||||||
paymentId,
|
paymentId,
|
||||||
status,
|
status,
|
||||||
amountUsd: asNumber(d.amount_usd) ?? asNumber(d.amount),
|
amountUsd: asNumber(d.amount_usd) ?? asNumber(d.amount),
|
||||||
metadata: asRecord(d.metadata) ?? asRecord(payload.metadata) ?? {}
|
checkoutSessionId: sid && /^cs_[A-Za-z0-9]{8,64}$/.test(sid) ? sid : null,
|
||||||
|
accountId: asString(d.account_id) ?? asString(metadata.account_id),
|
||||||
|
customerEmail: asString(d.customer_email) ?? asString(metadata.email) ?? asString(metadata.buyer_email),
|
||||||
|
property: asString(d.property) ?? asString(metadata.property),
|
||||||
|
metadata
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -68,16 +80,27 @@ export interface HireUsPaymentRow {
|
||||||
account_id: string | null;
|
account_id: string | null;
|
||||||
buyer_email: string | null;
|
buyer_email: string | null;
|
||||||
property: string | null;
|
property: string | null;
|
||||||
|
checkout_session_id: string | null;
|
||||||
metadata: Record<string, unknown>;
|
metadata: Record<string, unknown>;
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface HireUsPaymentStore {
|
export interface HireUsPaymentStore {
|
||||||
/** Insert once; resolve true if this call created the row, false if it already existed. */
|
/** Insert once; resolve true if this call created the row, false if it already existed. */
|
||||||
insertIfAbsent(row: HireUsPaymentRow): Promise<boolean>;
|
insertIfAbsent(row: HireUsPaymentRow): Promise<boolean>;
|
||||||
|
/** Mark the hosted checkout session paid (no-op if it is already). */
|
||||||
|
markCheckoutPaid?(sessionId: string, paymentId: string): Promise<void>;
|
||||||
}
|
}
|
||||||
|
|
||||||
export type SettleResult =
|
export type SettleResult =
|
||||||
| { handled: true; settled: true; duplicate: boolean; payment_id: string; account_id: string | null; email: string | null }
|
| {
|
||||||
|
handled: true;
|
||||||
|
settled: true;
|
||||||
|
duplicate: boolean;
|
||||||
|
payment_id: string;
|
||||||
|
checkout_session_id: string | null;
|
||||||
|
account_id: string | null;
|
||||||
|
email: string | null;
|
||||||
|
}
|
||||||
| { handled: true; settled: false; reason: string; payment_id: string | null };
|
| { handled: true; settled: false; reason: string; payment_id: string | null };
|
||||||
|
|
||||||
export async function settleHireUsWebhook(
|
export async function settleHireUsWebhook(
|
||||||
|
|
@ -95,8 +118,10 @@ export async function settleHireUsWebhook(
|
||||||
return { handled: true, settled: false, reason: "unknown payment", payment_id: event.paymentId };
|
return { handled: true, settled: false, reason: "unknown payment", payment_id: event.paymentId };
|
||||||
}
|
}
|
||||||
|
|
||||||
const accountId = asString(meta.account_id);
|
// Session fields first (CoinPay copies them onto every session payment),
|
||||||
const email = asString(meta.email) ?? asString(meta.buyer_email);
|
// then our own metadata for payments opened before checkout sessions.
|
||||||
|
const accountId = event.accountId;
|
||||||
|
const email = event.customerEmail;
|
||||||
const inserted = await store.insertIfAbsent({
|
const inserted = await store.insertIfAbsent({
|
||||||
payment_id: event.paymentId,
|
payment_id: event.paymentId,
|
||||||
event_id: event.eventId,
|
event_id: event.eventId,
|
||||||
|
|
@ -107,8 +132,20 @@ export async function settleHireUsWebhook(
|
||||||
rate_usd_per_hour: asNumber(meta.rate_usd_per_hour),
|
rate_usd_per_hour: asNumber(meta.rate_usd_per_hour),
|
||||||
account_id: accountId,
|
account_id: accountId,
|
||||||
buyer_email: email,
|
buyer_email: email,
|
||||||
property: asString(meta.property),
|
property: event.property,
|
||||||
|
checkout_session_id: event.checkoutSessionId,
|
||||||
metadata: meta
|
metadata: meta
|
||||||
});
|
});
|
||||||
return { handled: true, settled: true, duplicate: !inserted, payment_id: event.paymentId, account_id: accountId, email };
|
if (event.checkoutSessionId && store.markCheckoutPaid) {
|
||||||
|
await store.markCheckoutPaid(event.checkoutSessionId, event.paymentId);
|
||||||
|
}
|
||||||
|
return {
|
||||||
|
handled: true,
|
||||||
|
settled: true,
|
||||||
|
duplicate: !inserted,
|
||||||
|
payment_id: event.paymentId,
|
||||||
|
checkout_session_id: event.checkoutSessionId,
|
||||||
|
account_id: accountId,
|
||||||
|
email
|
||||||
|
};
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -2,7 +2,8 @@ import { serviceClient } from "@/lib/supabase";
|
||||||
import type { HireUsPaymentRow, HireUsPaymentStore } from "@/lib/coinpay-webhook";
|
import type { HireUsPaymentRow, HireUsPaymentStore } from "@/lib/coinpay-webhook";
|
||||||
|
|
||||||
// Supabase-backed store for settled Hire Us payments (table hire_us_payments,
|
// Supabase-backed store for settled Hire Us payments (table hire_us_payments,
|
||||||
// payment_id primary key). ignoreDuplicates makes a redelivery a no-op.
|
// payment_id primary key). ignoreDuplicates makes a redelivery a no-op. A paid
|
||||||
|
// checkout session is also marked on hire_us_checkouts.
|
||||||
export function supabaseHireUsPaymentStore(): HireUsPaymentStore {
|
export function supabaseHireUsPaymentStore(): HireUsPaymentStore {
|
||||||
return {
|
return {
|
||||||
async insertIfAbsent(row: HireUsPaymentRow) {
|
async insertIfAbsent(row: HireUsPaymentRow) {
|
||||||
|
|
@ -12,6 +13,47 @@ export function supabaseHireUsPaymentStore(): HireUsPaymentStore {
|
||||||
.select("payment_id");
|
.select("payment_id");
|
||||||
if (error) throw new Error(`hire_us_payments insert failed: ${error.message}`);
|
if (error) throw new Error(`hire_us_payments insert failed: ${error.message}`);
|
||||||
return Array.isArray(data) && data.length > 0;
|
return Array.isArray(data) && data.length > 0;
|
||||||
|
},
|
||||||
|
async markCheckoutPaid(sessionId: string, paymentId: string) {
|
||||||
|
const { error } = await serviceClient()
|
||||||
|
.from("hire_us_checkouts")
|
||||||
|
.update({ status: "paid", payment_id: paymentId, paid_at: new Date().toISOString() })
|
||||||
|
.eq("session_id", sessionId)
|
||||||
|
.eq("status", "open");
|
||||||
|
if (error) throw new Error(`hire_us_checkouts update failed: ${error.message}`);
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export interface HireUsCheckoutRow {
|
||||||
|
session_id: string;
|
||||||
|
account_id: string;
|
||||||
|
buyer_email: string;
|
||||||
|
hours: number;
|
||||||
|
rate_usd_per_hour: number;
|
||||||
|
amount_usd: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface HireUsCheckoutStore {
|
||||||
|
recordOpen(row: HireUsCheckoutRow): Promise<void>;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function supabaseHireUsCheckoutStore(): HireUsCheckoutStore {
|
||||||
|
return {
|
||||||
|
async recordOpen(row: HireUsCheckoutRow) {
|
||||||
|
const { error } = await serviceClient().from("hire_us_checkouts").insert(row);
|
||||||
|
if (error) throw new Error(`hire_us_checkouts insert failed: ${error.message}`);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
let checkoutStoreOverride: HireUsCheckoutStore | null = null;
|
||||||
|
|
||||||
|
/** The checkout store routes use; tests swap in a memory store. */
|
||||||
|
export function hireUsCheckoutStore(): HireUsCheckoutStore {
|
||||||
|
return checkoutStoreOverride ?? supabaseHireUsCheckoutStore();
|
||||||
|
}
|
||||||
|
|
||||||
|
export function setHireUsCheckoutStore(store: HireUsCheckoutStore | null): void {
|
||||||
|
checkoutStoreOverride = store;
|
||||||
|
}
|
||||||
|
|
|
||||||
26
supabase/migrations/20261021020000_hire_us_checkouts.sql
Normal file
26
supabase/migrations/20261021020000_hire_us_checkouts.sql
Normal file
|
|
@ -0,0 +1,26 @@
|
||||||
|
-- CoinPay hosted checkout sessions opened for Hire Us (metered agent-hours).
|
||||||
|
-- One row per cs_ session, written when the session opens; the signed webhook
|
||||||
|
-- marks it paid. Settled payments stay in hire_us_payments (one row per CoinPay
|
||||||
|
-- payment id), which now also carries the session id.
|
||||||
|
|
||||||
|
create table if not exists public.hire_us_checkouts (
|
||||||
|
session_id text primary key, -- CoinPay checkout session id (cs_...)
|
||||||
|
account_id text not null, -- CoinPay account (OAuth sub) or the buyer email for guests
|
||||||
|
buyer_email text not null,
|
||||||
|
hours numeric(10, 2) not null,
|
||||||
|
rate_usd_per_hour numeric(10, 2) not null,
|
||||||
|
amount_usd numeric(12, 2) not null,
|
||||||
|
status text not null default 'open' check (status in ('open', 'paid', 'expired')),
|
||||||
|
payment_id text,
|
||||||
|
created_at timestamptz not null default now(),
|
||||||
|
paid_at timestamptz
|
||||||
|
);
|
||||||
|
|
||||||
|
create index if not exists hire_us_checkouts_account_idx on public.hire_us_checkouts (account_id);
|
||||||
|
|
||||||
|
alter table public.hire_us_payments add column if not exists checkout_session_id text;
|
||||||
|
create index if not exists hire_us_payments_session_idx on public.hire_us_payments (checkout_session_id);
|
||||||
|
|
||||||
|
-- No policies: anon/authenticated cannot read or write; the service role bypasses RLS.
|
||||||
|
alter table public.hire_us_checkouts enable row level security;
|
||||||
|
grant all on public.hire_us_checkouts to service_role;
|
||||||
Loading…
Add table
Add a link
Reference in a new issue