@tgbotpress/plugin-premium 0.0.0-stage → 0.1.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +89 -2
- package/migrations/postgres/000-premium-core.sql +82 -0
- package/migrations/postgres/014-premium-payment.sql +11 -0
- package/migrations/postgres/023-telegram-purchase.sql +22 -0
- package/migrations/postgres/038-telegram-stars.sql +35 -0
- package/package.json +106 -4
- package/scripts/build.mjs +22 -0
- package/src/admin-api.d.ts +30 -0
- package/src/admin-api.js +486 -0
- package/src/admin-api.source.ts +330 -0
- package/src/admin-pages.d.ts +6 -0
- package/src/admin-pages.js +5 -0
- package/src/admin-pages.orders.d.ts +1 -0
- package/src/admin-pages.orders.js +26 -0
- package/src/admin-pages.orders.tsx +33 -0
- package/src/admin-pages.packages.d.ts +1 -0
- package/src/admin-pages.packages.js +39 -0
- package/src/admin-pages.packages.tsx +51 -0
- package/src/admin-pages.platforms.d.ts +1 -0
- package/src/admin-pages.platforms.js +33 -0
- package/src/admin-pages.platforms.tsx +52 -0
- package/src/admin-pages.trades.d.ts +1 -0
- package/src/admin-pages.trades.js +27 -0
- package/src/admin-pages.trades.tsx +32 -0
- package/src/admin-pages.ts +6 -0
- package/src/admin-ui-runtime.d.ts +63 -0
- package/src/admin-ui-runtime.js +11 -0
- package/src/admin-ui-runtime.ts +44 -0
- package/src/fulfillment.d.ts +24 -0
- package/src/fulfillment.js +417 -0
- package/src/fulfillment.source.ts +311 -0
- package/src/host-types.d.ts +31 -0
- package/src/index.d.ts +26 -0
- package/src/index.js +47 -0
- package/src/notifications.d.ts +39 -0
- package/src/notifications.js +96 -0
- package/src/notifications.source.ts +60 -0
- package/src/purchases.d.ts +51 -0
- package/src/purchases.js +627 -0
- package/src/purchases.source.ts +568 -0
- package/src/server.d.ts +41 -0
- package/src/server.js +44 -0
- package/src/server.source.ts +60 -0
- package/src/tasks.d.ts +24 -0
- package/src/tasks.js +46 -0
- package/src/tasks.source.ts +69 -0
- package/src/wallet-poll.d.ts +21 -0
- package/src/wallet-poll.js +139 -0
- package/src/wallet-poll.source.ts +120 -0
- package/tsconfig.build.json +11 -0
- package/tsconfig.json +19 -0
|
@@ -0,0 +1,568 @@
|
|
|
1
|
+
import { constants, createPrivateKey, privateDecrypt, randomBytes, randomInt, type KeyObject } from 'node:crypto'
|
|
2
|
+
import { readFileSync } from 'node:fs'
|
|
3
|
+
import type { DatabaseConnection as Pool } from './host-types.js'
|
|
4
|
+
import { telegramPremiumStarPrice } from './index.js'
|
|
5
|
+
|
|
6
|
+
type Database = Pick<Pool, 'query' | 'connect'>
|
|
7
|
+
type Queryable = Pick<Pool, 'query'>
|
|
8
|
+
type CallbackQuery = { id?: string | number; data?: string; from?: { id?: string | number; username?: string; is_bot?: boolean }; message?: Record<string, any> }
|
|
9
|
+
type Message = Record<string, any> & { message_id: string | number; chat: { id: string | number; type: string }; from?: { id?: string | number; username?: string; first_name?: string; last_name?: string; is_bot?: boolean }; text?: string }
|
|
10
|
+
type Update = { message?: Message; callback_query?: CallbackQuery }
|
|
11
|
+
type TelegramResult = { ok?: boolean; result?: { message_id?: number }; description?: string }
|
|
12
|
+
export type PremiumTelegramDatabase = Database
|
|
13
|
+
export type PremiumTelegramMessage = Message
|
|
14
|
+
export type PremiumTelegramUpdate = Update
|
|
15
|
+
export type PremiumSecretDecryptor = (value: string | null) => string
|
|
16
|
+
type PremiumPackage = { rid: number; premium_platform_rid: number; platform_name: number; package_name: string; package_month: number; usdt_price: string; show_notes: string | null; package_pic: string | null; receive_wallet: string | null; platform_hash: string | null; platform_cookie: string | null }
|
|
17
|
+
type Purchase = { update_rid: number; bot_rid: number; chat_id: string; premium_tg_username: string; premium_name: string; order_rid: number; package_name: string; premium_package_month: number; fulfillment_method: 'fragment_ton'|'telegram_stars'; need_pay_usdt: string; need_pay_stars: number; premium_tg_user_id: string|null; receive_wallet: string; created_at: string; expire_time: string; notification_sent: boolean }
|
|
18
|
+
|
|
19
|
+
export const premiumPackageCallbackClaimPredicate = [
|
|
20
|
+
"u.update_body ? 'callback_query'",
|
|
21
|
+
"AND u.update_body #>> '{callback_query,message,chat,type}'='private'",
|
|
22
|
+
"AND u.update_body #>> '{callback_query,message,chat,id}'=u.update_body #>> '{callback_query,from,id}'",
|
|
23
|
+
"AND COALESCE(u.update_body #>> '{callback_query,from,is_bot}','false')<>'true'",
|
|
24
|
+
"AND u.update_body #>> '{callback_query,data}' ~ '^premium_[0-9a-fA-F]{32}$'",
|
|
25
|
+
].join('\n')
|
|
26
|
+
|
|
27
|
+
export const premiumUsernameReplyClaimPredicate = [
|
|
28
|
+
"u.update_body ? 'message' AND u.update_body #>> '{message,chat,type}'='private'",
|
|
29
|
+
"AND COALESCE(u.update_body #>> '{message,from,is_bot}','false')<>'true'",
|
|
30
|
+
"AND u.update_body #>> '{message,from,id}'=u.update_body #>> '{message,chat,id}'",
|
|
31
|
+
"AND (left(trim(COALESCE(u.update_body #>> '{message,text}','')),1)='@' OR trim(COALESCE(u.update_body #>> '{message,text}','')) ~ '^[0-9]{1,16}$')",
|
|
32
|
+
"AND EXISTS (SELECT 1 FROM t_platform_telegram_conversation_state s WHERE s.bot_rid=u.bot_rid AND s.chat_id::text=u.update_body #>> '{message,chat,id}' AND s.user_id::text=u.update_body #>> '{message,from,id}' AND s.state='premium_purchase_username' AND s.expires_at>now())",
|
|
33
|
+
].join('\n')
|
|
34
|
+
export function isPremiumUsernameReplyCandidate(update: Update) {
|
|
35
|
+
const message = update?.message
|
|
36
|
+
const text = String(message?.text ?? '').trim()
|
|
37
|
+
return message?.chat?.type === 'private' && !message?.from?.is_bot && ((text.length >= 4 && text.startsWith('@')) || /^[1-9][0-9]{0,15}$/u.test(text))
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
export async function isPremiumUsernameReplyForPrompt(pool: Queryable, botRid: number, update: Update) {
|
|
41
|
+
const message = update?.message
|
|
42
|
+
const replyToMessageId = String(message?.reply_to_message?.message_id ?? '')
|
|
43
|
+
const chatId = String(message?.chat?.id ?? ''), userId = String(message?.from?.id ?? '')
|
|
44
|
+
if (message?.chat?.type !== 'private' || message?.from?.is_bot || !/^\d{1,20}$/u.test(replyToMessageId) || !/^\d{1,20}$/u.test(chatId) || !/^\d{1,20}$/u.test(userId)) return false
|
|
45
|
+
const result = await pool.query<{ premium: boolean }>("SELECT EXISTS(SELECT 1 FROM t_platform_telegram_conversation_state WHERE bot_rid=$1 AND chat_id::text=$2 AND user_id::text=$3 AND state='premium_purchase_username' AND expires_at>now() AND prompt_message_id::text=$4) AS premium", [botRid, chatId, userId, replyToMessageId])
|
|
46
|
+
return result.rows[0]?.premium === true
|
|
47
|
+
}
|
|
48
|
+
export const premiumWalletPayClaimPredicate = [
|
|
49
|
+
"u.update_body ? 'callback_query'",
|
|
50
|
+
"AND u.update_body #>> '{callback_query,message,chat,type}'='private'",
|
|
51
|
+
"AND u.update_body #>> '{callback_query,message,chat,id}'=u.update_body #>> '{callback_query,from,id}'",
|
|
52
|
+
"AND COALESCE(u.update_body #>> '{callback_query,from,is_bot}','false')<>'true'",
|
|
53
|
+
"AND u.update_body #>> '{callback_query,data}' ~ '^tgpremiumwalletpay_[1-9][0-9]{0,9}$'",
|
|
54
|
+
"AND EXISTS (SELECT 1 FROM jsonb_array_elements(COALESCE(u.update_body #> '{callback_query,message,reply_markup,inline_keyboard}','[]'::jsonb)) AS keyboard_row(row_json) CROSS JOIN LATERAL jsonb_array_elements(keyboard_row.row_json) AS button(button_json) WHERE button.button_json->>'callback_data'=u.update_body #>> '{callback_query,data}')",
|
|
55
|
+
].join('\n')
|
|
56
|
+
export const premiumCancelUnpaidClaimPredicate = [
|
|
57
|
+
"u.update_body ? 'callback_query' AND u.update_body #>> '{callback_query,message,chat,type}'='private'",
|
|
58
|
+
"AND u.update_body #>> '{callback_query,message,chat,id}'=u.update_body #>> '{callback_query,from,id}'",
|
|
59
|
+
"AND COALESCE(u.update_body #>> '{callback_query,from,is_bot}','false')<>'true'",
|
|
60
|
+
"AND u.update_body #>> '{callback_query,data}'='cancelpremiumunpaid'",
|
|
61
|
+
"AND EXISTS (SELECT 1 FROM jsonb_array_elements(COALESCE(u.update_body #> '{callback_query,message,reply_markup,inline_keyboard}','[]'::jsonb)) AS keyboard_row(row_json) CROSS JOIN LATERAL jsonb_array_elements(keyboard_row.row_json) AS button(button_json) WHERE button.button_json->>'callback_data'=u.update_body #>> '{callback_query,data}')",
|
|
62
|
+
].join('\n')
|
|
63
|
+
export const premiumChooseAgainClaimPredicate = [
|
|
64
|
+
"u.update_body ? 'callback_query' AND u.update_body #>> '{callback_query,message,chat,type}' IN ('private','group','supergroup')",
|
|
65
|
+
"AND (u.update_body #>> '{callback_query,message,chat,type}'<>'private' OR u.update_body #>> '{callback_query,message,chat,id}'=u.update_body #>> '{callback_query,from,id}')",
|
|
66
|
+
"AND COALESCE(u.update_body #>> '{callback_query,from,is_bot}','false')<>'true'",
|
|
67
|
+
"AND u.update_body #>> '{callback_query,data}'='重新选择套餐premium'",
|
|
68
|
+
"AND EXISTS (SELECT 1 FROM jsonb_array_elements(COALESCE(u.update_body #> '{callback_query,message,reply_markup,inline_keyboard}','[]'::jsonb)) AS keyboard_row(row_json) CROSS JOIN LATERAL jsonb_array_elements(keyboard_row.row_json) AS button(button_json) WHERE button.button_json->>'callback_data'=u.update_body #>> '{callback_query,data}')",
|
|
69
|
+
"AND EXISTS (SELECT 1 FROM t_telegram_bot_keyreply kr WHERE kr.bot_rid=u.bot_rid AND kr.status=0 AND kr.opt_type=4)",
|
|
70
|
+
].join('\n')
|
|
71
|
+
|
|
72
|
+
export function isPremiumCallbackUpdate(update: Update) {
|
|
73
|
+
const data = String(update?.callback_query?.data ?? '')
|
|
74
|
+
return callbackPattern.test(data) || /^tgpremiumwalletpay_[1-9][0-9]{0,9}$/u.test(data) || data === 'cancelpremiumunpaid' || data === '重新选择套餐premium'
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
const usernamePattern = /^@[A-Za-z0-9_]{3,32}$/u
|
|
78
|
+
const telegramIdPattern = /^[1-9][0-9]{0,15}$/u
|
|
79
|
+
const callbackPattern = /^premium_[0-9a-fA-F]{32}$/u
|
|
80
|
+
const telegramHeaders = { 'Content-Type': 'application/json' }
|
|
81
|
+
|
|
82
|
+
function callbackSelection(update: Update) {
|
|
83
|
+
const callback = update?.callback_query
|
|
84
|
+
const message = callback?.message
|
|
85
|
+
const chatId = String(message?.chat?.id ?? '')
|
|
86
|
+
const userId = String(callback?.from?.id ?? '')
|
|
87
|
+
const data = String(callback?.data ?? '')
|
|
88
|
+
if (!message || message.chat?.type !== 'private' || !/^\d{1,20}$/u.test(chatId) || userId !== chatId || callback?.from?.is_bot || !callbackPattern.test(data)) return null
|
|
89
|
+
return { callback, message, chatId, userId, data, callbackUsername: String(callback?.from?.username ?? '') }
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
function premiumMessage(message: Message) {
|
|
93
|
+
const chatId = String(message?.chat?.id ?? '')
|
|
94
|
+
const userId = String(message?.from?.id ?? '')
|
|
95
|
+
const username = String(message?.text ?? '').trim()
|
|
96
|
+
const messageIdText = String(message?.message_id ?? '')
|
|
97
|
+
const messageId = Number(messageIdText)
|
|
98
|
+
if (message?.chat?.type !== 'private' || !/^\d{1,20}$/u.test(chatId) || userId !== chatId || message?.from?.is_bot || !/^\d{1,20}$/u.test(messageIdText) || !Number.isSafeInteger(messageId) || messageId < 1 || (!usernamePattern.test(username) && !telegramIdPattern.test(username))) return null
|
|
99
|
+
return { chatId, userId, username, messageId, buyerUsername: String(message.from?.username ?? '') }
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
function escapeHtml(value: unknown) {
|
|
103
|
+
return String(value ?? '').replaceAll('&', '&').replaceAll('<', '<').replaceAll('>', '>').replaceAll('"', '"')
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
function contextObject(value: unknown): Record<string, unknown> {
|
|
107
|
+
if (value && typeof value === 'object' && !Array.isArray(value)) return value as Record<string, unknown>
|
|
108
|
+
if (typeof value === 'string') {
|
|
109
|
+
try { const parsed: unknown = JSON.parse(value); if (parsed && typeof parsed === 'object' && !Array.isArray(parsed)) return parsed as Record<string, unknown> } catch { /* malformed conversation state is treated as expired */ }
|
|
110
|
+
}
|
|
111
|
+
return {}
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
async function botTokenFor(pool: Queryable, botRid: number) {
|
|
115
|
+
const result = await pool.query<{ bot_token: string | null }>('SELECT bot_token FROM t_telegram_bot WHERE rid=$1', [botRid])
|
|
116
|
+
return String(result.rows[0]?.bot_token ?? '')
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
async function telegram(fetcher: typeof fetch, token: string, method: string, payload: Record<string, unknown>): Promise<TelegramResult> {
|
|
120
|
+
if (process.env.PLATFORM_TELEGRAM_ACTIONS !== 'true' || !/^\d{5,20}:[A-Za-z0-9_-]{20,100}$/u.test(token)) return { ok: false }
|
|
121
|
+
try {
|
|
122
|
+
const response = await fetcher('https://api.telegram.org/bot' + token + '/' + method, { method: 'POST', headers: telegramHeaders, body: JSON.stringify(payload), redirect: 'error', signal: AbortSignal.timeout(12_000) })
|
|
123
|
+
return await response.json() as TelegramResult
|
|
124
|
+
} catch { return { ok: false } }
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
function rsaPrivateKey(): KeyObject {
|
|
128
|
+
const path = process.env.TRON_RSA_PRIVATE_KEY_PATH
|
|
129
|
+
const raw = (path ? readFileSync(path, 'utf8') : process.env.TRON_RSA_PRIVATE_KEY)?.replace(/\\n/g, '\n').trim()
|
|
130
|
+
if (!raw) throw new Error('RSA_PRIVATE_KEY_UNAVAILABLE')
|
|
131
|
+
return createPrivateKey(raw)
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
function decryptPlatformCookie(value: string | null) {
|
|
135
|
+
if (!value) throw new Error('PREMIUM_PLATFORM_COOKIE_MISSING')
|
|
136
|
+
const versioned = value.startsWith('v2:')
|
|
137
|
+
const encoded = (versioned ? value.slice(3) : value).replace(/-/g, '+').replace(/_/g, '/')
|
|
138
|
+
if (!/^[A-Za-z0-9+/]+={0,2}$/u.test(encoded)) throw new Error('RSA_CIPHERTEXT_INVALID')
|
|
139
|
+
const encrypted = Buffer.from(encoded, 'base64')
|
|
140
|
+
const key = rsaPrivateKey()
|
|
141
|
+
const bytes = (key.asymmetricKeyDetails?.modulusLength ?? 0) / 8
|
|
142
|
+
if (!bytes || bytes < 256 || bytes % 1 || !encrypted.length || encrypted.length % bytes) throw new Error('RSA_CIPHERTEXT_INVALID')
|
|
143
|
+
const chunks: Buffer[] = []
|
|
144
|
+
for (let offset = 0; offset < encrypted.length; offset += bytes) chunks.push(privateDecrypt(versioned
|
|
145
|
+
? { key, padding: constants.RSA_PKCS1_OAEP_PADDING, oaepHash: 'sha1' }
|
|
146
|
+
: { key, padding: constants.RSA_PKCS1_PADDING }, encrypted.subarray(offset, offset + bytes)))
|
|
147
|
+
return Buffer.concat(chunks).toString('utf8')
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
async function searchFragmentRecipient(fetcher: typeof fetch, pkg: PremiumPackage, username: string, decryptSecret?: PremiumSecretDecryptor) {
|
|
151
|
+
const cookie = decryptSecret ? decryptSecret(pkg.platform_cookie) : decryptPlatformCookie(pkg.platform_cookie)
|
|
152
|
+
const url = new URL('https://fragment.com/api')
|
|
153
|
+
url.searchParams.set('hash', String(pkg.platform_hash ?? ''))
|
|
154
|
+
const form = new URLSearchParams({ query: username, months: String(pkg.package_month), method: 'searchPremiumGiftRecipient' })
|
|
155
|
+
const response = await fetcher(url, {
|
|
156
|
+
method: 'POST',
|
|
157
|
+
headers: {
|
|
158
|
+
Accept: 'application/json',
|
|
159
|
+
'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8',
|
|
160
|
+
Cookie: cookie,
|
|
161
|
+
Referer: 'https://fragment.com/',
|
|
162
|
+
'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 Chrome/131 Safari/537.36',
|
|
163
|
+
},
|
|
164
|
+
body: form,
|
|
165
|
+
redirect: 'error',
|
|
166
|
+
signal: AbortSignal.timeout(20_000),
|
|
167
|
+
})
|
|
168
|
+
let body: unknown
|
|
169
|
+
try { body = await response.json() } catch { throw new Error('FRAGMENT_INVALID_RESPONSE') }
|
|
170
|
+
if (!response.ok || !body || typeof body !== 'object' || Array.isArray(body)) throw new Error('FRAGMENT_INVALID_RESPONSE')
|
|
171
|
+
const result = body as { ok?: unknown; error?: unknown; found?: { name?: unknown; recipient?: unknown } }
|
|
172
|
+
if (result.ok !== true) throw new Error(typeof result.error === 'string' ? result.error : '未知')
|
|
173
|
+
const recipient = String(result.found?.recipient ?? '')
|
|
174
|
+
if (!recipient || recipient.length > 1000) throw new Error('FRAGMENT_RECIPIENT_MISSING')
|
|
175
|
+
return { recipient, displayName: String(result.found?.name ?? '未知').slice(0, 255) }
|
|
176
|
+
}
|
|
177
|
+
|
|
178
|
+
function packageKeyboard(packages: Array<{ package_name: string; callback_data: string }>) {
|
|
179
|
+
if (!packages.length) return undefined
|
|
180
|
+
const rows: Array<Array<{ text: string; callback_data: string }>> = [[{ text: '点击 ↓ 重新选择套餐(点我查看说明)', callback_data: '重新选择套餐premium' }]]
|
|
181
|
+
for (let index = 0; index < packages.length; index += 2) {
|
|
182
|
+
rows.push(packages.slice(index, index + 2).map(row => ({ text: String(row.package_name).slice(0, 64), callback_data: row.callback_data })))
|
|
183
|
+
}
|
|
184
|
+
return { inline_keyboard: rows }
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
export async function handleTelegramPremiumPackageCallback(pool: Queryable, fetcher: typeof fetch, botRid: number, update: Update, decryptSecret?: PremiumSecretDecryptor) {
|
|
188
|
+
const selected = callbackSelection(update)
|
|
189
|
+
if (!selected) return false
|
|
190
|
+
const token = await botTokenFor(pool, botRid)
|
|
191
|
+
if (selected.callback.id != null) {
|
|
192
|
+
const answered = await telegram(fetcher, token, 'answerCallbackQuery', { callback_query_id: String(selected.callback.id) })
|
|
193
|
+
if (!answered.ok) throw new Error('premium_package_callback_answer_failed')
|
|
194
|
+
}
|
|
195
|
+
const active = await pool.query<PremiumPackage>('SELECT p.rid,p.premium_platform_rid,b.platform_name,p.package_name,p.package_month,p.usdt_price::text AS usdt_price,p.show_notes,p.package_pic,b.receive_wallet,b.platform_hash,b.platform_cookie FROM t_premium_platform_package p JOIN t_premium_platform b ON b.rid=p.premium_platform_rid WHERE p.bot_rid=$1 AND p.callback_data=$2 AND p.status=0 AND b.status=0 LIMIT 1', [botRid, selected.data])
|
|
196
|
+
const packageData = active.rows[0]
|
|
197
|
+
const packages = await pool.query<{ package_name: string; callback_data: string }>('SELECT p.package_name,p.callback_data FROM t_premium_platform_package p JOIN t_premium_platform b ON b.rid=p.premium_platform_rid WHERE p.bot_rid=$1 AND p.status=0 AND b.status=0 ORDER BY p.seq_sn DESC,p.rid DESC', [botRid])
|
|
198
|
+
const markup = packageKeyboard(packages.rows)
|
|
199
|
+
let text: string
|
|
200
|
+
if (!packageData) text = '@' + escapeHtml(selected.callbackUsername) + ' <b>您好!该套餐已暂停购买,请选择其他套餐!</b>\n'
|
|
201
|
+
else {
|
|
202
|
+
const sessionId = randomBytes(18).toString('hex')
|
|
203
|
+
const context = JSON.stringify({ packageRid: packageData.rid, sessionId })
|
|
204
|
+
await pool.query("INSERT INTO t_platform_telegram_conversation_state(bot_rid,chat_id,user_id,state,prompt_message_id,context,expires_at) VALUES($1,$2,$3,'premium_purchase_username',NULL,$4::jsonb,now()+interval '15 minutes') ON CONFLICT(bot_rid,chat_id,user_id) DO UPDATE SET state='premium_purchase_username',prompt_message_id=NULL,context=$4::jsonb,expires_at=now()+interval '15 minutes',updated_at=now()", [botRid, selected.chatId, selected.userId, context])
|
|
205
|
+
const starsPlatform = Number(packageData.platform_name) === 3
|
|
206
|
+
text = starsPlatform
|
|
207
|
+
? '<b>请发送要开通会员的 Telegram 用户名或用户 ID:</b>\n<b>官方 Stars 开通仅支持机器人已记录的用户;目标用户先与机器人互动后可直接发用户名。</b>\n<b>会员套餐仍需按页面显示金额支付 USDT,确认收款后机器人再使用 Stars 开通。</b>\n'
|
|
208
|
+
: '<b>您好!请直接发送需要开通/续费会员的 Telegram 用户名:</b>\n<b>提示:用户名以 @ 开头,例如</b> @' + escapeHtml(selected.callbackUsername) + '\n'
|
|
209
|
+
text +=
|
|
210
|
+
escapeHtml(packageData.show_notes ?? '') + '\n➖➖➖➖➖➖➖➖\n' +
|
|
211
|
+
'<b>🟢当前套餐:' + escapeHtml(packageData.package_name) + '</b>\n' +
|
|
212
|
+
'<b>🟢开通月份:</b>' + escapeHtml(packageData.package_month) + '\n' +
|
|
213
|
+
(starsPlatform ? '<b>🟢机器人扣款:</b>' + escapeHtml(telegramPremiumStarPrice(packageData.package_month) ?? '月份无效') + ' Stars\n➖➖➖➖➖➖➖➖\n⚠️<b>需要机器人账户有足够 Stars。</b>' : '➖➖➖➖➖➖➖➖\n⚠️<b>请在下单后核对支付地址与金额,填写错误无法追回。</b>')
|
|
214
|
+
}
|
|
215
|
+
if (!packages.rows.length) text += '😭😭😭<b>暂无可用会员套餐,请联系管理员!</b>'
|
|
216
|
+
const photo = packageData?.package_pic?.trim() ?? ''
|
|
217
|
+
let sent: TelegramResult
|
|
218
|
+
if (photo && /^https:\/\//iu.test(photo) && text.length <= 1024) {
|
|
219
|
+
try {
|
|
220
|
+
const url = new URL(photo)
|
|
221
|
+
if (url.username || url.password) throw new Error('unsafe_photo_url')
|
|
222
|
+
sent = await telegram(fetcher, token, 'sendPhoto', { chat_id: selected.chatId, photo: url.toString(), caption: text, parse_mode: 'HTML', allow_sending_without_reply: true, ...(markup ? { reply_markup: markup } : {}) })
|
|
223
|
+
} catch {
|
|
224
|
+
sent = await telegram(fetcher, token, 'sendMessage', { chat_id: selected.chatId, text, parse_mode: 'HTML', allow_sending_without_reply: true, ...(markup ? { reply_markup: markup } : {}) })
|
|
225
|
+
}
|
|
226
|
+
} else sent = await telegram(fetcher, token, 'sendMessage', { chat_id: selected.chatId, text, parse_mode: 'HTML', allow_sending_without_reply: true, ...(markup ? { reply_markup: markup } : {}) })
|
|
227
|
+
if (!sent.ok) throw new Error('premium_package_selection_reply_failed')
|
|
228
|
+
if (packageData && sent.result?.message_id != null) {
|
|
229
|
+
await pool.query("UPDATE t_platform_telegram_conversation_state SET prompt_message_id=$4,updated_at=now() WHERE bot_rid=$1 AND chat_id=$2 AND user_id=$3 AND state='premium_purchase_username'", [botRid, selected.chatId, selected.userId, String(sent.result.message_id)])
|
|
230
|
+
}
|
|
231
|
+
return true
|
|
232
|
+
}
|
|
233
|
+
|
|
234
|
+
function parsePriceUnits(value: string) {
|
|
235
|
+
const match = /^(\d{1,8})(?:\.(\d{1,4}))?$/u.exec(value.trim())
|
|
236
|
+
if (!match) return null
|
|
237
|
+
return BigInt(match[1]) * 10_000n + BigInt((match[2] ?? '').padEnd(4, '0'))
|
|
238
|
+
}
|
|
239
|
+
|
|
240
|
+
function priceText(units: bigint) {
|
|
241
|
+
return (units / 10_000n).toString() + '.' + (units % 10_000n).toString().padStart(4, '0')
|
|
242
|
+
}
|
|
243
|
+
|
|
244
|
+
async function sendText(fetcher: typeof fetch, token: string, chatId: string, text: string, messageId?: number, replyMarkup?: Record<string, unknown>) {
|
|
245
|
+
const result = await telegram(fetcher, token, 'sendMessage', {
|
|
246
|
+
chat_id: chatId, text, parse_mode: 'HTML', allow_sending_without_reply: true,
|
|
247
|
+
...(messageId ? { reply_to_message_id: messageId } : {}),
|
|
248
|
+
...(replyMarkup ? { reply_markup: replyMarkup } : {}),
|
|
249
|
+
})
|
|
250
|
+
if (!result.ok) throw new Error('premium_purchase_reply_failed')
|
|
251
|
+
}
|
|
252
|
+
|
|
253
|
+
function purchaseReceipt(purchase: Purchase, replyMessageId: number) {
|
|
254
|
+
const stars = purchase.fulfillment_method === 'telegram_stars'
|
|
255
|
+
const keyboard = { inline_keyboard: [
|
|
256
|
+
[{ text: '余额支付', callback_data: 'tgpremiumwalletpay_' + purchase.order_rid }],
|
|
257
|
+
[{ text: '我要充值', callback_data: 'aitrusteeshiprechargetrx' }],
|
|
258
|
+
] }
|
|
259
|
+
const text = '<b>下单成功,请核对金额和地址支付</b>\n' +
|
|
260
|
+
'开通用户:' + escapeHtml(purchase.premium_tg_username) + '\n' +
|
|
261
|
+
'用户昵称:' + escapeHtml(purchase.premium_name) + '\n' +
|
|
262
|
+
'订单号:' + purchase.order_rid + '\n➖➖➖➖➖➖➖➖\n' +
|
|
263
|
+
'<b>🟢当前套餐:' + escapeHtml(purchase.package_name) + '</b>\n' +
|
|
264
|
+
'<b>🟢开通月份:</b>' + escapeHtml(purchase.premium_package_month) + '\n' +
|
|
265
|
+
'<b>🟢支付金额:</b><code>' + escapeHtml(purchase.need_pay_usdt) + '</code> <b>USDT</b> (点击金额复制)\n' +
|
|
266
|
+
'<b>🟢支付地址:</b><code>' + escapeHtml(purchase.receive_wallet) + '</code>\n' +
|
|
267
|
+
(stars ? '<b>🟢开通方式:</b>Telegram Stars(机器人将消耗 <code>' + escapeHtml(purchase.need_pay_stars) + '</code> Stars)\n' : '') +
|
|
268
|
+
'<b>🟢失效时间:' + escapeHtml(purchase.expire_time) + '</b>\n➖➖➖➖➖➖➖➖\n' +
|
|
269
|
+
'⚠️<b>请在订单失效时间支付,订单过期后请重新发起!</b>\n' +
|
|
270
|
+
'⚠️<b>点击地址和金额复制,金额或者地址错误将无法追回!</b>\n' +
|
|
271
|
+
'⏬<b>点击余额支付,可直接使用充值的 USDT 余额支付</b>\n' +
|
|
272
|
+
(stars ? 'Bot 将在 USDT 收款确认后使用 Telegram Stars 官方接口开通。\n' : '') +
|
|
273
|
+
'当前时间:' + escapeHtml(purchase.created_at)
|
|
274
|
+
return { chatId: purchase.chat_id, messageId: replyMessageId, text, markup: keyboard }
|
|
275
|
+
}
|
|
276
|
+
|
|
277
|
+
async function notifyPurchase(pool: Database, fetcher: typeof fetch, token: string, purchase: Purchase, replyMessageId: number) {
|
|
278
|
+
const client = await pool.connect()
|
|
279
|
+
try {
|
|
280
|
+
await client.query('BEGIN')
|
|
281
|
+
const current = await client.query<Purchase>('SELECT update_rid,bot_rid,chat_id,premium_tg_username,premium_name,order_rid,package_name,premium_package_month,fulfillment_method,need_pay_usdt::text AS need_pay_usdt,need_pay_stars,premium_tg_user_id::text AS premium_tg_user_id,receive_wallet,to_char(created_at,\'YYYY-MM-DD HH24:MI:SS\') AS created_at,to_char(expire_time,\'YYYY-MM-DD HH24:MI:SS\') AS expire_time,notification_sent_at IS NOT NULL AS notification_sent FROM t_platform_telegram_premium_purchase WHERE update_rid=$1 AND bot_rid=$2 AND chat_id=$3 FOR UPDATE', [purchase.update_rid, purchase.bot_rid, purchase.chat_id])
|
|
282
|
+
const row = current.rows[0]
|
|
283
|
+
if (!row || row.notification_sent) { await client.query('COMMIT'); return }
|
|
284
|
+
const receipt = purchaseReceipt(row, replyMessageId)
|
|
285
|
+
const sent = await telegram(fetcher, token, 'sendMessage', { chat_id: receipt.chatId, text: receipt.text, reply_to_message_id: receipt.messageId, parse_mode: 'HTML', allow_sending_without_reply: true, reply_markup: receipt.markup })
|
|
286
|
+
if (!sent.ok) throw new Error('premium_purchase_receipt_delivery_failed')
|
|
287
|
+
await client.query('UPDATE t_platform_telegram_premium_purchase SET notification_sent_at=now() WHERE update_rid=$1 AND bot_rid=$2 AND chat_id=$3 AND notification_sent_at IS NULL', [purchase.update_rid, purchase.bot_rid, purchase.chat_id])
|
|
288
|
+
await client.query('COMMIT')
|
|
289
|
+
} catch (error) {
|
|
290
|
+
await client.query('ROLLBACK').catch(() => undefined)
|
|
291
|
+
throw error
|
|
292
|
+
} finally { client.release() }
|
|
293
|
+
}
|
|
294
|
+
|
|
295
|
+
async function existingPurchase(pool: Queryable, updateRid: number, botRid: number, chatId: string) {
|
|
296
|
+
const result = await pool.query<Purchase>('SELECT update_rid,bot_rid,chat_id,premium_tg_username,premium_name,order_rid,package_name,premium_package_month,fulfillment_method,need_pay_usdt::text AS need_pay_usdt,need_pay_stars,premium_tg_user_id::text AS premium_tg_user_id,receive_wallet,to_char(created_at,\'YYYY-MM-DD HH24:MI:SS\') AS created_at,to_char(expire_time,\'YYYY-MM-DD HH24:MI:SS\') AS expire_time,notification_sent_at IS NOT NULL AS notification_sent FROM t_platform_telegram_premium_purchase WHERE update_rid=$1 AND bot_rid=$2 AND chat_id=$3 LIMIT 1', [updateRid, botRid, chatId])
|
|
297
|
+
return result.rows[0]
|
|
298
|
+
}
|
|
299
|
+
|
|
300
|
+
async function resolveTelegramStarsRecipient(pool: Queryable, botRid: number, value: string) {
|
|
301
|
+
let userId = ''
|
|
302
|
+
let label = ''
|
|
303
|
+
let name = ''
|
|
304
|
+
if (telegramIdPattern.test(value)) {
|
|
305
|
+
const parsed = BigInt(value)
|
|
306
|
+
if (parsed <= 0n || parsed > BigInt(Number.MAX_SAFE_INTEGER)) return null
|
|
307
|
+
userId = parsed.toString()
|
|
308
|
+
const found = await pool.query<{tg_username:string|null;tg_nickname:string|null}>('SELECT tg_username,tg_nickname FROM t_telegram_bot_user WHERE bot_rid=$1 AND tg_uid=$2 AND status=1 LIMIT 1',[botRid,userId])
|
|
309
|
+
const knownUsername=String(found.rows[0]?.tg_username??'').replace(/^@/,'').trim()
|
|
310
|
+
label=knownUsername?'@'+knownUsername:'TGID '+userId
|
|
311
|
+
name=String(found.rows[0]?.tg_nickname??label)
|
|
312
|
+
} else if (usernamePattern.test(value)) {
|
|
313
|
+
const lookup = await pool.query<{tg_uid:string;tg_username:string|null;tg_nickname:string|null}>("SELECT tg_uid::text,tg_username,tg_nickname FROM t_telegram_bot_user WHERE bot_rid=$1 AND status=1 AND lower(trim(tg_username,'@'))=lower($2) ORDER BY last_time DESC NULLS LAST LIMIT 2",[botRid,value.slice(1)])
|
|
314
|
+
if (lookup.rows.length !== 1) return null
|
|
315
|
+
const parsed=BigInt(lookup.rows[0].tg_uid)
|
|
316
|
+
if(parsed<=0n||parsed>BigInt(Number.MAX_SAFE_INTEGER))return null
|
|
317
|
+
userId=parsed.toString()
|
|
318
|
+
label='@'+String(lookup.rows[0].tg_username??value).replace(/^@/,'')
|
|
319
|
+
name=String(lookup.rows[0].tg_nickname??label)
|
|
320
|
+
} else return null
|
|
321
|
+
return {userId,label,name}
|
|
322
|
+
}
|
|
323
|
+
|
|
324
|
+
function uniqueRandomPrice(base: bigint) {
|
|
325
|
+
const offsets = Array.from({ length: 101 }, (_, index) => index + 100)
|
|
326
|
+
for (let index = offsets.length - 1; index > 0; index--) {
|
|
327
|
+
const swap = randomInt(index + 1)
|
|
328
|
+
;[offsets[index], offsets[swap]] = [offsets[swap], offsets[index]]
|
|
329
|
+
}
|
|
330
|
+
return offsets.map(offset => priceText(base + BigInt(offset)))
|
|
331
|
+
}
|
|
332
|
+
|
|
333
|
+
export async function handleTelegramPremiumUsernameReply(pool: Database, fetcher: typeof fetch, botRid: number, updateRid: number, message: Message, decryptSecret?: PremiumSecretDecryptor) {
|
|
334
|
+
const selected = premiumMessage(message)
|
|
335
|
+
if (!selected) return false
|
|
336
|
+
const token = await botTokenFor(pool, botRid)
|
|
337
|
+
const savedPurchase = await existingPurchase(pool, updateRid, botRid, selected.chatId)
|
|
338
|
+
if (savedPurchase) {
|
|
339
|
+
await notifyPurchase(pool, fetcher, token, savedPurchase, selected.messageId)
|
|
340
|
+
return true
|
|
341
|
+
}
|
|
342
|
+
const stateResult = await pool.query<{ context: unknown }>("SELECT context FROM t_platform_telegram_conversation_state WHERE bot_rid=$1 AND chat_id=$2 AND user_id=$3 AND state='premium_purchase_username' AND expires_at>now() LIMIT 1", [botRid, selected.chatId, selected.userId])
|
|
343
|
+
const state = stateResult.rows[0]
|
|
344
|
+
if (!state) {
|
|
345
|
+
await sendText(fetcher, token, selected.chatId, '套餐选择会话已过期,请重新选择会员套餐。', selected.messageId)
|
|
346
|
+
return true
|
|
347
|
+
}
|
|
348
|
+
const context = contextObject(state.context)
|
|
349
|
+
const packageRid = Number(context.packageRid)
|
|
350
|
+
const sessionId = String(context.sessionId ?? '')
|
|
351
|
+
if (!Number.isSafeInteger(packageRid) || packageRid <= 0 || !sessionId) {
|
|
352
|
+
await sendText(fetcher, token, selected.chatId, '套餐会话无效,请重新选择会员套餐。', selected.messageId)
|
|
353
|
+
return true
|
|
354
|
+
}
|
|
355
|
+
const pending = await pool.query<{ rid: number }>('SELECT rid FROM t_premium_platform_order WHERE bot_rid=$1 AND status IN (0,1) AND buy_tg_uid=$2 ORDER BY rid DESC LIMIT 1', [botRid, selected.chatId])
|
|
356
|
+
if (pending.rows[0]) {
|
|
357
|
+
await sendText(fetcher, token, selected.chatId, '您还有未完成的会员订单,暂时无法继续提交。若需重新提交,请先取消未完成的订单。', selected.messageId, { inline_keyboard: [[{ text: '取消未完成的订单', callback_data: 'cancelpremiumunpaid' }]] })
|
|
358
|
+
return true
|
|
359
|
+
}
|
|
360
|
+
const packageResult = await pool.query<PremiumPackage>('SELECT p.rid,p.premium_platform_rid,b.platform_name,p.package_name,p.package_month,p.usdt_price::text AS usdt_price,p.show_notes,p.package_pic,b.receive_wallet,b.platform_hash,b.platform_cookie FROM t_premium_platform_package p JOIN t_premium_platform b ON b.rid=p.premium_platform_rid WHERE p.rid=$1 AND p.bot_rid=$2 AND p.status=0 AND b.status=0 LIMIT 1', [packageRid, botRid])
|
|
361
|
+
const packageData = packageResult.rows[0]
|
|
362
|
+
if (!packageData) {
|
|
363
|
+
await sendText(fetcher, token, selected.chatId, '该会员套餐已暂停购买,请重新选择其他套餐。', selected.messageId)
|
|
364
|
+
return true
|
|
365
|
+
}
|
|
366
|
+
const starsMode = Number(packageData.platform_name) === 3
|
|
367
|
+
let fragment: { recipient: string; displayName: string } | null = null
|
|
368
|
+
let targetUserId: string | null = null
|
|
369
|
+
let targetLabel = selected.username
|
|
370
|
+
let premiumName = ''
|
|
371
|
+
let starCount = 0
|
|
372
|
+
const basePrice = parsePriceUnits(packageData.usdt_price)
|
|
373
|
+
if (basePrice === null || basePrice <= 0n || basePrice + 200n > 999_999_999_999n) {
|
|
374
|
+
await sendText(fetcher, token, selected.chatId, '当前会员套餐价格配置无效,请联系管理员。', selected.messageId)
|
|
375
|
+
return true
|
|
376
|
+
}
|
|
377
|
+
if (!packageData.receive_wallet) {
|
|
378
|
+
await sendText(fetcher, token, selected.chatId, '会员平台尚未配置 USDT 收款钱包,暂时无法创建订单,请联系管理员。', selected.messageId)
|
|
379
|
+
return true
|
|
380
|
+
}
|
|
381
|
+
if (starsMode) {
|
|
382
|
+
const target = await resolveTelegramStarsRecipient(pool, botRid, selected.username)
|
|
383
|
+
if (!target) {
|
|
384
|
+
await sendText(fetcher, token, selected.chatId, '机器人尚未记录该用户名对应的 Telegram ID。请让目标用户先与机器人互动后重试,或直接发送其 Telegram 数字 ID。', selected.messageId)
|
|
385
|
+
return true
|
|
386
|
+
}
|
|
387
|
+
targetUserId = target.userId
|
|
388
|
+
targetLabel = target.label
|
|
389
|
+
premiumName = target.name
|
|
390
|
+
starCount = telegramPremiumStarPrice(packageData.package_month) ?? 0
|
|
391
|
+
if (!starCount) {
|
|
392
|
+
await sendText(fetcher, token, selected.chatId, 'Telegram Stars 会员套餐月份无效,请联系管理员。', selected.messageId)
|
|
393
|
+
return true
|
|
394
|
+
}
|
|
395
|
+
} else {
|
|
396
|
+
if (!usernamePattern.test(selected.username)) {
|
|
397
|
+
await sendText(fetcher, token, selected.chatId, '用户名格式不正确,请输入以 @ 开头的 Telegram 用户名,例如 @username。', selected.messageId)
|
|
398
|
+
return true
|
|
399
|
+
}
|
|
400
|
+
if (!packageData.platform_hash || !packageData.platform_cookie) {
|
|
401
|
+
await sendText(fetcher, token, selected.chatId, 'Fragment 平台配置不完整,暂时无法创建订单,请联系管理员。', selected.messageId)
|
|
402
|
+
return true
|
|
403
|
+
}
|
|
404
|
+
try { fragment = await searchFragmentRecipient(fetcher, packageData, selected.username, decryptSecret); premiumName = fragment.displayName }
|
|
405
|
+
catch (error) {
|
|
406
|
+
const reason = error instanceof Error && error.message !== 'RSA_PRIVATE_KEY_UNAVAILABLE' && error.message !== 'PREMIUM_PLATFORM_COOKIE_MISSING' && error.message !== 'RSA_CIPHERTEXT_INVALID'
|
|
407
|
+
? escapeHtml(error.message.replace(/[\u0000-\u001f<>]/gu, ' ').slice(0, 180)) : '平台暂时无法验证该用户'
|
|
408
|
+
await sendText(fetcher, token, selected.chatId, '获取用户信息失败,请检查用户名是否正确,例如 @username。\n错误信息:' + reason, selected.messageId)
|
|
409
|
+
return true
|
|
410
|
+
}
|
|
411
|
+
}
|
|
412
|
+
|
|
413
|
+
const client = await pool.connect()
|
|
414
|
+
let purchase: Purchase | undefined
|
|
415
|
+
let hasPendingOrder = false
|
|
416
|
+
let sessionChanged = false
|
|
417
|
+
try {
|
|
418
|
+
await client.query('BEGIN')
|
|
419
|
+
await client.query("SELECT pg_advisory_xact_lock(hashtextextended('telegram-premium-buyer:' || $1 || ':' || $2,0))", [botRid, selected.chatId])
|
|
420
|
+
const duplicate = await client.query<Purchase>('SELECT update_rid,bot_rid,chat_id,premium_tg_username,premium_name,order_rid,package_name,premium_package_month,fulfillment_method,need_pay_usdt::text AS need_pay_usdt,need_pay_stars,premium_tg_user_id::text AS premium_tg_user_id,receive_wallet,to_char(created_at,\'YYYY-MM-DD HH24:MI:SS\') AS created_at,to_char(expire_time,\'YYYY-MM-DD HH24:MI:SS\') AS expire_time,notification_sent_at IS NOT NULL AS notification_sent FROM t_platform_telegram_premium_purchase WHERE update_rid=$1 AND bot_rid=$2 AND chat_id=$3 FOR UPDATE', [updateRid, botRid, selected.chatId])
|
|
421
|
+
if (duplicate.rows[0]) purchase = duplicate.rows[0]
|
|
422
|
+
else {
|
|
423
|
+
const currentState = await client.query<{ context: unknown }>("SELECT context FROM t_platform_telegram_conversation_state WHERE bot_rid=$1 AND chat_id=$2 AND user_id=$3 AND state='premium_purchase_username' AND expires_at>now() FOR UPDATE", [botRid, selected.chatId, selected.userId])
|
|
424
|
+
const currentContext = contextObject(currentState.rows[0]?.context)
|
|
425
|
+
if (String(currentContext.sessionId ?? '') !== sessionId || Number(currentContext.packageRid) !== packageRid) sessionChanged = true
|
|
426
|
+
else {
|
|
427
|
+
const existingOrder = await client.query<{ rid: number }>('SELECT rid FROM t_premium_platform_order WHERE bot_rid=$1 AND status IN (0,1) AND buy_tg_uid=$2 ORDER BY rid DESC LIMIT 1 FOR UPDATE', [botRid, selected.chatId])
|
|
428
|
+
if (existingOrder.rows[0]) hasPendingOrder = true
|
|
429
|
+
else {
|
|
430
|
+
if (basePrice === null) throw new Error('PREMIUM_PRICE_MISSING')
|
|
431
|
+
await client.query("SELECT pg_advisory_xact_lock(hashtextextended('telegram-premium-order-price',0))")
|
|
432
|
+
let amount = ''
|
|
433
|
+
for (const candidate of uniqueRandomPrice(basePrice)) {
|
|
434
|
+
const occupied = await client.query('SELECT 1 FROM t_premium_platform_order WHERE status IN (0,1) AND need_pay_usdt=$1::numeric LIMIT 1', [candidate])
|
|
435
|
+
if (!occupied.rows.length) { amount = candidate; break }
|
|
436
|
+
}
|
|
437
|
+
if (!amount) throw new Error('PREMIUM_RANDOM_PRICE_EXHAUSTED')
|
|
438
|
+
const inserted = await client.query<{ rid: number; expire_time: string }>('INSERT INTO t_premium_platform_order(bot_rid,premium_platform_rid,source_type,buy_tg_uid,buy_tg_username,premium_tg_username,need_pay_usdt,status,premium_platform_package_rid,premium_package_month,create_time,expire_time,recipient,fulfillment_method,need_pay_stars,premium_tg_user_id) VALUES($1,$2,2,$3,$4,$5,$6::numeric,0,$7,$8,now(),now()+interval \'15 minutes\',$9,$10,$11,$12) RETURNING rid,to_char(expire_time,\'YYYY-MM-DD HH24:MI:SS\') AS expire_time', [botRid, packageData.premium_platform_rid, selected.chatId, selected.buyerUsername || null, targetLabel, amount, packageRid, packageData.package_month, fragment?.recipient ?? null, starsMode ? 'telegram_stars' : 'fragment_ton', starCount, targetUserId])
|
|
439
|
+
const order = inserted.rows[0]
|
|
440
|
+
if (!order) throw new Error('PREMIUM_ORDER_INSERT_FAILED')
|
|
441
|
+
const purchaseName=starsMode?premiumName:fragment!.displayName
|
|
442
|
+
const saved = await client.query<Purchase>("INSERT INTO t_platform_telegram_premium_purchase(update_rid,bot_rid,chat_id,premium_tg_username,premium_name,order_rid,package_name,premium_package_month,need_pay_usdt,receive_wallet,expire_time,fulfillment_method,need_pay_stars,premium_tg_user_id) VALUES($1,$2,$3,$4,$5,$6,$7,$8,$9::numeric,$10,$11::timestamp,$12,$13,$14) RETURNING update_rid,bot_rid,chat_id,premium_tg_username,premium_name,order_rid,package_name,premium_package_month,fulfillment_method,need_pay_usdt::text AS need_pay_usdt,need_pay_stars,premium_tg_user_id::text AS premium_tg_user_id,receive_wallet,to_char(created_at,'YYYY-MM-DD HH24:MI:SS') AS created_at,to_char(expire_time,'YYYY-MM-DD HH24:MI:SS') AS expire_time,false AS notification_sent", [updateRid, botRid, selected.chatId, targetLabel, purchaseName, order.rid, packageData.package_name, packageData.package_month, amount, packageData.receive_wallet, order.expire_time, starsMode?'telegram_stars':'fragment_ton', starCount, targetUserId])
|
|
443
|
+
purchase = saved.rows[0]
|
|
444
|
+
if (!purchase) throw new Error('PREMIUM_PURCHASE_IDEMPOTENCY_INSERT_FAILED')
|
|
445
|
+
await client.query("DELETE FROM t_platform_telegram_conversation_state WHERE bot_rid=$1 AND chat_id=$2 AND user_id=$3 AND state='premium_purchase_username' AND context->>'sessionId'=$4", [botRid, selected.chatId, selected.userId, sessionId])
|
|
446
|
+
}
|
|
447
|
+
}
|
|
448
|
+
}
|
|
449
|
+
await client.query('COMMIT')
|
|
450
|
+
} catch (error) {
|
|
451
|
+
await client.query('ROLLBACK').catch(() => undefined)
|
|
452
|
+
throw error
|
|
453
|
+
} finally { client.release() }
|
|
454
|
+
|
|
455
|
+
if (sessionChanged) {
|
|
456
|
+
await sendText(fetcher, token, selected.chatId, '套餐选择已更新,请重新选择套餐后再发送用户名。', selected.messageId)
|
|
457
|
+
return true
|
|
458
|
+
}
|
|
459
|
+
if (hasPendingOrder) {
|
|
460
|
+
await sendText(fetcher, token, selected.chatId, '您还有未完成的会员订单,暂时无法继续提交。若需重新提交,请先取消未完成的订单。', selected.messageId, { inline_keyboard: [[{ text: '取消未完成的订单', callback_data: 'cancelpremiumunpaid' }]] })
|
|
461
|
+
return true
|
|
462
|
+
}
|
|
463
|
+
if (!purchase) throw new Error('PREMIUM_PURCHASE_STATE_INVALID')
|
|
464
|
+
await notifyPurchase(pool, fetcher, token, purchase, selected.messageId)
|
|
465
|
+
return true
|
|
466
|
+
}
|
|
467
|
+
|
|
468
|
+
function verifiedCallback(update: Update, pattern: RegExp, allowedChats: string[] = ['private']) {
|
|
469
|
+
const callback = update?.callback_query, message = callback?.message
|
|
470
|
+
const chatId = String(message?.chat?.id ?? ''), userId = String(callback?.from?.id ?? ''), data = String(callback?.data ?? '')
|
|
471
|
+
const keyboard = message?.reply_markup?.inline_keyboard
|
|
472
|
+
if (!message || !allowedChats.includes(String(message.chat?.type)) || !/^-?\d{1,20}$/u.test(chatId) || !/^\d{1,20}$/u.test(userId) || (message.chat?.type === 'private' && chatId !== userId) || callback?.from?.is_bot || !pattern.test(data)) return null
|
|
473
|
+
if (!Array.isArray(keyboard) || !keyboard.some((row: unknown) => Array.isArray(row) && row.some((button: any) => button?.callback_data === data))) return null
|
|
474
|
+
return { callback, message, chatId, data }
|
|
475
|
+
}
|
|
476
|
+
|
|
477
|
+
async function botToken(pool: Queryable, botRid: number) {
|
|
478
|
+
const result = await pool.query<{ bot_token: string | null }>('SELECT bot_token FROM t_telegram_bot WHERE rid=$1', [botRid])
|
|
479
|
+
const token = result.rows[0]?.bot_token
|
|
480
|
+
if (!token) throw new Error('PREMIUM_BOT_MISSING')
|
|
481
|
+
return token
|
|
482
|
+
}
|
|
483
|
+
|
|
484
|
+
async function answerPremiumCallback(fetcher: typeof fetch, token: string, method: string, payload: Record<string, unknown>): Promise<TelegramResult> {
|
|
485
|
+
if (process.env.PLATFORM_TELEGRAM_ACTIONS !== 'true' || !/^\d{5,20}:[A-Za-z0-9_-]{20,100}$/u.test(token)) return { ok: false }
|
|
486
|
+
try {
|
|
487
|
+
const response = await fetcher('https://api.telegram.org/bot' + token + '/' + method, { method: 'POST', headers: telegramHeaders, body: JSON.stringify(payload), redirect: 'error', signal: AbortSignal.timeout(12_000) })
|
|
488
|
+
return await response.json() as TelegramResult
|
|
489
|
+
} catch { return { ok: false } }
|
|
490
|
+
}
|
|
491
|
+
|
|
492
|
+
function decimalAmount(value: unknown) {
|
|
493
|
+
const match = String(value ?? '').trim().match(/^(\d+)(?:\.(\d+))?$/u)
|
|
494
|
+
if (!match) return null
|
|
495
|
+
const fraction = match[2] ?? ''
|
|
496
|
+
return { units: BigInt(match[1]) * 10n ** BigInt(fraction.length) + BigInt(fraction || '0'), scale: fraction.length }
|
|
497
|
+
}
|
|
498
|
+
|
|
499
|
+
export async function handlePremiumWalletPayCallback(pool: Database, fetcher: typeof fetch, botRid: number, update: Update) {
|
|
500
|
+
const selected = verifiedCallback(update, /^tgpremiumwalletpay_([1-9][0-9]{0,9})$/u)
|
|
501
|
+
if (!selected) return false
|
|
502
|
+
const orderRid = Number(/^tgpremiumwalletpay_(\d+)$/u.exec(selected.data)?.[1])
|
|
503
|
+
const token = await botToken(pool, botRid)
|
|
504
|
+
if (selected.callback.id != null) await answerPremiumCallback(fetcher, token, 'answerCallbackQuery', { callback_query_id: String(selected.callback.id) })
|
|
505
|
+
const client = await pool.connect()
|
|
506
|
+
let outcome: 'not_pending'|'insufficient'|'paid' = 'not_pending', username = '', months = ''
|
|
507
|
+
try {
|
|
508
|
+
await client.query('BEGIN')
|
|
509
|
+
const order = await client.query<{ need_pay_usdt: string; premium_tg_username: string|null; premium_package_month: number|string|null }>('SELECT need_pay_usdt::text,premium_tg_username,premium_package_month FROM t_premium_platform_order WHERE rid=$1 AND bot_rid=$2 AND buy_tg_uid=$3 AND status=0 FOR UPDATE', [orderRid, botRid, selected.chatId])
|
|
510
|
+
if (order.rows[0]) {
|
|
511
|
+
const amountText = String(order.rows[0].need_pay_usdt ?? ''), amount = decimalAmount(amountText)
|
|
512
|
+
if (amount && amount.units > 0n && /^\d{1,20}(?:\.\d{1,6})?$/u.test(amountText)) {
|
|
513
|
+
const user = await client.query<{ rid: number }>('SELECT rid FROM t_telegram_bot_user WHERE bot_rid=$1 AND tg_uid=$2 FOR UPDATE', [botRid, selected.chatId])
|
|
514
|
+
if (!user.rows[0]) outcome = 'insufficient'
|
|
515
|
+
else {
|
|
516
|
+
const debit = await client.query('UPDATE t_telegram_bot_user SET cash_usdt=cash_usdt-$3::numeric WHERE rid=$1 AND bot_rid=$2 AND cash_usdt >= $3::numeric RETURNING cash_usdt::text', [user.rows[0].rid, botRid, amountText])
|
|
517
|
+
if (!debit.rowCount) outcome = 'insufficient'
|
|
518
|
+
else {
|
|
519
|
+
const paid = await client.query('UPDATE t_premium_platform_order SET status=1,update_time=now() WHERE rid=$1 AND bot_rid=$2 AND buy_tg_uid=$3 AND status=0 RETURNING rid', [orderRid, botRid, selected.chatId])
|
|
520
|
+
if (!paid.rowCount) throw new Error('PREMIUM_WALLET_ORDER_STATE_CONFLICT')
|
|
521
|
+
username = String(order.rows[0].premium_tg_username ?? '')
|
|
522
|
+
months = String(order.rows[0].premium_package_month ?? '')
|
|
523
|
+
outcome = 'paid'
|
|
524
|
+
}
|
|
525
|
+
}
|
|
526
|
+
}
|
|
527
|
+
}
|
|
528
|
+
await client.query('COMMIT')
|
|
529
|
+
} catch (error) { await client.query('ROLLBACK').catch(() => undefined); throw error } finally { client.release() }
|
|
530
|
+
const result = outcome === 'paid'
|
|
531
|
+
? await answerPremiumCallback(fetcher, token, 'editMessageText', { chat_id: selected.chatId, message_id: selected.message.message_id, text: `会员订单支付成功,开通中···\n开通用户:${escapeHtml(username)}\n开通时间:${escapeHtml(months)}`, parse_mode: 'HTML', allow_sending_without_reply: true })
|
|
532
|
+
: await answerPremiumCallback(fetcher, token, 'sendMessage', { chat_id: selected.chatId, text: outcome === 'insufficient' ? '用户USDT余额不足' : '订单不存在或者不是待支付状态', reply_to_message_id: selected.message.message_id, parse_mode: 'Markdown', allow_sending_without_reply: true })
|
|
533
|
+
if (!result.ok) throw new Error(outcome === 'paid' ? 'PREMIUM_WALLET_PAY_SUCCESS_MESSAGE_FAILED' : 'PREMIUM_WALLET_PAY_RESULT_MESSAGE_FAILED')
|
|
534
|
+
return true
|
|
535
|
+
}
|
|
536
|
+
|
|
537
|
+
export async function handlePremiumCancelUnpaidCallback(pool: Database, fetcher: typeof fetch, botRid: number, update: Update) {
|
|
538
|
+
const selected = verifiedCallback(update, /^cancelpremiumunpaid$/u)
|
|
539
|
+
if (!selected) return false
|
|
540
|
+
const token = await botToken(pool, botRid)
|
|
541
|
+
if (selected.callback.id != null) await answerPremiumCallback(fetcher, token, 'answerCallbackQuery', { callback_query_id: String(selected.callback.id) })
|
|
542
|
+
const client = await pool.connect()
|
|
543
|
+
try {
|
|
544
|
+
await client.query('BEGIN')
|
|
545
|
+
await client.query("SELECT pg_advisory_xact_lock(hashtextextended('telegram-premium-cancel:' || $1 || ':' || $2,0))", [botRid, selected.chatId])
|
|
546
|
+
await client.query('UPDATE t_premium_platform_order SET status=4,cancel_time=now() WHERE bot_rid=$1 AND status=0 AND buy_tg_uid=$2', [botRid, selected.chatId])
|
|
547
|
+
await client.query('COMMIT')
|
|
548
|
+
} catch (error) { await client.query('ROLLBACK').catch(() => undefined); throw error } finally { client.release() }
|
|
549
|
+
const sent = await answerPremiumCallback(fetcher, token, 'sendMessage', { chat_id: selected.chatId, text: '您的未完成会员订单已取消,可重新发起购买会员!', parse_mode: 'Markdown', allow_sending_without_reply: true })
|
|
550
|
+
if (!sent.ok) throw new Error('PREMIUM_CANCEL_UNPAID_REPLY_FAILED')
|
|
551
|
+
return true
|
|
552
|
+
}
|
|
553
|
+
|
|
554
|
+
export async function handlePremiumChooseAgainCallback(pool: Database, fetcher: typeof fetch, botRid: number, update: Update) {
|
|
555
|
+
const selected = verifiedCallback(update, /^重新选择套餐premium$/u, ['private', 'group', 'supergroup'])
|
|
556
|
+
if (!selected) return false
|
|
557
|
+
const token = await botToken(pool, botRid)
|
|
558
|
+
const sent = await answerPremiumCallback(fetcher, token, 'answerCallbackQuery', { callback_query_id: String(selected.callback.id ?? ''), text: '开通 Telegram 会员前,请仔细核对收款地址、支付金额和开通账号。', show_alert: true })
|
|
559
|
+
if (!sent.ok) throw new Error('PREMIUM_CHOOSE_AGAIN_ALERT_FAILED')
|
|
560
|
+
return true
|
|
561
|
+
}
|
|
562
|
+
|
|
563
|
+
export async function handlePremiumTelegramCallback(pool: Database, fetcher: typeof fetch, botRid: number, update: Update, decryptSecret?: PremiumSecretDecryptor) {
|
|
564
|
+
if (await handleTelegramPremiumPackageCallback(pool, fetcher, botRid, update, decryptSecret)) return true
|
|
565
|
+
if (await handlePremiumWalletPayCallback(pool, fetcher, botRid, update)) return true
|
|
566
|
+
if (await handlePremiumCancelUnpaidCallback(pool, fetcher, botRid, update)) return true
|
|
567
|
+
return handlePremiumChooseAgainCallback(pool, fetcher, botRid, update)
|
|
568
|
+
}
|
package/src/server.d.ts
ADDED
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
import type { DatabaseConnection } from './host-types.js';
|
|
2
|
+
import { type PremiumAdminHost } from './admin-api.js';
|
|
3
|
+
import { isPremiumCallbackUpdate, isPremiumUsernameReplyCandidate, type PremiumTelegramMessage, type PremiumTelegramUpdate } from './purchases.js';
|
|
4
|
+
import { type PremiumScheduledTaskOptions } from './tasks.js';
|
|
5
|
+
export type PremiumModuleDatabase = Pick<DatabaseConnection, 'query' | 'connect'>;
|
|
6
|
+
export type PremiumModuleRuntimeOptions = {
|
|
7
|
+
adminHost: PremiumAdminHost;
|
|
8
|
+
fetcher?: typeof fetch;
|
|
9
|
+
getWalletApiKeys: (pool: PremiumModuleDatabase) => Promise<string[]>;
|
|
10
|
+
decryptSecret: PremiumScheduledTaskOptions['decryptSecret'];
|
|
11
|
+
runPayment: PremiumScheduledTaskOptions['runPayment'];
|
|
12
|
+
preflight: PremiumScheduledTaskOptions['preflight'];
|
|
13
|
+
walletPollingEnabled?: boolean;
|
|
14
|
+
telegramActionsEnabled?: boolean;
|
|
15
|
+
fulfillmentEnabled?: boolean;
|
|
16
|
+
allowTelegramStars?: boolean;
|
|
17
|
+
};
|
|
18
|
+
export declare function createPremiumModuleRuntime(options: PremiumModuleRuntimeOptions): {
|
|
19
|
+
manifest: import("./index.js").PremiumPluginManifest;
|
|
20
|
+
api: {
|
|
21
|
+
platforms: (request: Request) => Promise<Response>;
|
|
22
|
+
packages: (request: Request) => Promise<Response>;
|
|
23
|
+
orders: (request: Request) => Promise<Response>;
|
|
24
|
+
trades: (request: Request) => Promise<Response>;
|
|
25
|
+
};
|
|
26
|
+
createTasks(pool: PremiumModuleDatabase, logger?: PremiumScheduledTaskOptions["logger"]): import("./tasks.js").PremiumScheduledTask[];
|
|
27
|
+
telegram: {
|
|
28
|
+
claimPredicates: {
|
|
29
|
+
package: string;
|
|
30
|
+
walletPay: string;
|
|
31
|
+
cancelUnpaid: string;
|
|
32
|
+
chooseAgain: string;
|
|
33
|
+
usernameReply: string;
|
|
34
|
+
};
|
|
35
|
+
isCallbackUpdate: typeof isPremiumCallbackUpdate;
|
|
36
|
+
isUsernameReplyCandidate: typeof isPremiumUsernameReplyCandidate;
|
|
37
|
+
isUsernameReplyForPrompt: (pool: Pick<PremiumModuleDatabase, "query">, botRid: number, update: PremiumTelegramUpdate) => Promise<boolean>;
|
|
38
|
+
handleCallback: (pool: PremiumModuleDatabase, fetcher: typeof fetch, botRid: number, update: PremiumTelegramUpdate) => Promise<boolean>;
|
|
39
|
+
handleUsernameReply: (pool: PremiumModuleDatabase, fetcher: typeof fetch, botRid: number, updateRid: number, message: PremiumTelegramMessage) => Promise<boolean>;
|
|
40
|
+
};
|
|
41
|
+
};
|