397 lines
16 KiB
JavaScript
397 lines
16 KiB
JavaScript
(function attachBackgroundPlusCheckoutCreate(root, factory) {
|
||
root.MultiPageBackgroundPlusCheckoutCreate = factory();
|
||
})(typeof self !== 'undefined' ? self : globalThis, function createBackgroundPlusCheckoutCreateModule() {
|
||
const PLUS_CHECKOUT_SOURCE = 'plus-checkout';
|
||
const PLUS_CHECKOUT_ENTRY_URL = 'https://chatgpt.com/';
|
||
const PLUS_CHECKOUT_INJECT_FILES = ['content/utils.js', 'content/operation-delay.js', 'content/plus-checkout.js'];
|
||
const PLUS_PAYMENT_METHOD_PAYPAL = 'paypal';
|
||
const PLUS_PAYMENT_METHOD_GOPAY = 'gopay';
|
||
const PLUS_PAYMENT_METHOD_GPC_HELPER = 'gpc-helper';
|
||
const DEFAULT_GPC_HELPER_API_URL = 'https://gpc.qlhazycoder.top';
|
||
|
||
function createPlusCheckoutCreateExecutor(deps = {}) {
|
||
const {
|
||
addLog: rawAddLog = async () => {},
|
||
chrome,
|
||
completeStepFromBackground,
|
||
ensureContentScriptReadyOnTabUntilStopped,
|
||
fetch: fetchImpl = null,
|
||
registerTab,
|
||
sendTabMessageUntilStopped,
|
||
setState,
|
||
sleepWithStop,
|
||
waitForTabCompleteUntilStopped,
|
||
throwIfStopped = () => {},
|
||
} = deps;
|
||
|
||
function addLog(message, level = 'info', options = {}) {
|
||
return rawAddLog(message, level, {
|
||
step: 6,
|
||
stepKey: 'plus-checkout-create',
|
||
...(options && typeof options === 'object' ? options : {}),
|
||
});
|
||
}
|
||
|
||
function normalizePlusPaymentMethod(value = '') {
|
||
const rootScope = typeof self !== 'undefined' ? self : globalThis;
|
||
if (rootScope.GoPayUtils?.normalizePlusPaymentMethod) {
|
||
return rootScope.GoPayUtils.normalizePlusPaymentMethod(value);
|
||
}
|
||
const normalized = String(value || '').trim().toLowerCase();
|
||
if (normalized === PLUS_PAYMENT_METHOD_GPC_HELPER) {
|
||
return PLUS_PAYMENT_METHOD_GPC_HELPER;
|
||
}
|
||
return normalized === PLUS_PAYMENT_METHOD_GOPAY ? PLUS_PAYMENT_METHOD_GOPAY : PLUS_PAYMENT_METHOD_PAYPAL;
|
||
}
|
||
|
||
function getCheckoutModeLabel(state = {}) {
|
||
const paymentMethod = normalizePlusPaymentMethod(state?.plusPaymentMethod);
|
||
if (paymentMethod === PLUS_PAYMENT_METHOD_GPC_HELPER) {
|
||
return 'GPC 订阅页';
|
||
}
|
||
return paymentMethod === PLUS_PAYMENT_METHOD_GOPAY ? 'GoPay 订阅页' : 'Plus Checkout';
|
||
}
|
||
|
||
function getPlusPaymentMethodLabel(method = PLUS_PAYMENT_METHOD_PAYPAL) {
|
||
const paymentMethod = normalizePlusPaymentMethod(method);
|
||
if (paymentMethod === PLUS_PAYMENT_METHOD_GPC_HELPER) {
|
||
return 'GPC';
|
||
}
|
||
return paymentMethod === PLUS_PAYMENT_METHOD_GOPAY ? 'GoPay' : 'PayPal';
|
||
}
|
||
|
||
async function openFreshChatGptTabForCheckoutCreate() {
|
||
const tab = await chrome.tabs.create({ url: PLUS_CHECKOUT_ENTRY_URL, active: true });
|
||
const tabId = Number(tab?.id);
|
||
if (!Number.isInteger(tabId)) {
|
||
throw new Error('步骤 6:打开 ChatGPT 页面失败,无法创建订阅页。');
|
||
}
|
||
if (typeof registerTab === 'function') {
|
||
await registerTab(PLUS_CHECKOUT_SOURCE, tabId);
|
||
}
|
||
return tabId;
|
||
}
|
||
|
||
function normalizeHelperCountryCode(countryCode = '86') {
|
||
const digits = String(countryCode || '').replace(/\D/g, '');
|
||
return digits || '86';
|
||
}
|
||
|
||
function normalizeHelperPhoneNumber(phone = '', countryCode = '86') {
|
||
const cleaned = String(phone || '').replace(/\D/g, '');
|
||
const countryDigits = normalizeHelperCountryCode(countryCode);
|
||
if (countryDigits && cleaned.startsWith(countryDigits) && cleaned.length > countryDigits.length) {
|
||
return cleaned.slice(countryDigits.length);
|
||
}
|
||
return cleaned;
|
||
}
|
||
|
||
function normalizeGpcOtpChannel(value = '') {
|
||
const rootScope = typeof self !== 'undefined' ? self : globalThis;
|
||
if (rootScope.GoPayUtils?.normalizeGpcOtpChannel) {
|
||
return rootScope.GoPayUtils.normalizeGpcOtpChannel(value);
|
||
}
|
||
return String(value || '').trim().toLowerCase() === 'sms' ? 'sms' : 'whatsapp';
|
||
}
|
||
|
||
function resolveGpcHelperApiKey(state = {}) {
|
||
const apiKey = String(
|
||
state?.gopayHelperApiKey
|
||
|| state?.gpcApiKey
|
||
|| state?.apiKey
|
||
|| ''
|
||
).trim();
|
||
if (!apiKey) {
|
||
throw new Error('创建 GPC 订单失败:缺少 API Key。');
|
||
}
|
||
return apiKey;
|
||
}
|
||
|
||
function normalizeGpcHelperBaseUrl(apiUrl = '') {
|
||
const rootScope = typeof self !== 'undefined' ? self : globalThis;
|
||
if (rootScope.GoPayUtils?.normalizeGpcHelperBaseUrl) {
|
||
return rootScope.GoPayUtils.normalizeGpcHelperBaseUrl(apiUrl);
|
||
}
|
||
let normalized = String(apiUrl || DEFAULT_GPC_HELPER_API_URL).trim().replace(/\/+$/g, '');
|
||
normalized = normalized.replace(/\/api\/checkout\/start$/i, '');
|
||
normalized = normalized.replace(/\/api\/gopay\/(?:otp|pin)$/i, '');
|
||
normalized = normalized.replace(/\/api\/gp\/tasks(?:\/[^/?#]+)?(?:\/(?:otp|pin|stop))?(?:\?.*)?$/i, '');
|
||
normalized = normalized.replace(/\/api\/gp\/balance(?:\?.*)?$/i, '');
|
||
normalized = normalized.replace(/\/api\/card\/balance(?:\?.*)?$/i, '');
|
||
normalized = normalized.replace(/\/api\/card\/redeem-api-key(?:\?.*)?$/i, '');
|
||
return normalized || DEFAULT_GPC_HELPER_API_URL;
|
||
}
|
||
|
||
function buildGpcHelperApiUrl(apiUrl = '', path = '') {
|
||
const rootScope = typeof self !== 'undefined' ? self : globalThis;
|
||
if (rootScope.GoPayUtils?.buildGpcHelperApiUrl) {
|
||
return rootScope.GoPayUtils.buildGpcHelperApiUrl(apiUrl, path);
|
||
}
|
||
const baseUrl = normalizeGpcHelperBaseUrl(apiUrl);
|
||
if (!baseUrl) {
|
||
return '';
|
||
}
|
||
const normalizedPath = String(path || '').startsWith('/') ? String(path || '') : `/${String(path || '')}`;
|
||
return `${baseUrl}${normalizedPath}`;
|
||
}
|
||
|
||
function buildGpcTaskCreateUrl(apiUrl = '') {
|
||
const rootScope = typeof self !== 'undefined' ? self : globalThis;
|
||
if (rootScope.GoPayUtils?.buildGpcTaskCreateUrl) {
|
||
return rootScope.GoPayUtils.buildGpcTaskCreateUrl(apiUrl);
|
||
}
|
||
return buildGpcHelperApiUrl(apiUrl, '/api/gp/tasks');
|
||
}
|
||
|
||
function unwrapGpcResponse(payload = {}) {
|
||
const rootScope = typeof self !== 'undefined' ? self : globalThis;
|
||
if (rootScope.GoPayUtils?.unwrapGpcResponse) {
|
||
return rootScope.GoPayUtils.unwrapGpcResponse(payload);
|
||
}
|
||
if (payload && typeof payload === 'object' && !Array.isArray(payload)
|
||
&& Object.prototype.hasOwnProperty.call(payload, 'data')
|
||
&& (Object.prototype.hasOwnProperty.call(payload, 'code') || Object.prototype.hasOwnProperty.call(payload, 'message'))) {
|
||
return payload.data ?? {};
|
||
}
|
||
return payload;
|
||
}
|
||
|
||
function isGpcUnifiedResponseOk(payload = {}) {
|
||
const rootScope = typeof self !== 'undefined' ? self : globalThis;
|
||
if (rootScope.GoPayUtils?.isGpcUnifiedResponseOk) {
|
||
return rootScope.GoPayUtils.isGpcUnifiedResponseOk(payload);
|
||
}
|
||
if (!payload || typeof payload !== 'object' || !Object.prototype.hasOwnProperty.call(payload, 'code')) {
|
||
return true;
|
||
}
|
||
const code = Number(payload.code);
|
||
return Number.isFinite(code) ? code >= 200 && code < 300 : String(payload.code || '').trim() === '200';
|
||
}
|
||
|
||
function getGpcResponseErrorDetail(payload = {}, status = 0) {
|
||
const rootScope = typeof self !== 'undefined' ? self : globalThis;
|
||
if (rootScope.GoPayUtils?.extractGpcResponseErrorDetail) {
|
||
return rootScope.GoPayUtils.extractGpcResponseErrorDetail(payload, status);
|
||
}
|
||
return payload?.data?.detail || payload?.detail || payload?.message || payload?.error || `HTTP ${status || 0}`;
|
||
}
|
||
|
||
async function fetchJsonWithTimeout(url, options = {}, timeoutMs = 30000) {
|
||
const fetcher = typeof fetchImpl === 'function'
|
||
? fetchImpl
|
||
: (typeof fetch === 'function' ? fetch.bind(globalThis) : null);
|
||
if (typeof fetcher !== 'function') {
|
||
throw new Error('当前运行环境不支持 fetch,无法调用 GPC API。');
|
||
}
|
||
const controller = typeof AbortController === 'function' ? new AbortController() : null;
|
||
const timer = controller ? setTimeout(() => controller.abort(), Math.max(1000, Number(timeoutMs) || 30000)) : null;
|
||
try {
|
||
const response = await fetcher(url, { ...options, ...(controller ? { signal: controller.signal } : {}) });
|
||
const data = await response.json().catch(() => ({}));
|
||
return { response, data };
|
||
} finally {
|
||
if (timer) clearTimeout(timer);
|
||
}
|
||
}
|
||
|
||
async function readAccessTokenFromChatGptSessionTab(tabId) {
|
||
await waitForTabCompleteUntilStopped(tabId);
|
||
await sleepWithStop(1000);
|
||
await ensureContentScriptReadyOnTabUntilStopped(PLUS_CHECKOUT_SOURCE, tabId, {
|
||
inject: PLUS_CHECKOUT_INJECT_FILES,
|
||
injectSource: PLUS_CHECKOUT_SOURCE,
|
||
logMessage: '步骤 6:正在等待 ChatGPT 页面完成加载,再继续获取 accessToken...',
|
||
});
|
||
|
||
const sessionResult = await sendTabMessageUntilStopped(tabId, PLUS_CHECKOUT_SOURCE, {
|
||
type: 'PLUS_CHECKOUT_GET_STATE',
|
||
source: 'background',
|
||
payload: {
|
||
includeSession: true,
|
||
includeAccessToken: true,
|
||
},
|
||
});
|
||
if (sessionResult?.error) {
|
||
throw new Error(sessionResult.error);
|
||
}
|
||
return String(sessionResult?.accessToken || sessionResult?.session?.accessToken || '').trim();
|
||
}
|
||
|
||
async function generateGpcCheckoutFromApi(accessToken = '', state = {}) {
|
||
const token = String(accessToken || '').trim();
|
||
if (!token) {
|
||
throw new Error('创建 GPC 订单失败:缺少 accessToken。');
|
||
}
|
||
const apiUrl = buildGpcTaskCreateUrl(state?.gopayHelperApiUrl);
|
||
if (!apiUrl) {
|
||
throw new Error('创建 GPC 订单失败:缺少 API 地址。');
|
||
}
|
||
const phoneNumber = String(state?.gopayHelperPhoneNumber || '').trim();
|
||
const countryCode = normalizeHelperCountryCode(state?.gopayHelperCountryCode || '86');
|
||
const pin = String(state?.gopayHelperPin || '').trim();
|
||
const apiKey = resolveGpcHelperApiKey(state);
|
||
if (!phoneNumber) {
|
||
throw new Error('创建 GPC 订单失败:缺少手机号。');
|
||
}
|
||
if (!pin) {
|
||
throw new Error('创建 GPC 订单失败:缺少 PIN。');
|
||
}
|
||
|
||
throwIfStopped();
|
||
const payload = {
|
||
access_token: token,
|
||
phone_mode: 'manual',
|
||
country_code: countryCode,
|
||
phone_number: normalizeHelperPhoneNumber(phoneNumber, countryCode),
|
||
otp_channel: normalizeGpcOtpChannel(state?.gopayHelperOtpChannel),
|
||
};
|
||
|
||
const orderCreatedAt = Date.now();
|
||
const { response, data } = await fetchJsonWithTimeout(apiUrl, {
|
||
method: 'POST',
|
||
headers: {
|
||
Accept: '*/*',
|
||
'Accept-Language': 'zh-CN,zh;q=0.9,en;q=0.8',
|
||
'Content-Type': 'application/json',
|
||
'X-API-Key': apiKey,
|
||
},
|
||
body: JSON.stringify(payload),
|
||
}, 30000);
|
||
|
||
const taskData = unwrapGpcResponse(data);
|
||
const taskId = String(taskData?.task_id || taskData?.taskId || '').trim();
|
||
|
||
if (!response?.ok || !isGpcUnifiedResponseOk(data) || !taskId) {
|
||
const detail = getGpcResponseErrorDetail(data, response?.status || 0);
|
||
throw new Error(`创建 GPC 订单失败:${detail}`);
|
||
}
|
||
|
||
return {
|
||
taskId,
|
||
taskStatus: String(taskData?.status || '').trim(),
|
||
statusText: String(taskData?.status_text || taskData?.statusText || '').trim(),
|
||
remoteStage: String(taskData?.remote_stage || taskData?.remoteStage || '').trim(),
|
||
orderCreatedAt,
|
||
responsePayload: taskData && typeof taskData === 'object' && !Array.isArray(taskData) ? taskData : null,
|
||
country: 'ID',
|
||
currency: 'IDR',
|
||
checkoutSource: PLUS_PAYMENT_METHOD_GPC_HELPER,
|
||
};
|
||
}
|
||
|
||
async function executeGpcCheckoutCreate(state = {}) {
|
||
let accessToken = String(state?.contributionAccessToken || state?.accessToken || state?.chatgptAccessToken || '').trim();
|
||
if (!accessToken) {
|
||
await addLog('步骤 6:正在获取 accessToken...', 'info');
|
||
const tokenTabId = await openFreshChatGptTabForCheckoutCreate();
|
||
try {
|
||
accessToken = await readAccessTokenFromChatGptSessionTab(tokenTabId);
|
||
} finally {
|
||
if (chrome?.tabs?.remove && Number.isInteger(tokenTabId)) {
|
||
await chrome.tabs.remove(tokenTabId).catch(() => {});
|
||
}
|
||
}
|
||
}
|
||
if (!accessToken) {
|
||
throw new Error('步骤 6:GPC 模式获取 accessToken 失败。');
|
||
}
|
||
|
||
await addLog('步骤 6:正在调用 GPC 接口创建订单...', 'info');
|
||
const result = await generateGpcCheckoutFromApi(accessToken, state);
|
||
await setState({
|
||
plusCheckoutTabId: null,
|
||
plusCheckoutUrl: '',
|
||
plusCheckoutCountry: result.country || 'ID',
|
||
plusCheckoutCurrency: result.currency || 'IDR',
|
||
plusCheckoutSource: result.checkoutSource,
|
||
gopayHelperTaskId: result.taskId,
|
||
gopayHelperTaskStatus: result.taskStatus,
|
||
gopayHelperStatusText: result.statusText,
|
||
gopayHelperRemoteStage: result.remoteStage,
|
||
gopayHelperTaskPayload: result.responsePayload,
|
||
gopayHelperReferenceId: '',
|
||
gopayHelperGoPayGuid: '',
|
||
gopayHelperRedirectUrl: '',
|
||
gopayHelperNextAction: '',
|
||
gopayHelperFlowId: '',
|
||
gopayHelperChallengeId: '',
|
||
gopayHelperStartPayload: null,
|
||
gopayHelperOrderCreatedAt: result.orderCreatedAt || Date.now(),
|
||
});
|
||
await addLog(`步骤 6:GPC 任务已创建(task_id: ${result.taskId}),准备继续下一步。`, 'info');
|
||
await completeStepFromBackground(6, {
|
||
plusCheckoutCountry: result.country || 'ID',
|
||
plusCheckoutCurrency: result.currency || 'IDR',
|
||
plusCheckoutSource: result.checkoutSource,
|
||
});
|
||
}
|
||
|
||
async function executePlusCheckoutCreate(state = {}) {
|
||
const paymentMethod = normalizePlusPaymentMethod(state?.plusPaymentMethod);
|
||
if (paymentMethod === PLUS_PAYMENT_METHOD_GPC_HELPER) {
|
||
await executeGpcCheckoutCreate(state);
|
||
return;
|
||
}
|
||
|
||
const paymentMethodLabel = getPlusPaymentMethodLabel(paymentMethod);
|
||
const checkoutModeLabel = getCheckoutModeLabel(state);
|
||
await addLog(`步骤 6:正在打开新的 ChatGPT 会话,准备创建${checkoutModeLabel}...`, 'info');
|
||
const tabId = await openFreshChatGptTabForCheckoutCreate();
|
||
|
||
await waitForTabCompleteUntilStopped(tabId);
|
||
await sleepWithStop(1000);
|
||
await ensureContentScriptReadyOnTabUntilStopped(PLUS_CHECKOUT_SOURCE, tabId, {
|
||
inject: PLUS_CHECKOUT_INJECT_FILES,
|
||
injectSource: PLUS_CHECKOUT_SOURCE,
|
||
logMessage: '步骤 6:正在等待 ChatGPT 页面完成加载,再继续创建订阅页...',
|
||
});
|
||
|
||
const result = await sendTabMessageUntilStopped(tabId, PLUS_CHECKOUT_SOURCE, {
|
||
type: 'CREATE_PLUS_CHECKOUT',
|
||
source: 'background',
|
||
payload: { paymentMethod },
|
||
});
|
||
|
||
if (result?.error) {
|
||
throw new Error(result.error);
|
||
}
|
||
if (!result?.checkoutUrl) {
|
||
throw new Error(`步骤 6:${checkoutModeLabel}未返回可用的订阅链接。`);
|
||
}
|
||
|
||
await addLog(`步骤 6:${checkoutModeLabel}已创建,正在打开订阅页面...`, 'ok');
|
||
await chrome.tabs.update(tabId, { url: result.checkoutUrl, active: true });
|
||
await waitForTabCompleteUntilStopped(tabId);
|
||
await sleepWithStop(1000);
|
||
await ensureContentScriptReadyOnTabUntilStopped(PLUS_CHECKOUT_SOURCE, tabId, {
|
||
inject: PLUS_CHECKOUT_INJECT_FILES,
|
||
injectSource: PLUS_CHECKOUT_SOURCE,
|
||
logMessage: '步骤 6:正在等待订阅页面完成加载...',
|
||
});
|
||
|
||
await setState({
|
||
plusCheckoutTabId: tabId,
|
||
plusCheckoutUrl: result.checkoutUrl,
|
||
plusCheckoutCountry: result.country || 'DE',
|
||
plusCheckoutCurrency: result.currency || 'EUR',
|
||
plusCheckoutSource: '',
|
||
});
|
||
|
||
await addLog(`步骤 6:Plus Checkout 页面已就绪(${paymentMethodLabel} / ${result.country || 'DE'} ${result.currency || 'EUR'}),准备继续下一步。`, 'info');
|
||
|
||
await completeStepFromBackground(6, {
|
||
plusCheckoutCountry: result.country || 'DE',
|
||
plusCheckoutCurrency: result.currency || 'EUR',
|
||
});
|
||
}
|
||
|
||
return {
|
||
executePlusCheckoutCreate,
|
||
};
|
||
}
|
||
|
||
return {
|
||
createPlusCheckoutCreateExecutor,
|
||
};
|
||
});
|