indrajitghosh20006/Igstore_01botPublic Β· Bot Template

ProfileTelegram

AIThe bot provides an admin interface for a digital store, allowing the owner or co‑admins to add balances, products, plans, and categories. It supports payment workflows via UPI and Binance Pay, automatically generating QR codes and handling manual approval of deposits. The code patches inline keyboards to use premium emoji icons and includes helper functions for user and bot properties. Overall, it serves as a commerce management tool for a Telegram-based storefront.

Commercestoreadminbalanceproductplancategory
170 commands0 envUpdated 8h agoCreated Oct 30, 2026
Back to folder

commands/_onSuccessfulPayment.js

javascript Β· 217 lines

Raw
1/**#command2name: /onSuccessfulPayment3answer: 4keyboard: 5parse_mode: markdown6aliases: 7allow_only_group: false8need_reply: false9is_web: 010#command**/11 12// PREMIUM BUTTON ICONS13(function(){14  try {15    if (!JSON.__premiumPatched) {16      var __origStringify = JSON.stringify;17      JSON.stringify = function(value, replacer, space) {18        try {19          if (value && value.inline_keyboard && Array.isArray(value.inline_keyboard)) {20            var premiumIds = [21              "6143444134125379822",22              "6091379307907652768",23              "6147534454819661264",24              "6147817325660741985",25              "6235683689292897318",26              "6102856637343600044"27            ];28            var rows = value.inline_keyboard.map(function(row, ri) {29              if (!Array.isArray(row)) return row;30              return row.map(function(btn, bi) {31                if (!btn || typeof btn !== "object") return btn;32                var copy = {};33                for (var k in btn) copy[k] = btn[k];34                if (!copy.icon_custom_emoji_id) copy.icon_custom_emoji_id = premiumIds[(ri + bi) % premiumIds.length];35                return copy;36              });37            });38            var cloned = {};39            for (var key in value) cloned[key] = value[key];40            cloned.inline_keyboard = rows;41            return __origStringify.call(JSON, cloned, replacer, space);42          }43        } catch (e) {}44        return __origStringify.call(JSON, value, replacer, space);45      };46      JSON.__premiumPatched = true;47    }48  } catch (e) {}49})();50 51 52 53// =========================================================54// ⭐ Handles Telegram's successful_payment event (Stars payment completed).55// Two payload types:56//   "deposit:<userId>:<amount>"        -> credit Stars wallet balance57//   "buy:<userId>:<prodIdx>:<planIdx>" -> deliver key directly (manual-first, then API)58// ⚠️ PLATFORM NOTE: same routing caveat as _onPreCheckoutQuery.js β€” this is59// also duplicated as a fallback inside _start.js.60// =========================================================61 62try {63  var sp = (request && request.message && request.message.successful_payment)64    ? request.message.successful_payment65    : (request && request.successful_payment ? request.successful_payment : null);66 67  if (!sp) { return; }68 69  var chatId = chat.chatid;70  var payload = sp.invoice_payload || "";71  var starsPaid = Number(sp.total_amount || 0); // XTR amount = Stars count (no decimals)72  var telegramChargeId = sp.telegram_payment_charge_id || "N/A";73 74  var parts = payload.split(":");75  var mode = parts[0];76 77  // πŸ“’ Log every Stars transaction for admin visibility78  function logStarsTransaction(entry) {79    var log = Bot.getProperty("stars_transactions") || [];80    log.push(entry);81    if (log.length > 500) { log = log.slice(log.length - 500); } // keep it bounded82    Bot.setProperty("stars_transactions", log, "json");83  }84 85  if (mode === "deposit") {86    var depUserId = parts[1];87    var depAmount = Number(parts[2]);88 89    var current = Number(Bot.getProperty("stars_balance_" + depUserId) || 0);90    var newBal = current + starsPaid;91    Bot.setProperty("stars_balance_" + depUserId, newBal, "number");92 93    logStarsTransaction({94      type: "deposit",95      userId: depUserId,96      stars: starsPaid,97      chargeId: telegramChargeId,98      date: new Date().toLocaleString()99    });100 101    Api.sendMessage({102      chat_id: chatId,103      text: "<blockquote>⭐ <b>STARS DEPOSIT SUCCESSFUL!</b></blockquote>\n\n" +104            "⭐ <b>Added:</b> " + starsPaid + " Stars\n" +105            "πŸ’« <b>New Stars Balance:</b> " + newBal + "\n" +106            "🧾 <b>Transaction ID:</b> <code>" + telegramChargeId + "</code>\n\n" +107            "<i>Aapke Stars wallet me add ho gaye!</i>",108      parse_mode: "HTML",109      reply_markup: JSON.stringify({ inline_keyboard: [[{ text: "Back to Menu", callback_data: "/back", style: "primary", icon_custom_emoji_id: "5893163582194978381" }]] })110    });111 112    var ownerId = Bot.getProperty("owner_id") || "7839151435";113    try {114      Api.sendMessage({115        chat_id: ownerId,116        text: "<blockquote>⭐ <b>NEW STARS DEPOSIT</b></blockquote>\nπŸ‘€ <b>User:</b> <code>" + depUserId + "</code>\n⭐ <b>Amount:</b> " + starsPaid + " Stars\n🧾 <b>Charge ID:</b> <code>" + telegramChargeId + "</code>",117        parse_mode: "HTML"118      });119    } catch (e) {}120 121  } else if (mode === "buy") {122    var buyUserId = parts[1];123    var prodIdx = Number(parts[2]);124    var planIdx = Number(parts[3]);125 126    var productList = Bot.getProperty("stored_products") || [];127    var product = productList[prodIdx];128    var plan = product ? product.plans[planIdx] : null;129 130    if (!product || !plan) {131      Api.sendMessage({ chat_id: chatId, text: "⚠️ Payment received but product config changed. Contact support with charge ID: " + telegramChargeId, parse_mode: "HTML" });132      return;133    }134 135    var planUnit = plan.unit || "day";136    var cleanPlanDays = String(plan.days).replace(/[^0-9.]/g, "").trim();137    var durationDisplay = plan.durationDisplay || (cleanPlanDays + " " + (planUnit === "hour" ? "Hour(s)" : planUnit === "minute" ? "Minute(s)" : "Day(s)"));138    var cleanProdName = product.name.trim().toUpperCase();139 140    // πŸ”‘ MANUAL STOCK FIRST (same rule as the UPI flow β€” never waste a paid API call if manual stock exists)141    var scopeSuffix = (planUnit === "day") ? cleanPlanDays : (cleanPlanDays + "_" + planUnit);142    var manualKeysStorageKey = "manual_keys_" + cleanProdName + "_" + cleanPlanDays;143    var backupStockKey = "stock_" + product.name.trim() + "_" + cleanPlanDays + "_Day";144    var manualStock = Bot.getProperty(manualKeysStorageKey);145    var isBackupUsed = false;146    if (!manualStock || (Array.isArray(manualStock) && manualStock.length === 0)) {147      manualStock = Bot.getProperty(backupStockKey);148      isBackupUsed = true;149    }150    if (typeof manualStock === "string" && manualStock.trim() !== "") {151      try { manualStock = JSON.parse(manualStock); } catch (e) { manualStock = manualStock.split("\n").map(function (k) { return k.trim(); }).filter(Boolean); }152    }153 154    var generatedKey = null;155    if (Array.isArray(manualStock) && manualStock.length > 0) {156      generatedKey = manualStock.shift();157      if (isBackupUsed) { Bot.setProperty(backupStockKey, manualStock, "json"); }158      else { Bot.setProperty(manualKeysStorageKey, manualStock, "json"); }159    }160 161    logStarsTransaction({162      type: "purchase",163      userId: buyUserId,164      product: product.name,165      plan: durationDisplay,166      stars: starsPaid,167      chargeId: telegramChargeId,168      date: new Date().toLocaleString()169    });170 171    if (generatedKey) {172      // βœ… Manual delivery173      var purchaseHistory = User.getProperty("my_purchased_keys") || [];174      purchaseHistory.push({175        productName: product.name,176        days: durationDisplay,177        key: generatedKey,178        cost: starsPaid + " ⭐",179        date: new Date().toLocaleDateString()180      });181      User.setProperty("my_purchased_keys", purchaseHistory, "json");182 183      Api.sendMessage({184        chat_id: chatId,185        text: "<blockquote>⭐ <b>PAYMENT SUCCESSFUL β€” KEY DELIVERED!</b></blockquote>\n\n" +186              "πŸ“¦ <b>Product:</b> " + product.name + "\n" +187              "⏳ <b>Duration:</b> " + durationDisplay + "\n" +188              "⭐ <b>Paid:</b> " + starsPaid + " Stars\n" +189              "πŸ”‘ <b>Your Key:</b> <code>" + generatedKey + "</code>\n\n" +190              "<i>Enjoy your purchase! πŸŽ‰</i>",191        parse_mode: "HTML",192        reply_markup: JSON.stringify({ inline_keyboard: [[{ text: "πŸ“‹ Copy Key", copy_text: { text: generatedKey } }], [{ text: "Back to Menu", callback_data: "/back", style: "primary", icon_custom_emoji_id: "5893163582194978381" }]] })193      });194    } else {195      // No manual stock β€” flag for admin to deliver via existing API/manual process196      Api.sendMessage({197        chat_id: chatId,198        text: "<blockquote>⭐ <b>PAYMENT RECEIVED!</b></blockquote>\n\n" +199              "<i>Manual stock khaali hai β€” aapki key jald hi deliver ki jaayegi. Agar API-based delivery configured hai, wo bhi automatically try hogi.</i>\n\n" +200              "🧾 <b>Charge ID:</b> <code>" + telegramChargeId + "</code>",201        parse_mode: "HTML"202      });203    }204 205    var ownerId2 = Bot.getProperty("owner_id") || "7839151435";206    try {207      Api.sendMessage({208        chat_id: ownerId2,209        text: "<blockquote>⭐ <b>NEW STARS PURCHASE</b></blockquote>\nπŸ‘€ <b>User:</b> <code>" + buyUserId + "</code>\nπŸ“¦ <b>Product:</b> " + product.name + " (" + durationDisplay + ")\n⭐ <b>Paid:</b> " + starsPaid + " Stars\nπŸ”‘ <b>Delivery:</b> " + (generatedKey ? "Manual Stock βœ…" : "PENDING ⚠️") + "\n🧾 <b>Charge ID:</b> <code>" + telegramChargeId + "</code>",210        parse_mode: "HTML"211      });212    } catch (e) {}213  }214 215} catch (err) {216  try { Bot.sendMessage("⚠️ Successful Payment Handler Error: " + err.message, { parse_mode: "HTML" }); } catch (e2) {}217}