(async () => {
const config = {
workspaceName: "Lead Smart Inc",
defaultQuantity: 13,
country: "TW",
currency: "TWD",
autoTopUpEnabled: true,
openCheckoutPage: true,
timeoutMs: 20_000
};
const lockKey = "checkout_request_running";
let checkoutWindow = null;
async function copyText(text) {
try {
await navigator.clipboard.writeText(text);
return true;
} catch {
const textarea = document.createElement("textarea");
textarea.value = text;
textarea.setAttribute("readonly", "");
textarea.style.position = "fixed";
textarea.style.left = "-9999px";
textarea.style.opacity = "0";
document.body.appendChild(textarea);
textarea.select();
textarea.setSelectionRange(0, textarea.value.length);
const copied = document.execCommand("copy");
textarea.remove();
return copied;
}
}
function parseResponse(text) {
if (!text) return {};
try {
return JSON.parse(text);
} catch {
return { rawResponse: text };
}
}
try {
if (location.hostname !== "chatgpt.com") {
throw new Error("请先打开 https://chatgpt.com 再运行脚本");
}
if (window[lockKey]) {
throw new Error("已有 checkout 请求正在执行,请勿重复提交");
}
const quantityText = prompt(
"请输入购买的 credit 数量:",
String(config.defaultQuantity)
);
if (quantityText === null) return;
const quantity = Number(quantityText);
if (!Number.isInteger(quantity) || quantity <= 0) {
throw new Error("数量必须是大于 0 的整数");
}
const confirmed = confirm(
[
"即将创建 ChatGPT Business checkout:",
"",
`工作空间:${config.workspaceName}`,
`数量:${quantity} credit`,
`地区/货币:${config.country}/${config.currency}`,
`自动充值:${config.autoTopUpEnabled ? "开启" : "关闭"}`,
"",
"确认继续?"
].join("\n")
);
if (!confirmed) return;
window[lockKey] = true;
// 提前创建窗口,避免异步请求结束后被浏览器拦截。
if (config.openCheckoutPage) {
checkoutWindow = window.open("about:blank", "_blank");
if (checkoutWindow) {
checkoutWindow.document.title = "正在创建 checkout";
checkoutWindow.document.body.style.fontFamily = "sans-serif";
checkoutWindow.document.body.style.padding = "24px";
checkoutWindow.document.body.textContent =
"正在创建结算会话,请稍候...";
}
}
const controller = new AbortController();
const timeoutId = setTimeout(() => {
controller.abort();
}, config.timeoutMs);
try {
// 获取当前登录会话
const sessionResponse = await fetch("/api/auth/session", {
method: "GET",
credentials: "include",
cache: "no-store",
signal: controller.signal
});
const sessionText = await sessionResponse.text();
const sessionData = parseResponse(sessionText);
if (!sessionResponse.ok) {
throw new Error(
`获取 Session 失败,HTTP ${sessionResponse.status}\n` +
JSON.stringify(sessionData, null, 2)
);
}
const accessToken = sessionData?.accessToken;
if (!accessToken) {
throw new Error(
"Session 中没有 accessToken,请重新登录 ChatGPT 后再试"
);
}
const headers = {
"Content-Type": "application/json",
"Authorization": `Bearer ${accessToken}`,
"oai-language": "zh-CN"
};
const deviceId = localStorage.getItem("oai-device-id");
if (deviceId) {
headers["oai-device-id"] = deviceId;
}
// 创建 checkout
const checkoutResponse = await fetch(
"https://chatgpt.com/backend-api/payments/checkout",
{
method: "POST",
mode: "cors",
credentials: "include",
headers,
signal: controller.signal,
body: JSON.stringify({
entry_point: "all_plans_pricing_modal",
plan_name: "chatgptbusiness_usage_based",
usage_based_workspace_credit_purchase_data: {
quantity,
unit: "credit",
workspace_name: config.workspaceName,
plan_type: "team",
auto_top_up_enabled: config.autoTopUpEnabled
},
billing_details: {
country: config.country,
currency: config.currency
}
})
}
);
const checkoutText = await checkoutResponse.text();
const data = parseResponse(checkoutText);
if (!checkoutResponse.ok) {
throw new Error(
`Checkout 请求失败,HTTP ${checkoutResponse.status}\n` +
JSON.stringify(data, null, 2)
);
}
const checkoutUrl =
data.checkout_url ||
data.checkoutUrl ||
data.checkout_session_url ||
data.checkoutSessionUrl ||
data.redirect_url ||
data.redirectUrl ||
data.url;
console.log("Checkout 返回数据:", data);
if (!checkoutUrl) {
throw new Error(
"请求成功,但返回结果中没有找到 checkout 地址;" +
"完整返回数据已输出到 Console"
);
}
const parsedUrl = new URL(checkoutUrl, location.origin);
const allowedHosts = new Set([
"chatgpt.com",
"pay.openai.com",
"checkout.stripe.com"
]);
const allowed =
parsedUrl.protocol === "https:" &&
(
allowedHosts.has(parsedUrl.hostname) ||
parsedUrl.hostname.endsWith(".stripe.com")
);
if (!allowed) {
throw new Error(
`返回了未识别的 checkout 地址:${parsedUrl.href}`
);
}
// 自动复制返回地址
const copied = await copyText(parsedUrl.href);
console.log("Checkout 地址:", parsedUrl.href);
console.log(
copied
? "Checkout 地址已复制到剪贴板"
: "自动复制失败,请从上一行手动复制"
);
// 打开官方结算页面
if (config.openCheckoutPage) {
if (checkoutWindow && !checkoutWindow.closed) {
checkoutWindow.location.replace(parsedUrl.href);
} else {
window.open(parsedUrl.href, "_blank");
}
}
alert(
copied
? "Checkout 地址已复制,并已打开结算页面。"
: "Checkout 已创建并打开,但自动复制失败,请从 Console 复制地址。"
);
} finally {
clearTimeout(timeoutId);
}
} catch (error) {
if (
checkoutWindow &&
!checkoutWindow.closed &&
checkoutWindow.location.href === "about:blank"
) {
checkoutWindow.close();
}
const message =
error?.name === "AbortError"
? "请求超时,请稍后重试"
: error?.message || String(error);
console.error("Checkout 请求失败:", error);
alert(message);
} finally {
window[lockKey] = false;
}
})();
6
23
23 Antworten
Sortierung