You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用Python Requests实现Shopify带Token的结账机器人?

Shopify结账机器人的技术选型与支付安全方案

核心问题

1. 结账流程实现:requests能否替代浏览器自动化工具?

当前用requests.Session()+BeautifulSoup完成了库存检查、价格核验、加购操作,跳转至结账URL后发现Shopify使用带attemptToken、queueToken、paymentMethodIdentifier的动态GraphQL请求,不确定纯requests能否完成结账,还是必须用Playwright/Selenium这类工具。

2. 支付安全:信用卡信息加密最佳实践

担心机器人填写信用卡信息的安全风险,需要安全可行的加密及提交方案。

现有代码

import requests
from bs4 import BeautifulSoup
from fake_useragent import UserAgent
import time

def getPageSoup(url, session, ua):
    headers = {
        "Accept": "text/html,application/xhtml+xml,afdafdfacpplication/xml;q=0.9,image/avif,"
                  "image/webp,image/apng,*/*;q=0.8,appliccation/signed-exchange;v=b3;q=0.7",
        "User-Agent": ua.random,
        "Referer": "https://randomWebsite.eu/nl/products/pofdkemfdason-scardsdfalet-viofadslet-"
                   "pris zxmatvih-evolutxions-accessvxczory-pouch-collcxzxvectivon",
        "accept-language": "nl-NL,nl;q=0.9,en-US;q=0.8,en;q=0.7",
    }

    r = session.get(url, headers=headers)
    if r.status_code == 200:
        print("entered website")
        return BeautifulSoup(r.text, 'html.parser')
    else:
        print(f"could not enter website, status code:{r.status_code}\n")
        exit(1) #change later

def StockChecker(soup):
    stock_element = soup.find("div", {"class": "label label--out-stock mb-3 mr-3 text-nowrap d-none-important"})

    if stock_element:
        print("In stock")
        return True
    else:
        print("Out of stock")
        return False

def checkPrice(soup, maxPrice):
    price_element = soup.find("div", {"class": "product-page-info__price text-center text-md-left mb-25"})
    price_value = float(price_element.get_text().replace("€", "").replace(",", ".").strip())
    if price_value < maxPrice:
        print(f"price is cheap: {price_value}")
        return True
    else:
        print(f"price is not cheap: {price_value}")
        return False

def addToCart(session, ua):
    addToCartUrl = "https://randomWebsite/nl/cart/add.js"

    headers = {
        "Accept": "*/*",
        "User-Agent": ua.random,
        "Content-Type": "application/json",
        "Referer": "https://randomWebsite/nl/products/pokemon-scarlet-"
                   "vbciob clet-prvsdVismatic-evolbzxcfutiodns-accesbcxz sory-pouch-collectbfzion",
        "Origin": "https://randomWebsite",
        "accept-language": "nl-NL,nl;q=0.9,en-US;q=0.8,en;q=0.7",
        "accept-encoding": "gzip, deflate, br, zstd",
    }

    for quantity in range(5, 0, -1):
        jsonPayload = {
            "id": "10003555974656809",
            "quantity": str(quantity),
        }

        r = session.post(addToCartUrl, json=jsonPayload, headers=headers)
        time.sleep(1)

        print(r.status_code) #remove later
        if r.status_code == 200:
            checkCart = session.get("https://randomWebsite/nl/cart.js")
            cartData = checkCart.json()
            if cartData.get("item_count") > 0:
                print(f"Successfully added {cartData['item_count']} items to cart!")
                return True
            else:
                print(f"failed to add {cartData['item_count']} items")

    print("Failed to add any item at all")
    return False

def goCheckout(session):
    checkoutResponse = session.get("https://randomWebsite/nl/checkout")
    checkoutUrl = checkoutResponse.url
    print(checkoutUrl)

#MAIN PROGRAM:

#variables
url = ("https://randomWebsite/nl/products/pokemon-scarlet-"
       "vivdoletd-prismvsdaatic-evvdsavolutink-accsdvessory-pouvdch-cilecvdstion")
maxPrice = 50.0 #max desired price of product
ua = UserAgent()

#create a session
session = requests.Session()

#retrive parsed webpage in html
soup = getPageSoup(url, session, ua)
time.sleep(1)

#check availability of item
if StockChecker(soup):
    if checkPrice(soup, maxPrice):
        if addToCart(session, ua):
            goCheckout(session)
            print("end of code for now")

解决方案

一、结账流程实现方案

1. 纯requests实现的可能性

理论上可行,但门槛极高:

  • 需抓包解析所有结账阶段的GraphQL请求,明确attemptToken、queueToken等动态参数的来源——这类参数通常嵌入在结账页面的HTML全局变量中,或通过前置API请求返回。
  • 必须严格模拟浏览器的请求顺序、Shopify特定Headers(如X-Shopify-Api-Features、X-Requested-With)及Cookie状态,任何细节出错都会被拦截。
  • 若店铺启用Cloudflare等反爬机制,纯requests极易被识别拦截,需额外处理验证码、UA指纹等问题。

2. 浏览器自动化工具的优势

Playwright/Selenium是更稳妥的选择:

  • 自动处理动态参数生成、请求顺序、Cookie与Session管理,无需手动解析所有GraphQL逻辑。
  • 模拟真实浏览器环境,降低被反爬拦截的概率,遇到验证码时可配合打码工具处理。
  • 开发效率更高,无需花费大量时间逆向Shopify结账API。

二、支付安全最佳实践

绝对不要在机器人代码中明文存储或传输信用卡信息,推荐以下方案:

1. 使用Shopify官方支付API(自有店铺场景)

若机器人为店铺自有工具,可通过Shopify Admin API或Storefront API发起支付,直接调用官方加密通道,无需接触卡密。

2. 委托官方支付页面处理

通过浏览器自动化工具引导至Shopify官方支付页面,由用户手动输入信用卡信息——这是最安全的方式,避免机器人接触敏感数据。

3. 加密传输与存储(仅万不得已时)

  • 传输:必须通过HTTPS提交,Shopify支付接口本身已启用SSL,确保请求URL以https开头。
  • 存储:绝对不要本地存储信用卡信息,若需临时缓存,使用AES-256强加密算法,密钥与代码分离存储(如环境变量、加密密钥管理服务)。
  • 合规:严格遵循PCI DSS支付卡行业数据安全标准,避免违规处理卡密引发法律风险。

内容的提问来源于stack exchange,提问作者Denzel

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.12 17:37:31