amanjha18v/AMAN_SHOPS_BOTPublic · Bot Template
AIAMAN SHOP STORE appears to be a Telegram automation bot. Commands include /*, /addbal, /addbal_all, /addbal_binance, /addbal_binance_approve, /addbal_binance_paid, /addbal_upi, /addcat_id. Observed in code: messaging, http, libs, keyboards, payments.
Utilityutility
132 commands0 envUpdated 6h agoCreated Sep 4, 2026
commands/_onBuyCheck.js
javascript · 447 lines
1/**#command2name: /onBuyCheck3answer: 4keyboard: 5parse_mode: markdown6aliases: 7allow_only_group: false8need_reply: false9is_web: 010#command**/11 12function resolveApiDuration(plan, cleanPlanDays, planUnit, productNameOverride) {13 // IMPORTANT: Keep the admin/API duration name exactly as entered.14 // The product-specific day ranges below are used only when the stored plan15 // contains a plain numeric Day duration; this lets 1-30 Day plans target16 // the exact website/API names requested by the admin without changing any17 // other product data or purchase logic.18 var raw = String((plan && (plan.api_duration || plan.name_on_website || plan.durationDisplay || plan.name || plan.title)) || "").replace(/\s+/g, " ").trim();19 20 // Already-custom API labels (including casing/suffixes) must pass through unchanged.21 if (raw && !/^[0-9]+(?:\.[0-9]+)?\s*(day|days)$/i.test(raw)) {22 return raw;23 }24 25 var dayMatch = raw.match(/^([0-9]+(?:\.[0-9]+)?)\s*(day|days)$/i);26 var n = dayMatch ? dayMatch[1] : String(cleanPlanDays || "1");27 var productName = String(productNameOverride || (plan && (plan.product_name || plan.productName || plan.product || plan.category)) || "").trim().toLowerCase();28 29 // If product name is not stored on the plan, the caller's raw API label is30 // still preserved above. Generic numeric Day plans remain "N Days".31 if (/pc\s*aim\s*silent/.test(productName)) return n + " Day Pc Aim Silent";32 if (/pc\s*modmenu\s*x86/.test(productName)) return n + " Day Pc Modmenu x86";33 if (/pc\s*bypass\s*\+\s*silent/.test(productName) || /bypass\s*\+\s*silent/.test(productName)) return n + " Days Pc Bypass + Silent";34 if (/nonroot/.test(productName) && !/root\s*\+\s*nonroot/.test(productName)) return n + " DaYS NONROOT";35 if (/pc\s*aimkill/.test(productName) || /aimkill/.test(productName)) return n + " DaYS PC AIMKILL";36 if (/root\s*\+\s*nonroot/.test(productName)) return n + " DaYs Root + Nonroot";37 if (/fluo?rite\s*ff/.test(productName)) return n + " DAYs FluoRite FF";38 if (/\broot\b/.test(productName)) return n + " DaYs ROOT";39 if (/all\s*colou?rs\s*mix/.test(productName)) return n + " DaYs All Colours Mix";40 if (/\bbasic\b/.test(productName)) return n + " DaYs Basic";41 if (/\bpro\b/.test(productName)) return n + " DaYs PRO";42 if (/\bsafe\b/.test(productName)) return n + " DaYs SAFE";43 if (/\bbrutal\b/.test(productName)) return n + " DaYs BRUTAL";44 if (/\bbrutal\b/.test(productName)) return n + " DaYs";45 46 // Hours/minutes are preserved exactly; no existing API duration is removed.47 var gh = raw.match(/^([0-9]+(?:\.[0-9]+)?)\s*(hour|hours)$/i);48 if (gh) return gh[1] + " Hours";49 var gm = raw.match(/^([0-9]+(?:\.[0-9]+)?)\s*(minute|minutes)$/i);50 if (gm) return gm[1] + (Number(gm[1]) === 1 ? " Minute" : " Minutes");51 52 return raw || n + " Days";53}54 55 56try {57 var userId = user.telegramid;58 59 // ✅ CRITICAL FIX: Proper atomic duplicate-payment prevention60 var utrFromContent = null;61 62 // Parse content to get UTR early63 if (content) {64 var res = (typeof content === "object") ? content : JSON.parse(content);65 if (res && res.data && res.data.utr) {66 utrFromContent = res.data.utr;67 }68 }69 70 // 🛑 STEP 1: Check if payment already processed using UTR (most reliable identifier)71 if (utrFromContent && Bot.getProperty("paid_" + utrFromContent)) {72 // ✅ FIX: Vanish the QR completely instead of leaving a stale "already used" caption behind73 try {74 Api.deleteMessage({ chat_id: chat.chatid, message_id: request.message.message_id });75 } catch (e) {}76 77 try {78 Bot.setProperty("buy_qr_msg_id_" + userId, null, "string");79 User.setProperty("buy_qr_msg_id_" + userId, null, "string");80 } catch (e) {}81 82 if (request && request.id) {83 try {84 Api.answerCallbackQuery({85 callback_query_id: String(request.id),86 text: "✅ ALREADY CLAIMED ✅\nYe order pehle hi deliver ho chuka hai.",87 show_alert: true88 });89 } catch (e) {}90 }91 92 Api.sendMessage({93 chat_id: chat.chatid,94 text: "<blockquote><tg-emoji emoji-id='5330237710655306682'>✅</tg-emoji> <b>ORDER ALREADY CLAIMED</b>\n<i>Ye payment pehle hi verify ho kar item deliver ho chuka hai. Apni keys 'All History' me check karein.</i></blockquote>",95 parse_mode: "HTML",96 reply_markup: JSON.stringify({97 inline_keyboard: [[98 { text: "📜 My Keys", callback_data: "/mykey", style: "primary" },99 { text: "🛒 Shop Menu", callback_data: "/buy_hack", style: "success" }100 ]]101 })102 });103 return;104 }105 106 // 🛑 STEP 2: Duplicate-click lock check107 var isChecking = User.getProperty("buy_verifying_lock_" + userId);108 if (isChecking) {109 if (request && request.id) {110 Api.answerCallbackQuery({111 callback_query_id: String(request.id),112 text: "⏳ ALREADY CHECKING — PLEASE WAIT...",113 show_alert: true114 });115 }116 return;117 }118 119 // 🛑 STEP 3: SET LOCK IMMEDIATELY before any async operations120 User.setProperty("buy_verifying_lock_" + userId, true, "boolean");121 122 if (!content) {123 Api.editMessageCaption({124 chat_id: chat.chatid, message_id: request.message.message_id,125 caption: "<blockquote>⚠️ <b>Server didn't respond.</b>\nClick 'I have paid' again.</blockquote>", parse_mode: "HTML"126 });127 User.setProperty("buy_verifying_lock_" + userId, false, "boolean");128 return;129 }130 131 var res = (typeof content === "object") ? content : JSON.parse(content);132 133 if (res.status === "success" && res.data) {134 var utr = res.data.utr;135 var isPaid = Bot.getProperty("paid_" + utr);136 137 if (isPaid) {138 // ✅ FIX: Vanish the QR completely instead of leaving a stale "already used" caption behind139 try {140 Api.deleteMessage({ chat_id: chat.chatid, message_id: request.message.message_id });141 } catch (e) {}142 143 try {144 Bot.setProperty("buy_qr_msg_id_" + userId, null, "string");145 User.setProperty("buy_qr_msg_id_" + userId, null, "string");146 } catch (e) {}147 148 if (request && request.id) {149 try {150 Api.answerCallbackQuery({151 callback_query_id: String(request.id),152 text: "✅ ALREADY CLAIMED ✅\nYe order pehle hi deliver ho chuka hai.",153 show_alert: true154 });155 } catch (e) {}156 }157 158 Api.sendMessage({159 chat_id: chat.chatid,160 text: "<blockquote><tg-emoji emoji-id='5330237710655306682'>✅</tg-emoji> <b>ORDER ALREADY CLAIMED</b>\n<i>Ye payment pehle hi verify ho kar item deliver ho chuka hai. Apni keys 'All History' me check karein.</i></blockquote>",161 parse_mode: "HTML",162 reply_markup: JSON.stringify({163 inline_keyboard: [[164 { text: "📜 My Keys", callback_data: "/mykey", style: "primary" },165 { text: "🛒 Shop Menu", callback_data: "/buy_hack", style: "success" }166 ]]167 })168 });169 User.setProperty("buy_verifying_lock_" + userId, false, "boolean");170 return;171 }172 173 // ✅ IMMEDIATELY mark as paid BEFORE any async API calls to prevent race condition174 Bot.setProperty("paid_" + utr, true, "boolean");175 176 Api.editMessageCaption({177 chat_id: chat.chatid, message_id: request.message.message_id,178 caption: "<tg-emoji emoji-id='6192822213486321961'>🔄</tg-emoji> <b>Payment verified! Delivering your key...</b>",179 parse_mode: "HTML"180 });181 182 // ✅ FIX: Detect which purchase pipeline this QR payment belongs to.183 // "ffid" = local stock-based FF ID item (set by /execute_id_buy on low balance)184 // default/"plan" = original plan-based product via external xyzcheats API185 var flowType = User.getProperty("buy_flow_type") || "plan";186 187 if (flowType === "ffid") {188 // =========================================================189 // 🎮 FF ID STOCK DELIVERY (after successful QR payment)190 // =========================================================191 try {192 var rawType = User.getProperty("buy_ffid_rawtype") || "";193 var isResellerFlow = User.getProperty("buy_ffid_is_reseller") === true;194 var finalCost = Number(User.getProperty("buy_price") || 0);195 var displayTypeName = User.getProperty("buy_prod_name") || rawType;196 197 var stockData = [];198 var isDynamicCategory = false;199 var isGeneralCategory = false;200 var selectedCat = null;201 202 var fbCategories = Bot.getProperty("fb_categories") || [];203 if (!Array.isArray(fbCategories)) { fbCategories = []; }204 205 if (rawType.indexOf("fb_") === 0) {206 isDynamicCategory = true;207 var targetCatId = rawType.replace("fb_", "").trim();208 for (var i = 0; i < fbCategories.length; i++) {209 if (fbCategories[i].id === targetCatId) { selectedCat = fbCategories[i]; break; }210 }211 if (selectedCat) { stockData = selectedCat.stock_list || []; }212 } else if (rawType === "fb" || rawType === "google") {213 stockData = Bot.getProperty("ff_stock_" + rawType) || [];214 } else {215 isGeneralCategory = true;216 var categoriesFF = Bot.getProperty("ff_categories") || {};217 selectedCat = categoriesFF[rawType];218 if (selectedCat) {219 var fallbackStock = Bot.getProperty("ff_stock_" + rawType) || [];220 stockData = (selectedCat.stock_list && selectedCat.stock_list.length > 0) ? selectedCat.stock_list : fallbackStock;221 }222 }223 224 if (!stockData || stockData.length === 0) {225 Api.editMessageCaption({226 chat_id: chat.chatid, message_id: request.message.message_id,227 caption: "⚠️ Payment received but item went out of stock. Contact admin with UTR: " + utr,228 parse_mode: "HTML"229 });230 User.setProperty("buy_verifying_lock_" + userId, false, "boolean");231 return;232 }233 234 var accountExtracted = stockData.shift();235 236 if (isDynamicCategory && selectedCat) {237 selectedCat.stock_list = stockData;238 Bot.setProperty("fb_categories", fbCategories, "json");239 } else if (isGeneralCategory && selectedCat) {240 selectedCat.stock_list = stockData;241 var categoriesFF2 = Bot.getProperty("ff_categories") || {};242 categoriesFF2[rawType] = selectedCat;243 Bot.setProperty("ff_categories", categoriesFF2, "json");244 Bot.setProperty("ff_stock_" + rawType, stockData, "json");245 } else {246 Bot.setProperty("ff_stock_" + rawType, stockData, "json");247 }248 249 var fullRawString = String(accountExtracted || "").trim();250 var emailData = fullRawString;251 var passwordData = "No Password Found";252 253 if (fullRawString.indexOf("|") !== -1) {254 var lastPipeIndex = fullRawString.lastIndexOf("|");255 var firstPart = fullRawString.substring(0, lastPipeIndex).trim();256 var secondPart = fullRawString.substring(lastPipeIndex + 1).trim();257 258 if (firstPart.indexOf(" ") !== -1) {259 var spaceParts = firstPart.split(" ");260 emailData = spaceParts[spaceParts.length - 1].trim();261 } else {262 emailData = firstPart;263 }264 passwordData = secondPart;265 }266 267 var purchasedKeys = User.getProperty("my_purchased_keys") || [];268 if (!Array.isArray(purchasedKeys)) { purchasedKeys = []; }269 var currentDate = new Date().toLocaleDateString('en-IN', { timeZone: "Asia/Kolkata" });270 purchasedKeys.push({271 productName: displayTypeName,272 cost: finalCost.toString(),273 key: emailData + (passwordData !== "No Password Found" ? " | " + passwordData : ""),274 days: "Permanent",275 date: currentDate276 });277 User.setProperty("my_purchased_keys", purchasedKeys, "json");278 279 var deliveryText =280 "┏━━━━━━━━━━━━━━━━━━━━━━━━┓\n" +281 "┃ ❤️🔥 <b>PURCHASE SUCCESSFUL!</b> ❤️🔥 ┃\n" +282 "┗━━━━━━━━━━━━━━━━━━━━━━━━┛\n\n" +283 "📦 <b>Item:</b> <code>" + displayTypeName + "</code>\n" +284 "💰 <b>Paid:</b> <code>₹" + finalCost + "</code> " + (isResellerFlow ? "<b>(Reseller)</b>" : "") + "\n" +285 "━━━━━━━━━━━━━━━━━━━━━━━━━━\n" +286 "👤 <b>ACCOUNT DETAILS:</b>\n\n" +287 "🚀 <b>Email:</b> <code>" + emailData + "</code>\n" +288 "🔒 <b>Password:</b> <code>" + passwordData + "</code>\n" +289 "━━━━━━━━━━━━━━━━━━━━━━━━━━\n" +290 "⚠️ <i>Copy details instantly.</i>";291 292 Api.sendMessage({293 chat_id: chat.chatid,294 text: deliveryText,295 parse_mode: "HTML"296 });297 298 var adminLogChannel = "5191323229";299 var adminNotificationMsg =300 "<blockquote>⚠️ <b>NEW ORDER ALERT (QR)</b>" + (isResellerFlow ? " [RESELLER]" : "") + "</blockquote>\n" +301 "👤 <b>User:</b> <a href='tg://user?id=" + userId + "'>" + user.first_name + "</a> (<code>" + userId + "</code>)\n" +302 "📦 <b>Item:</b> <code>" + displayTypeName + "</code>\n" +303 "💰 <b>Revenue:</b> <code>₹" + finalCost + "</code>\n" +304 "⚡ <b>Stock Left:</b> <code>" + stockData.length + " units</code>\n\n" +305 "🖥 <b>ACCOUNT DETAILS:</b>\n" +306 "➔ <b>Email:</b> <code>" + emailData + "</code>\n" +307 "➔ <b>Password:</b> <code>" + passwordData + "</code>";308 309 Api.sendMessage({310 chat_id: adminLogChannel,311 text: adminNotificationMsg,312 parse_mode: "HTML"313 });314 315 // Cleanup all buy_ state for this order316 User.setProperty("buy_flow_type", null, "string");317 User.setProperty("buy_ffid_rawtype", null, "string");318 User.setProperty("buy_ffid_is_reseller", null, "boolean");319 User.setProperty("buy_price", null, "number");320 User.setProperty("buy_needpay", null, "number");321 User.setProperty("buy_prod_name", null, "string");322 User.setProperty("buy_plan_unit", null, "string");323 User.setProperty("buy_plan_name_on_website", null, "string");324 User.setProperty("buy_pending_order_id", null);325 Bot.setProperty("buy_qr_msg_id_" + userId, null, "string");326 User.setProperty("buy_qr_msg_id_" + userId, null, "string");327 Bot.setProperty("buy_qr_caption_" + userId, null, "string");328 User.setProperty("buy_qr_caption_" + userId, null, "string");329 Bot.setProperty("buy_qr_buttons_" + userId, null, "string");330 User.setProperty("buy_qr_buttons_" + userId, null, "string");331 332 } catch (ffErr) {333 Api.editMessageCaption({334 chat_id: chat.chatid, message_id: request.message.message_id,335 caption: "⚠️ Delivery error. Contact admin with UTR: " + utr + " | Error: " + ffErr.message,336 parse_mode: "HTML"337 });338 }339 User.setProperty("buy_verifying_lock_" + userId, false, "boolean");340 return;341 }342 343 // =========================================================344 // 📦 ORIGINAL PLAN-BASED DELIVERY (external xyzcheats API)345 // =========================================================346 var prodIdx = User.getProperty("buy_prod_idx");347 var planIdx = User.getProperty("buy_plan_idx");348 var productList = Bot.getProperty("stored_products") || [];349 var product = productList[prodIdx];350 var plan = product && product.plans ? product.plans[planIdx] : null;351 352 if (!product || !plan) {353 Api.editMessageCaption({354 chat_id: chat.chatid, message_id: request.message.message_id,355 caption: "⚠️ Payment received but product data missing. Contact admin with UTR: " + utr,356 parse_mode: "HTML"357 });358 User.setProperty("buy_verifying_lock_" + userId, false, "boolean");359 return;360 }361 362 var webProductId = String(product.id || "PID_ID").trim();363 var cleanPlanDays = User.getProperty("buy_plan_days") || String(plan.days);364 var planUnit = User.getProperty("buy_plan_unit") || plan.unit || "day";365 var prodNameLower = String(product.name).toLowerCase();366 var durationParam = resolveApiDuration(plan, cleanPlanDays, planUnit, product && product.name);367 368 // 🔌 Use configured multi-API system instead of a hardcoded API.369 var apiRegistry = Bot.getProperty("api_registry") || {};370 var activeApiId = Bot.getProperty("active_reseller_api") || "";371 var selectedApi = activeApiId ? apiRegistry[activeApiId] : null;372 if (!selectedApi) {373 selectedApi = { id:"default", url:"https://adminpanels.shop/api/reseller_v1.php", api_key:"9cd415688a9b01920994099cba20180c", master_key:"a7f3e8b2c9d1f4a6b8c2d5e9f1a3b6c8", android_required:false, enabled:true };374 }375 if (selectedApi.enabled === false) {376 Bot.sendMessage("❌ Selected API is disabled. Admin ko /apiset se active API select karna hoga.");377 return;378 }379 var postFields = { api_key:selectedApi.api_key || "", action:"buy", product_id:webProductId, duration:durationParam };380 var savedAndroidId = User.getProperty("android_id") || User.getProperty("android_id_" + userId) || Bot.getProperty("android_id_" + userId) || "";381 if (selectedApi.android_required && !savedAndroidId) {382 Bot.sendMessage("⚠️ Android ID required for this API/product.");383 return;384 }385 if (savedAndroidId) postFields.android_id = String(savedAndroidId);386 var postFieldsString = Object.keys(postFields).map(function(k){ return encodeURIComponent(k) + "=" + encodeURIComponent(postFields[k]); }).join("&");387 User.setProperty("last_pending_api_id", String(selectedApi.id || activeApiId || ""), "string");388 389 User.setProperty("last_pending_price", User.getProperty("buy_price"), "number");390 User.setProperty("last_pending_prod_id", webProductId, "string");391 User.setProperty("last_pending_prod_name", String(product.name).trim(), "string");392 User.setProperty("last_pending_plan_days", cleanPlanDays, "string");393 User.setProperty("last_pending_plan_unit", planUnit, "string");394 395 HTTP.post({396 url: selectedApi.url,397 body: postFieldsString,398 headers: (function(){ var h={"Content-Type":"application/x-www-form-urlencoded"}; if(selectedApi.master_key) h["x-master-key"]=selectedApi.master_key; return h; })(),399 success: "/onWebKeyReceive",400 error: "/onWebKeyError"401 });402 403 User.setProperty("buy_pending_order_id", null);404 User.setProperty("buy_prod_idx", null);405 User.setProperty("buy_plan_idx", null);406 Bot.setProperty("buy_qr_msg_id_" + userId, null, "string");407 User.setProperty("buy_qr_msg_id_" + userId, null, "string");408 Bot.setProperty("buy_qr_caption_" + userId, null, "string");409 User.setProperty("buy_qr_caption_" + userId, null, "string");410 Bot.setProperty("buy_qr_buttons_" + userId, null, "string");411 User.setProperty("buy_qr_buttons_" + userId, null, "string");412 413 User.setProperty("buy_verifying_lock_" + userId, false, "boolean");414 415 } else {416 // ❌ Payment not found — restore original QR caption/buttons, then show dismissible notice417 try {418 var origCaption = Bot.getProperty("buy_qr_caption_" + userId) || User.getProperty("buy_qr_caption_" + userId);419 var origButtons = Bot.getProperty("buy_qr_buttons_" + userId) || User.getProperty("buy_qr_buttons_" + userId);420 421 if (origCaption) {422 Api.editMessageCaption({423 chat_id: chat.chatid,424 message_id: request.message.message_id,425 caption: origCaption,426 parse_mode: "HTML",427 reply_markup: origButtons ? origButtons : undefined428 });429 }430 } catch (e) {}431 432 if (request && request.id) {433 Api.answerCallbackQuery({434 callback_query_id: String(request.id),435 text: "❌ PAYMENT NOT FOUND ❌\nPlease complete the payment first, then tap again.",436 show_alert: true437 });438 }439 User.setProperty("buy_verifying_lock_" + userId, false, "boolean");440 }441 442} catch (err) {443 try {444 User.setProperty("buy_verifying_lock_" + user.telegramid, false, "boolean");445 } catch (e) {}446 Bot.sendMessage("⚠️ <b>Verification Exception:</b> " + err.message, { parse_mode: "HTML" });447}