Files
waima_req/歪马送酒_商品券列表.py

318 lines
12 KiB
Python
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
import json
import requests
import newsetting as ten
from urllib.parse import urlencode
# 远端 mtgsig 签名服务(同 8月/海底捞 里那套)
SIGN_URL = 'http://129.211.12.35:18003/minipro_mt_0206'
SIGN_TOKEN = 'test_sdfio23923ojbedfojgbouqgew4r32dds'
# 歪马抓包库: 模板包从这张表里取 is_ok 为 null 的行
tent = ten.All_Setting(host='192.168.5.5', port=3306, db='headers_project')
HEADERS_TABLE = 'waima_coupon_list_headers'
# 任务库: 店铺任务从这张表按店铺去重, 券列表 response 也写回这个库
tent_coupon = ten.All_Setting(host='192.168.5.5', port=3306, db='project_waima')
TASK_TABLE = 'waima_keyword_input'
RESULT_TABLE = 'waima_coupon_list'
ITEM_TABLE = 'waima_coupon_list_item' # 拆字段后的券明细表
# 代理库: 按任务城市取代理, 没有对应城市代理的任务跳过不跑
tent_proxy = ten.All_Setting(host='192.168.5.5', port=3306, db='project_proxy')
PROXY_TABLE = 'proxs_list'
# 任务表 city -> 首页城市ID(市级行政区划代码: 取 adcode 前 4 位 + 00)
CITY_ID = {
'北京市': '110100',
'上海市': '310100',
'广州市': '440100',
'深圳市': '440300',
'厦门市': '350200',
'成都市': '510100',
}
# 任务城市没有对应代理时, 退到该省省会的代理(只换出口IP, 任务城市/坐标头不变)
CITY_CAPITAL = {
'北京市': '北京',
'上海市': '上海',
'广州市': '广州',
'深圳市': '广州',
'厦门市': '福州',
'成都市': '成都',
}
BATCH = '2026-12-03'
WM_POI_ID = -100 # 店铺数字 id(抓包商品页请求里就是 -100)
SORT = [] # app 首次打开券弹窗传的是空数组
MAX_NUM = 500 # 单个包最多请求次数(跟 run_pro3 一样按 current_count 卡)
REQ_TIMEOUT = 5 # 单条 https 请求等待秒数
CATEGORY_NAME = {6: '通用券', 7: '商品券'} # couponCategoryType
def get_sign_new1(url, data, dfpid, mtg_origin, open_id, method='POST'):
"""调远端服务动态生成 mtgsig"""
headers = {"content-type": "application/json", "token": SIGN_TOKEN}
body = {
"mtg_origin": mtg_origin,
"url": url,
"data": data,
"dfpid": dfpid,
"method": method,
"open_id": open_id, # 微信的open_id
}
req = requests.post(SIGN_URL, headers=headers, json=body,
proxies={'http': None, 'https': None}, verify=False).text
print('签名结果:', req[:100])
return req
def req_https(url, body, template, proxy):
"""发一条 https 请求并返回响应; body 是 dict, proxy 是对应城市的代理"""
header = dict(template['headers'])
# Host / Content-Length / Connection 交给 requests 自己算, 留着 body 一变长度就对不上
header.pop('Host', None)
header.pop('Content-Length', None)
header.pop('Connection', None)
mtg_origin = json.loads(header['mtgsig'])
dfpid = mtg_origin['a3']
# 必须是紧凑 JSON, 与签名的字节串完全一致
data_str = json.dumps(body, ensure_ascii=False, separators=(',', ':'))
if 'openid' in header:
openId = header['openid']
else:
openId = header['openId']
header['mtgsig'] = get_sign_new1(url, data_str, dfpid, mtg_origin, openId,'POST')
return requests.post(url, headers=header, data=data_str.encode('utf-8'),
timeout=REQ_TIMEOUT, proxies=proxy)
def get_proxs():
"""取城市代理, 返回 {city: prox_data}"""
sql = f'''
select city, prox_data from {PROXY_TABLE}
'''
rows = tent_proxy.get_shoppingmalls(sql)
proxs = {}
for row in rows:
city, prox_data = row
if type(prox_data) == str:
prox_data = json.loads(prox_data)
proxs[city] = prox_data
print('城市代理 %d 条' % len(proxs))
return proxs
def get_city_proxy(city, proxs):
"""按城市取代理; 任务表是'深圳市', 代理表是'深圳', 先精确再互相包含; 都没有就退省会"""
proxy_config = proxs.get(city)
if bool(proxy_config):
return proxy_config
for pro_city, prox_data in proxs.items():
if pro_city in city or city in pro_city:
return prox_data
capital = CITY_CAPITAL.get(city)
if capital:
prox_data = proxs.get(capital)
if bool(prox_data):
print(' %s 没有对应城市代理, 改用省会 %s 代理' % (city, capital))
return prox_data
return None
def set_task_loc_headers(header, city, latitude, longitude):
"""按任务城市/坐标覆盖模板包里的 homePage* 头; 包里 camelCase 和全小写两种写法都有"""
values = {
'homepagecityid': CITY_ID[city],
'homepagelatitude': latitude,
'homepagelongitude': longitude,
}
for key in list(header):
if key.lower() in values:
header[key] = values[key.lower()]
def get_header_rows():
"""取未处理的模板包(id / json_data / current_count)"""
sql = f'''
select id, json_data, current_count from {HEADERS_TABLE} where is_ok is null and current_count < {MAX_NUM}
'''
rows = tent.get_shoppingmalls(sql)
print('未处理模板包 %d 条' % len(rows))
return rows
def update_req_count(row_id):
sql = f'''
update {HEADERS_TABLE} set req_count=req_count+1,current_count=current_count+1 where id='{row_id}'
'''
tent.update_data(sql)
def update_is_ok(row_id, is_ok):
sql = f'''
update {HEADERS_TABLE} set is_ok={is_ok} where id='{row_id}'
'''
tent.update_data(sql)
def get_task_rows():
"""从关键词任务表按店铺去重, 一个店铺跑一次券列表; new_store_id 为空的不跑"""
sql = f'''
select distinct batch, store_id, new_store_id, store_name, city, latitude, longitude from {TASK_TABLE} where batch = '{BATCH}' and new_store_id is not null and new_store_id <> ''
'''
rows = tent_coupon.get_shoppingmalls(sql)
print('待跑店铺 %d 个' % len(rows))
return rows
def is_done(batch, store_id):
"""该批次+店铺的券列表是否已经入过库"""
sql = f'''
select id from {RESULT_TABLE} where batch='{batch}' and store_id='{store_id}' limit 1
'''
rows = tent_coupon.get_shoppingmalls(sql)
return len(rows) > 0
def insert_coupon_list(batch, store_id, store_name, rawdata):
"""整个 response 入库"""
sql = f'''
insert into {RESULT_TABLE} (batch, store_id, store_name, rawdata) values (%s,%s,%s,%s)
'''
insert_data = (batch, store_id, store_name, rawdata)
tent_coupon.write_data_one(sql, insert_data)
def clean_coupon_items(data, shop_id, new_shop_id):
"""可用券+可领券拍平成一行一券; shop_id 是原 store_id, new_shop_id 是按坐标召回拿到的 poiIdStr"""
rows = []
for coupon in data['availableCouponInfos'] + data['receivableCouponList']:
item = (
shop_id,
new_shop_id,
str(coupon['couponConfigId']), # 源里可用券是 int, 可领券是 str, 统一转串
coupon['channelType'],
coupon['channelConfigId'],
coupon['couponName'],
coupon['couponTypeDoc'],
coupon['couponCategoryType'],
coupon['couponPrice'],
coupon['reduceDoc'],
coupon['limitPriceText'],
coupon['couponConditionText'],
coupon['useDoc'],
json.dumps(coupon['couponUseRules'], ensure_ascii=False),
coupon['tabId'],
)
rows.append(item)
return rows
def insert_coupon_items(rows):
sql = f'''
insert into {ITEM_TABLE} (shop_id,new_shop_id,couponConfigId,channelType,channelConfigId,couponName,couponTypeDoc,couponCategoryType,couponPrice,reduceDoc,limitPriceText,couponConditionText,useDoc,couponUseRules,tabId) values (%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s)
'''
tent_coupon.write_data(sql, rows)
def show_coupon_list(data):
"""打印响应里的券列表概要"""
available = data['availableCouponInfos']
goods_list = [c for c in available if c['couponCategoryType'] == 7]
common_list = [c for c in available if c['couponCategoryType'] == 6]
print('可用券 %d 张(商品券 %d, 通用券 %d), 可领券 %d 张, tab %s' % (
len(available), len(goods_list), len(common_list),
len(data['receivableCouponList']), data['tabList']))
for c in available:
print(' [%s] %s | 面额%s %s | configId=%s | viewId=%s | tabId=%s | 状态%s%s' % (
CATEGORY_NAME.get(c['couponCategoryType'], c['couponCategoryType']),
c['couponName'], c['couponPrice'], c['couponConditionText'],
c['couponConfigId'], c['couponViewId'], c['tabId'],
c['couponStatus'], c['availableStatus']))
return goods_list
def run_coupon_list():
header_rows = get_header_rows()
if not header_rows:
print('没有可用的模板包')
return
task_queue = list(get_task_rows()) # pymysql fetchall 是 tuple, 转 list 才能 pop/append
proxs = get_proxs()
attempt_index = 0
while task_queue:
task_row = task_queue.pop(0)
batch, store_id, new_store_id, store_name, city, latitude, longitude = task_row
proxy = get_city_proxy(city, proxs)
if not proxy:
print('没有对应城市代理, 跳过店铺=%s(%s) 城市=%s' % (store_name, store_id, city))
continue
# 任务表存的是十进制度, homePage* 头要 ×1e6 的整数(如 23.129433 -> 23129433)
latitude = str(int(round(float(latitude) * 1000000)))
longitude = str(int(round(float(longitude) * 1000000)))
if is_done(batch, store_id):
print('=== 批次=%s 店铺=%s(%s) 已有券列表, 跳过 ===' % (batch, store_name, store_id))
continue
header_id, json_data, current_count = header_rows[attempt_index % len(header_rows)]
attempt_index += 1
template = json.loads(json_data)
set_task_loc_headers(template['headers'], city, latitude, longitude)
print('=== 任务 批次=%s 店铺=%s(store_id=%s new_store_id=%s) 模板包 id=%s current_count=%s ===' % (
batch, store_name, store_id, new_store_id, header_id, current_count))
# app 的 poi-transform 拦截器会把 body 里的 wmPoiId 换成店铺数字 id 并补上 poiIdStr, 这里按抓包里那份的值来
body = {
'sort': SORT,
'wmPoiId': WM_POI_ID,
'poiIdStr': new_store_id, # 店铺 poiIdStr 取任务表的 new_store_id(按坐标召回的), 不写死
}
print('请求体:', json.dumps(body, ensure_ascii=False, separators=(',', ':')))
resp = req_https(template['url'], body, template, proxy)
print(' status', resp.status_code)
if '您还没有登录,请先登录' in resp.text:
print(' 账号未登录, 标记 is_ok=406')
update_is_ok(header_id, 406)
continue
if resp.status_code != 200:
print(' 响应头:', resp.headers)
print(' 响应体:', resp.text[:500])
update_is_ok(header_id, resp.status_code)
continue
inner = resp.json()
if inner['code'] == 0 and not inner['data']['availableCouponInfos'] and not inner['data']['receivableCouponList'] and not inner['data']['unavailableCouponInfos']:
print(' 可用券/可领券/不可用券都为空, 判定包已失效, 标记 is_ok=403, 任务放回池子换包重跑')
update_is_ok(header_id, 403)
header_rows = [row for row in header_rows if row[0] != header_id]
if not header_rows:
print(' 没有可用的模板包, 退出')
return
task_queue.append(task_row)
continue
update_req_count(header_id)
insert_coupon_list(batch, store_id, store_name, resp.text)
print(' 入库: 批次=%s 店铺=%s(%s)' % (batch, store_name, store_id))
if inner['code'] != 0:
print(' 接口返回异常:', inner['code'], inner['msg'])
continue
goods_list = show_coupon_list(inner['data'])
print('商品券 %d 张' % len(goods_list))
item_rows = clean_coupon_items(inner['data'], store_id, new_store_id)
insert_coupon_items(item_rows)
print(' 清洗入库: %d 条券明细' % len(item_rows))
if __name__ == '__main__':
run_coupon_list()