vfs_plugin.py 49 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234
  1. # plugins/vfs_global_plugin.py
  2. import time
  3. import json
  4. import random
  5. import base64
  6. import re
  7. import urllib.parse
  8. from datetime import datetime
  9. from typing import Dict, Any, Optional, List, Tuple
  10. from curl_cffi import requests
  11. # 加密库
  12. from cryptography.hazmat.primitives import serialization, hashes
  13. from cryptography.hazmat.primitives.asymmetric import padding
  14. from cryptography.hazmat.backends import default_backend
  15. from vs_plg import IVSPlg
  16. from vs_types import VSPlgConfig, VSQueryResult, VSBookResult, AvailabilityStatus, NotFoundError, PermissionDeniedError, RateLimiteddError, SessionExpiredOrInvalidError, BizLogicError
  17. from vs_log_macros import VSC_INFO, VSC_ERROR, VSC_DEBUG, VSC_WARN
  18. from toolkit.vs_cloud_api import VSCloudApi
  19. from toolkit.rule_engine import RuleEngine
  20. # ----------------- 静态常量与辅助数据 -----------------
  21. VFS_PUBLIC_KEY_PEM = """-----BEGIN PUBLIC KEY-----
  22. MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAuupFgB+lYIOtSxrRoHzc
  23. LmCZKJ6+oSbgqgOPzFMM0TasOeLw0NXEn1XfIzXdx75+tegNKwyIZumoh0yhubKs
  24. t59GV321kN0iquYRHrdh3ygfDDHlS9rROQeBqRga0ncSADtbLMrBPqXJjPCoV76y
  25. t92towriKoH75BhiazY0mghm4LjmAWrV0u/GNpV3tk9bxbtHEXGaFmxCJqjg+7x6
  26. 1e5wXLfvpj9w1QsiSWOSJxLOyICz/9ByxXycQQFdNmjnnnwco9Gt/Mi33NYH71j0
  27. 5oXIjklFC4lvJqaqSY5lS7Vwb9oCt9zX9J0Yz4z4e/3V+0jgRnWOFGofyks4FKe2
  28. GQIDAQAB
  29. -----END PUBLIC KEY-----"""
  30. COUNTRY_MAP = {
  31. "china": "CHN", "france": "FRA", "germany": "DEU", "italy": "ITA",
  32. "united kingdom": "GBR", "united states": "USA", "india": "IND",
  33. "russia": "RUS", "turkey": "TUR", "vietnam": "VNM"
  34. }
  35. def get_country_iso3(name: str) -> str:
  36. return COUNTRY_MAP.get(name.lower(), "CHN")
  37. def get_alias_email(email: str, new_domain: str = "gmail-app.com") -> str:
  38. """
  39. 将邮箱域名替换为指定域名(默认 gmail-app.com)
  40. """
  41. if "@" not in email:
  42. raise ValueError(f"Invalid email: {email}")
  43. local_part, _ = email.rsplit("@", 1)
  44. return f"{local_part}@{new_domain}"
  45. # ----------------- VfsPlugin 类 -----------------
  46. class VfsPlugin(IVSPlg):
  47. def __init__(self, group_id: str):
  48. self.group_id = group_id
  49. self.config: Optional[VSPlgConfig] = None
  50. self.free_config: Dict[str, Any] = {}
  51. self.session = requests.Session()
  52. # 模拟 Chrome 124
  53. self.session.impersonate = "chrome124"
  54. self.jwt_token = ""
  55. self.user_agent = ""
  56. self.real_ip = ""
  57. self.is_healthy = True
  58. # 缓存配置
  59. self.center_conf = None
  60. self.category_conf = {}
  61. self.subcategory_conf = {}
  62. # 加载公钥
  63. self.public_key = serialization.load_pem_public_key(
  64. VFS_PUBLIC_KEY_PEM.encode(),
  65. backend=default_backend()
  66. )
  67. def get_group_id(self) -> str:
  68. return self.group_id
  69. def set_config(self, config: VSPlgConfig):
  70. self.config = config
  71. try:
  72. self.free_config = json.loads(config.free_config) if config.free_config else {}
  73. except:
  74. self.free_config = {}
  75. # 设置代理
  76. if config.proxy.ip:
  77. proxy_str = f"{config.proxy.scheme}://"
  78. if config.proxy.username:
  79. proxy_str += f"{config.proxy.username}:{config.proxy.password}@"
  80. proxy_str += f"{config.proxy.ip}:{config.proxy.port}"
  81. self.session.proxies = {"http": proxy_str, "https": proxy_str}
  82. VSC_DEBUG("vfs_plg", "[%s] Proxy set: %s", self.group_id, config.proxy.ip)
  83. def health_check(self) -> bool:
  84. # 直接利用 VSError 的逻辑
  85. return self.is_healthy
  86. def create_session(self) -> None:
  87. """登录流程"""
  88. VSC_INFO("vfs_plg", "[%s] Starting login...", self.group_id)
  89. # 1. Cloudflare Turnstile
  90. cf_token = self._handle_cloudflare_challenge()
  91. # 2. 准备参数
  92. email = self.config.account.username
  93. password = self.config.account.password
  94. enc_password = self._encrypt_password(password)
  95. mission_code = self.free_config.get("missionCode", "")
  96. country_code = self.free_config.get("countryCode", "")
  97. client_src = self._get_client_source()
  98. orange_src = self._get_orange_source(email)
  99. url = "https://lift-api.vfsglobal.com/user/login"
  100. headers = self._get_common_headers(with_auth=False)
  101. headers.update({
  102. "clientsource": client_src,
  103. "orangex": orange_src,
  104. "content-type": "application/x-www-form-urlencoded"
  105. })
  106. data = {
  107. "username": email,
  108. "password": enc_password,
  109. "missioncode": mission_code,
  110. "countrycode": country_code,
  111. "languageCode": "en-US",
  112. "captcha_version": "cloudflare-v1",
  113. "captcha_api_key": cf_token
  114. }
  115. # 3. 发送登录请求 (包含 OPTIONS)
  116. resp = self._perform_request("POST", url, headers=headers, data=data)
  117. resp_json = resp.json()
  118. if "accessToken" in resp_json and resp_json["accessToken"]:
  119. self.jwt_token = resp_json["accessToken"]
  120. VSC_INFO("vfs_plg", "[%s] Login successful, JWT obtained.", self.group_id)
  121. return
  122. # OTP 处理
  123. if resp_json.get("enableOTPAuthentication"):
  124. VSC_INFO("vfs_plg", "[%s] Login requires OTP.", self.group_id)
  125. otp = self._read_otp_email()
  126. self._submit_login_otp(None, otp)
  127. return
  128. raise BizLogicError(message="Login failed: No access token or OTP flow.")
  129. def query(self) -> VSQueryResult:
  130. """查询可预约 Slot"""
  131. result = VSQueryResult()
  132. appt_types = self.free_config.get("appointmentType", [])
  133. if not appt_types:
  134. raise NotFoundError(message="No matching appointment configuration found.")
  135. apt_config = random.choice(appt_types)
  136. self._fetch_configurations(apt_config)
  137. earliest_date = self._query_earliest_slot(apt_config)
  138. result.success = False
  139. result.visa_type = apt_config.get("subcategoryCode", "")
  140. result.city = apt_config.get("vacCode", "")
  141. result.country = self.free_config.get("countryCode", "")
  142. result.routing_key = apt_config.get("routingKey", "")
  143. if earliest_date:
  144. if "WaitList" in earliest_date:
  145. result.success = True
  146. result.availability_status = AvailabilityStatus.Waitlist
  147. VSC_INFO("vfs_plg", "[%s] Found WaitList.", self.group_id)
  148. else:
  149. result.success = True
  150. result.availability_status = AvailabilityStatus.Available
  151. result.earliest_date = earliest_date
  152. VSC_INFO("vfs_plg", "[%s] Found Slot: %s", self.group_id, earliest_date)
  153. day_info = VSQueryResult.DateAvailability()
  154. day_info.date = earliest_date
  155. result.availability.append(day_info)
  156. return result
  157. def _get_filtered_covered_months(self, start_date, end_date, from_date) -> List[str]:
  158. """
  159. 计算需要查询的月份列表,格式 YYYY-MM-DD (每月1号)
  160. """
  161. fmt = "%Y-%m-%d"
  162. # 默认值处理
  163. try:
  164. dt_start = datetime.strptime(start_date, fmt) if start_date else datetime.now()
  165. dt_end = datetime.strptime(end_date, fmt) if end_date else datetime.now().replace(year=datetime.now().year + 1)
  166. # from_date 格式可能是 DD/MM/YYYY (从 slot_info 来)
  167. try:
  168. dt_from = datetime.strptime(from_date, "%d/%m/%Y")
  169. except:
  170. dt_from = datetime.now()
  171. except:
  172. return []
  173. # 归一化到月初
  174. dt_start = dt_start.replace(day=1)
  175. dt_end = dt_end.replace(day=1)
  176. dt_from = dt_from.replace(day=1)
  177. # 起始点取 max(start, from)
  178. curr = max(dt_start, dt_from)
  179. months = []
  180. while curr <= dt_end:
  181. months.append(curr.strftime(fmt))
  182. # 下个月
  183. if curr.month == 12:
  184. curr = curr.replace(year=curr.year + 1, month=1)
  185. else:
  186. curr = curr.replace(month=curr.month + 1)
  187. return months
  188. def book(self, slot_info: VSQueryResult, user_inputs) -> VSBookResult:
  189. """
  190. 执行完整的预约流程,包含:上传文档 -> 添加申请人 -> OTP -> 选时间 -> 锁定 -> 支付
  191. """
  192. user_email = user_inputs.get('email', 'get_visa_666@example.com')
  193. user_inputs['alias_email'] = get_alias_email(user_email, new_domain="gmail-app.com")
  194. res = VSBookResult()
  195. slot_routing_key = slot_info.routing_key
  196. from_date = slot_info.earliest_date if slot_info.earliest_date else datetime.now().strftime("%d/%m/%Y")
  197. apt_config = None
  198. appt_types = self.free_config.get("appointmentType", [])
  199. for apt in appt_types:
  200. if apt.get("routingKey") == slot_routing_key or len(appt_types) == 1:
  201. apt_config = apt
  202. break
  203. if not apt_config:
  204. raise NotFoundError(message="Book: Config missing.")
  205. self._fetch_configurations(apt_config)
  206. sub_cc = apt_config.get("subcategoryCode")
  207. sub_conf = self.subcategory_conf.get(sub_cc, {})
  208. # OCR 识别 / 文档上传
  209. ocr_enabled = sub_conf.get("isOCREnable", False)
  210. if ocr_enabled:
  211. VSC_INFO("vfs_plg", "[%s] OCR Enabled, uploading documents...", self.group_id)
  212. upload_res = self._upload_applicant_documents(apt_config, user_inputs, upload_res)
  213. user_inputs["applicant_image"] = upload_res.get("passportImageFilename")
  214. user_inputs["applicant_image_data"] = upload_res.get("passportImageFileBytes") # Base64
  215. user_inputs["guid"] = upload_res.get("uploadDocumentGUID")
  216. # 需要提供申请号 (Cover Letter)
  217. enable_reference_number = sub_conf.get("enableReferenceNumber", False)
  218. # 添加申请人 (核心步骤 1)
  219. final_urn = None
  220. is_waitlist = (slot_info.availability_status == AvailabilityStatus.Waitlist)
  221. add_primary_retry = 0
  222. MAX_RETRY = 3
  223. success_add = False
  224. while add_primary_retry < MAX_RETRY:
  225. try:
  226. final_urn = self._add_primary_applicant(apt_config, user_inputs, is_waitlist, ocr_enabled, enable_reference_number)
  227. success_add = True
  228. break
  229. except Exception as e:
  230. VSC_WARN("vfs_plg", "[%s] Add Applicant retry %d...", self.group_id, add_primary_retry)
  231. time.sleep(5)
  232. add_primary_retry += 1
  233. if not success_add:
  234. raise BizLogicError(message="Failed to add primary applicant (Slot likely taken)")
  235. VSC_INFO("vfs_plg", "[%s] Applicant Added. URN: %s", self.group_id, final_urn)
  236. # 申请人 OTP 验证 (核心步骤 2)
  237. otp_enabled = sub_conf.get("isApplicantOTPEnabled", False)
  238. if otp_enabled:
  239. VSC_INFO("vfs_plg", "[%s] Applicant OTP Required.", self.group_id)
  240. if not self._applicant_otp_send(apt_config, final_urn):
  241. raise BizLogicError(message='applicant otp send failed')
  242. # 复用之前的读邮件逻辑
  243. otp_code = self._read_otp_email()
  244. if not self._applicant_otp_verify(apt_config, final_urn, otp_code):
  245. raise BizLogicError(message='applicant otp verify failed')
  246. # 如果是 Waitlist 模式,直接确认并返回
  247. if is_waitlist:
  248. if self._confirm_waitlist(apt_config, final_urn):
  249. res.success = True
  250. res.urn = final_urn
  251. return res
  252. raise BizLogicError(message='confirm waitlist failed')
  253. # 规则引擎与日期筛选 (核心步骤 3)
  254. rules_str = user_inputs.get("rules", "")
  255. rule_engine = RuleEngine(rules_str)
  256. expected_start = user_inputs.get("expected_start_date", "")
  257. expected_end = user_inputs.get("expected_end_date", "")
  258. rule_engine.set_date_range_start(expected_start)
  259. rule_engine.set_date_range_end(expected_end)
  260. # 计算需要扫描的月份, 如果 expected_start/end 为空,默认使用 from_date 所在月
  261. months = self._get_filtered_covered_months(expected_start, expected_end, from_date)
  262. VSC_INFO("vfs_plg", "[%s] Scanning months: %s (From: %s)", self.group_id, months, from_date)
  263. selected_slot_id = ""
  264. selected_slot_date = ""
  265. selected_slot_time_range = ""
  266. # 记录所有有号日期,避免重复处理
  267. all_ads = set()
  268. forbidden_dates = set()
  269. found_slot = False
  270. # 遍历月份寻找 Slot
  271. for m_str in months:
  272. # 需要 DD/MM/YYYY
  273. dt_m = datetime.strptime(m_str, "%Y-%m-%d")
  274. converted_date = dt_m.strftime("%d/%m/%Y")
  275. ads = not self._query_slot_calendar(apt_config, final_urn, converted_date)
  276. # 过滤已知的 slots
  277. new_ads = [d for d in ads if d not in all_ads]
  278. all_ads.update(new_ads)
  279. # 尝试 3 次选择
  280. for _ in range(3):
  281. # 排除 forbidden
  282. avail_candidates = [d for d in list(all_ads) if d not in forbidden_dates]
  283. # 规则筛选
  284. sel_dates = rule_engine.select_date(avail_candidates, "%d/%m/%Y")
  285. if not sel_dates:
  286. break
  287. tmp_date = sel_dates[0]
  288. forbidden_dates.add(tmp_date)
  289. # 审计日志
  290. if not self._saveuseractionaudit(apt_config, final_urn, tmp_date):
  291. time.sleep(3)
  292. continue
  293. # 查询具体时间
  294. ats = self._query_slot_time(apt_config, final_urn, tmp_date)
  295. if not ats:
  296. time.sleep(3)
  297. continue
  298. # 随机选择一个时间段
  299. sel_tm = random.choice(ats)
  300. selected_slot_id = sel_tm.get("allocationId")
  301. selected_slot_date = tmp_date
  302. selected_slot_time_range = sel_tm.get("slot")
  303. found_slot = True
  304. break
  305. if found_slot:
  306. break
  307. if not found_slot:
  308. VSC_INFO("vfs_plg", "[%s] No valid slots found after Rule Engine filtering.", self.group_id)
  309. res.success = False
  310. return res
  311. VSC_INFO("vfs_plg", "[%s] Slot Selected: %s %s (ID: %s)",
  312. self.group_id, selected_slot_date, selected_slot_time_range, selected_slot_id)
  313. # 服务、费用、最终预约 (核心步骤 4)
  314. self._submit_no_addition_service(final_urn)
  315. amount, currency = self._query_fee(apt_config, final_urn)
  316. schedule_res = self._schedule(apt_config, final_urn, amount, currency, selected_slot_id)
  317. if schedule_res.get("IsAppointmentBooked"):
  318. VSC_INFO("vfs_plg", "[%s] IsAppointmentBooked is false", self.group_id)
  319. res.success = False
  320. return res
  321. # 构造返回结果
  322. res.success = True
  323. res.account = self.config.account.username
  324. res.book_date = selected_slot_date
  325. res.book_time = selected_slot_time_range
  326. res.urn = final_urn
  327. res.fee_amount = int(amount * 100)
  328. res.fee_currency = currency
  329. # 处理支付链接
  330. if schedule_res.get("IsPaymentRequired", False):
  331. payload = schedule_res.get("payLoad", "")
  332. payment_url = self._pay_request(payload)
  333. if payment_url:
  334. res.payment_link = payment_url
  335. # 保存 Session
  336. saved_session = self._save_http_session(payment_url)
  337. if saved_session:
  338. res.session_id = saved_session['session_id']
  339. return res
  340. def _confirm_waitlist(self, apt_config: Dict[str, Any], urn: str) -> bool:
  341. """
  342. 确认加入候补名单 (对应 C++ VFSApi::confirm_waitlist)
  343. """
  344. url = "https://lift-api.vfsglobal.com/appointment/ConfirmWaitlist"
  345. headers = self._get_common_headers(with_auth=True)
  346. headers["content-type"] = "application/json;charset=UTF-8"
  347. data = {
  348. "missionCode": self.free_config.get("missionCode"),
  349. "countryCode": self.free_config.get("countryCode"),
  350. "centerCode": apt_config.get("vacCode"),
  351. "loginUser": self.config.account.username,
  352. "urn": urn,
  353. "notificationType": "none",
  354. "CanVFSReachoutToApplicant": True
  355. }
  356. resp = self._perform_request("POST", url, headers=headers, json_data=data)
  357. return resp.json().get("isConfirmed")
  358. def _upload_applicant_documents(self, apt_config, user_inputs) -> Dict:
  359. """上传护照图片"""
  360. url = "https://lift-api.vfsglobal.com/appointment/UploadApplicantDocument"
  361. passport_url = user_inputs.get("passport_image_url")
  362. if not passport_url:
  363. raise NotFoundError(message="Missing passport_image_url")
  364. img_resp = requests.get(passport_url, timeout=30)
  365. if img_resp.status_code != 200:
  366. raise BizLogicError(message="Failed to download passport image")
  367. b64_str = base64.b64encode(img_resp.content).decode('utf-8')
  368. headers = self._get_common_headers(with_auth=True)
  369. headers["content-type"] = "application/json;charset=UTF-8"
  370. data = {
  371. "missioncode": self.free_config.get("missionCode"),
  372. "countryCode": self.free_config.get("countryCode"),
  373. "centerCode": apt_config.get("vacCode"),
  374. "loginUser": self.config.account.username,
  375. "languageCode": "en-US",
  376. "visaCategoryCode": apt_config.get("subcategoryCode"),
  377. "fileBytes": b64_str,
  378. "selfiImageFileBytes": ""
  379. }
  380. result = {}
  381. resp = self._perform_request("POST", url, headers=headers, json_data=data)
  382. j = resp.json()
  383. result.update(j)
  384. result["passportImageFilename"] = "passport_img.jpg"
  385. result["passportImageFileBytes"] = b64_str
  386. return result
  387. def _add_primary_applicant(self, apt_config: Dict[str, Any], user_inputs: Dict[str, Any],
  388. is_waitlist: bool, ocr_enabled: bool, enable_ref: bool) -> str:
  389. """
  390. 构造复杂的申请人 JSON payload 并提交
  391. """
  392. url = "https://lift-api.vfsglobal.com/appointment/applicants"
  393. headers = self._get_common_headers(with_auth=True)
  394. headers["content-type"] = "application/json;charset=UTF-8"
  395. #male/Male -> 1, 否则 -> 2
  396. gender_str = str(user_inputs.get("gender", "")).lower()
  397. gender_code = 1 if gender_str == "male" else 2
  398. raw_dial = user_inputs.get("phone_country_code", "86")
  399. dial_code = str(raw_dial)
  400. # to_ddmmyyyy (YYYY-MM-DD -> DD/MM/YYYY)
  401. def _to_ddmmyyyy(d_str):
  402. try:
  403. # 假设输入是 YYYY-MM-DD
  404. return datetime.strptime(d_str, "%Y-%m-%d").strftime("%d/%m/%Y")
  405. except:
  406. return d_str # 原样返回
  407. dob = _to_ddmmyyyy(str(user_inputs.get("birthday", "")))
  408. ppt_exp = _to_ddmmyyyy(str(user_inputs.get("passport_expiry_date", "")))
  409. # --- 构造单个 Applicant 对象 ---
  410. applicant = {
  411. "urn": "",
  412. "arn": "",
  413. "loginUser": self.config.account.username,
  414. # 基本信息 (全部大写)
  415. "firstName": str(user_inputs.get("first_name", "")).upper(),
  416. "middleName": "",
  417. "lastName": str(user_inputs.get("last_name", "")).upper(),
  418. "employerFirstName": "",
  419. "employerLastName": "",
  420. "salutation": "",
  421. "gender": gender_code,
  422. # 联系信息
  423. "contactNumber": str(user_inputs.get("phone", "")),
  424. "dialCode": dial_code,
  425. "employerContactNumber": "",
  426. "employerDialCode": "",
  427. "emailId": str(user_inputs.get("alias_email", "")).upper(),
  428. "employerEmailId": "",
  429. # 证件信息
  430. "passportNumber": str(user_inputs.get("passport_no", "")).upper(),
  431. "confirmPassportNumber": "",
  432. "passportExpirtyDate": ppt_exp,
  433. "dateOfBirth": dob,
  434. "nationalId": None,
  435. # 国籍 (使用全局辅助函数 get_country_iso3)
  436. "nationalityCode": get_country_iso3(str(user_inputs.get("nationality", ""))),
  437. # 地址与其它 (大部分为空)
  438. "state": None,
  439. "city": None,
  440. "addressline1": None,
  441. "addressline2": None,
  442. "pincode": None,
  443. "isEndorsedChild": False,
  444. "applicantType": 0,
  445. "vlnNumber": None,
  446. "applicantGroupId": 0,
  447. "parentPassportNumber": "",
  448. "parentPassportExpiry": "",
  449. "dateOfDeparture": None,
  450. "entryType": "",
  451. "eoiVisaType": "",
  452. "passportType": "",
  453. "vfsReferenceNumber": "",
  454. "familyReunificationCerificateNumber": "",
  455. "PVRequestRefNumber": "",
  456. "PVStatus": "",
  457. "PVStatusDescription": "",
  458. "PVCanAllowRetry": True,
  459. "PVisVerified": False,
  460. "eefRegistrationNumber": "",
  461. "isAutoRefresh": True,
  462. "helloVerifyNumber": "",
  463. "OfflineCClink": "",
  464. "idenfystatuscheck": False,
  465. "vafStatus": None,
  466. "SpecialAssistance": "",
  467. "AdditionalRefNo": None,
  468. "juridictionCode": "",
  469. "canInitiateVAF": False,
  470. "canEditVAF": False,
  471. "canDeleteVAF": False,
  472. "canDownloadVAF": False,
  473. "Retryleft": "",
  474. # 真实 IP 注入
  475. "ipAddress": self.real_ip or "127.0.0.1"
  476. }
  477. # --- 处理 Reference Number (Cover Letter) ---
  478. if enable_ref:
  479. applicant["referenceNumber"] = str(user_inputs.get("cover_letter", ""))
  480. else:
  481. applicant["referenceNumber"] = None
  482. # --- 处理 OCR 数据 ---
  483. if ocr_enabled:
  484. applicant["applicantImage"] = str(user_inputs.get("applicant_image", ""))
  485. applicant["applicantImageData"] = str(user_inputs.get("applicant_image_data", ""))
  486. applicant["GUID"] = str(user_inputs.get("guid", ""))
  487. # --- 构造最外层 Payload ---
  488. payload = {
  489. "countryCode": self.free_config.get("countryCode"),
  490. "missionCode": self.free_config.get("missionCode"),
  491. "centerCode": apt_config.get("vacCode"),
  492. "loginUser": self.config.account.username,
  493. "visaCategoryCode": apt_config.get("subcategoryCode"),
  494. "applicantList": [applicant], # 数组形式
  495. "languageCode": "en-US",
  496. "isWaitlist": is_waitlist,
  497. "isEdit": False,
  498. "feeEntryTypeCode": None,
  499. "feeExemptionTypeCode": None,
  500. "feeExemptionDetailsCode": None,
  501. "juridictionCode": None,
  502. "regionCode": None
  503. }
  504. # --- 发送请求 ---
  505. resp = self._perform_request("POST", url, headers=headers, json_data=payload)
  506. # --- 处理响应 ---
  507. return resp.json()["urn"]
  508. def _applicant_otp_send(self, apt_config, urn) -> bool:
  509. url = "https://lift-api.vfsglobal.com/appointment/applicantotp"
  510. headers = self._get_common_headers(with_auth=True)
  511. headers["content-type"] = "application/json;charset=UTF-8"
  512. data = {
  513. "urn": urn,
  514. "loginUser": self.config.account.username,
  515. "missionCode": self.free_config.get("missionCode"),
  516. "countryCode": self.free_config.get("countryCode"),
  517. "centerCode": apt_config.get("vacCode"),
  518. "OTP": "",
  519. "otpAction": "GENERATE",
  520. "languageCode": "en-US"
  521. }
  522. resp = self._perform_request("POST", url, headers=headers, json_data=data)
  523. return resp.json().get("isOTPGenerated")
  524. def _applicant_otp_verify(self, apt_config, urn, otp) -> bool:
  525. url = "https://lift-api.vfsglobal.com/appointment/applicantotp"
  526. headers = self._get_common_headers(with_auth=True)
  527. # C++ specific: datacenter header
  528. headers["datacenter"] = "GERMANY"
  529. headers["content-type"] = "application/json;charset=UTF-8"
  530. data = {
  531. "urn": urn,
  532. "loginUser": self.config.account.username,
  533. "missionCode": self.free_config.get("missionCode"),
  534. "countryCode": self.free_config.get("countryCode"),
  535. "centerCode": apt_config.get("vacCode"),
  536. "OTP": otp,
  537. "otpAction": "VALIDATE",
  538. "languageCode": "en-US"
  539. }
  540. resp = self._perform_request("POST", url, headers=headers, json_data=data)
  541. return resp.json().get("isOTPValidated")
  542. def _query_slot_calendar(self, apt_config, urn, from_date) -> List:
  543. url = "https://lift-api.vfsglobal.com/appointment/calendar"
  544. headers = self._get_common_headers(with_auth=True)
  545. headers["content-type"] = "application/json;charset=UTF-8"
  546. data = {
  547. "missionCode": self.free_config.get("missionCode"),
  548. "countryCode": self.free_config.get("countryCode"),
  549. "centerCode": apt_config.get("vacCode"),
  550. "loginUser": self.config.account.username,
  551. "visaCategoryCode": apt_config.get("subcategoryCode"),
  552. "fromDate": from_date,
  553. "urn": urn,
  554. "payCode": ""
  555. }
  556. resp = self._perform_request("POST", url, headers=headers, json_data=data)
  557. calendars = resp.json().get("calendars")
  558. if calendars:
  559. ads_out = []
  560. for item in calendars:
  561. # C++ assumes "MM/DD/YYYY" -> "DD/MM/YYYY"
  562. raw = item.get("date")
  563. # Normalize to DD/MM/YYYY
  564. dObj = datetime.strptime(raw, "%m/%d/%Y")
  565. ads_out.append(dObj.strftime("%d/%m/%Y"))
  566. return ads_out
  567. return []
  568. def _query_slot_time(self, apt_config, urn, slot_date) -> List:
  569. url = "https://lift-api.vfsglobal.com/appointment/timeslot"
  570. headers = self._get_common_headers(with_auth=True)
  571. headers["content-type"] = "application/json;charset=UTF-8"
  572. data = {
  573. "missionCode": self.free_config.get("missionCode"),
  574. "countryCode": self.free_config.get("countryCode"),
  575. "centerCode": apt_config.get("vacCode"),
  576. "loginUser": self.config.account.username,
  577. "visaCategoryCode": apt_config.get("subcategoryCode"),
  578. "slotDate": slot_date,
  579. "urn": urn
  580. }
  581. resp = self._perform_request("POST", url, headers=headers, json_data=data)
  582. return resp.json().get("slots")
  583. def _saveuseractionaudit(self, apt_config, urn, earliest_date) -> bool:
  584. url = "https://lift-api.vfsglobal.com/appointment/saveuseractionaudit"
  585. headers = self._get_common_headers(with_auth=True)
  586. headers["content-type"] = "application/json;charset=UTF-8"
  587. # ISO format conversion
  588. try:
  589. dt = datetime.strptime(earliest_date, "%d/%m/%Y")
  590. iso_date = dt.strftime("%Y-%m-%dT%H:%M:%S")
  591. except:
  592. iso_date = earliest_date
  593. data = {
  594. "missionCode": self.free_config.get("missionCode"),
  595. "countryCode": self.free_config.get("countryCode"),
  596. "centerCode": apt_config.get("vacCode"),
  597. "loginUser": self.config.account.username,
  598. "urn": urn,
  599. "firstEarliestSlotDate": earliest_date,
  600. "action": "schedule",
  601. "ipAddress": self.real_ip or "127.0.0.1",
  602. "eadAppointmentDetail": iso_date
  603. }
  604. resp = self._perform_request("POST", url, headers=headers, json_data=data)
  605. return resp.json().get("isSavedSuccess", False)
  606. def _perform_request(self, method, url, headers=None, data=None, json_data=None, params=None):
  607. """
  608. 统一 HTTP 请求封装,严格复刻 C++ 逻辑:
  609. 1. 发送 OPTIONS 请求
  610. 2. 发送实际请求
  611. """
  612. print(f'[perform request] {method} {url}')
  613. # --- 1. 发送 OPTIONS 请求 ---
  614. try:
  615. # OPTIONS 请求使用相同的 URL 和 headers (部分 header 如 content-length 会被自动处理)
  616. # 某些服务器反爬会检测 OPTIONS 请求
  617. opt_headers = headers.copy() if headers else {}
  618. # 发送 OPTIONS
  619. self.session.request("OPTIONS", url, headers=opt_headers, timeout=10)
  620. # C++ 代码中并不检查 OPTIONS 的返回值,只检查执行是否成功
  621. # 这里我们假设只要不抛出异常即可
  622. except Exception as e:
  623. # 记录警告但不中断流程,防止仅仅是 OPTIONS 失败导致误判
  624. VSC_DEBUG("vfs_plg", "OPTIONS request failed (non-fatal): %s", str(e))
  625. resp = self.session.request(method, url, headers=headers, data=data, json=json_data, params=params, timeout=30)
  626. VSC_INFO('vfs_plg', resp.text)
  627. if resp.status_code == 200:
  628. return resp
  629. elif resp.status_code == 401:
  630. self.is_healthy = False
  631. raise SessionExpiredOrInvalidError()
  632. elif resp.status_code == 403:
  633. raise PermissionDeniedError()
  634. elif resp.status_code == 429:
  635. self.is_healthy = False
  636. raise RateLimiteddError()
  637. else:
  638. raise BizLogicError(message=f"HTTP Error {resp.status_code}: {resp.text[:100]}")
  639. def _encrypt_password(self, password: str) -> str:
  640. ciphertext = self.public_key.encrypt(
  641. password.encode(),
  642. padding.OAEP(
  643. mgf=padding.MGF1(algorithm=hashes.SHA256()),
  644. algorithm=hashes.SHA256(),
  645. label=None
  646. )
  647. )
  648. return base64.b64encode(ciphertext).decode()
  649. def _get_orange_source(self, email: str) -> str:
  650. timestamp = datetime.utcnow().strftime("%Y-%m-%dT%H:%M:%S")
  651. payload = f"{email};{timestamp}"
  652. return self._encrypt_password(payload)
  653. def _get_client_source(self) -> str:
  654. timestamp = datetime.utcnow().strftime("%Y-%m-%dT%H:%M:%S")
  655. payload = f"GA;{timestamp}Z"
  656. return self._encrypt_password(payload)
  657. def _handle_cloudflare_challenge(self) -> str:
  658. """
  659. 完整实现的 Cloudflare Turnstile 验证逻辑
  660. """
  661. mission = self.free_config.get("missionCode", "")
  662. country = self.free_config.get("countryCode", "")
  663. if not mission or not country:
  664. raise NotFoundError(message="Missing missionCode or countryCode in free_config")
  665. website_url = f"https://visa.vfsglobal.com/{country}/en/{mission}/login"
  666. # 构造代理字符串传给打码平台 (格式: http://user:pass@ip:port)
  667. proxy_str = ""
  668. if self.config.proxy.ip:
  669. proxy_str = f"{self.config.proxy.scheme}://"
  670. if self.config.proxy.username:
  671. proxy_str += f"{self.config.proxy.username}:{self.config.proxy.password}@"
  672. proxy_str += f"{self.config.proxy.ip}:{self.config.proxy.port}"
  673. # 2. 提交任务
  674. VSC_INFO("vfs_plg", "[%s] Submitting Turnstile task for %s...", self.group_id, website_url)
  675. task_out = VSCloudApi.Instance().submit_anti_turnstile_task(proxy_str, website_url)
  676. if not task_out:
  677. raise BizLogicError(message="Failed to submit captcha task to Cloud API")
  678. task_id = str(task_out.get("id"))
  679. if not task_id:
  680. raise BizLogicError(message="Cloud API returned invalid task ID")
  681. # 3. 轮询结果 (超时时间 120秒)
  682. timeout = 120
  683. start_time = time.time()
  684. while time.time() - start_time < timeout:
  685. result_out = VSCloudApi.Instance().get_anti_turnstile_result(task_id)
  686. if not result_out:
  687. time.sleep(3)
  688. continue
  689. # status: 0=Pending, 1=Processing, 2=Success, 3=Failed
  690. status = result_out.get("status", 0)
  691. if status == 2:
  692. raw_result = result_out.get("result", "")
  693. if isinstance(raw_result, str):
  694. data = json.loads(raw_result)
  695. else:
  696. data = raw_result
  697. token = data.get("token")
  698. ua = data.get("userAgent")
  699. cookies_list = data.get("cookies", [])
  700. if not token:
  701. raise BizLogicError("Captcha solved but token is empty")
  702. # A. 设置 User-Agent
  703. if ua:
  704. self.user_agent = ua
  705. self.session.headers["User-Agent"] = ua
  706. # B. 设置 Cookies
  707. if cookies_list:
  708. VSC_DEBUG("vfs_plg", "[%s] Syncing %d cookies from Captcha solver...", self.group_id, len(cookies_list))
  709. for cookie in cookies_list:
  710. # 兼容不同的 cookie 格式
  711. c_name = cookie.get("name")
  712. c_value = cookie.get("value")
  713. c_domain = cookie.get("domain", "")
  714. c_path = cookie.get("path", "/")
  715. if c_name and c_value:
  716. self.session.cookies.set(
  717. name=c_name,
  718. value=c_value,
  719. domain=c_domain,
  720. path=c_path
  721. )
  722. VSC_INFO("vfs_plg", "[%s] Cloudflare challenge passed.", self.group_id)
  723. return token
  724. elif status == 3: # Failed
  725. err_msg = result_out.get("result", "Unknown error")
  726. raise BizLogicError(message=f"Captcha task failed: {err_msg}")
  727. else:
  728. # Pending / Processing
  729. time.sleep(3)
  730. raise BizLogicError(message="Captcha task timeout (120s)")
  731. def _get_common_headers(self, with_auth=True) -> Dict[str, str]:
  732. mission = self.free_config.get("missionCode", "")
  733. country = self.free_config.get("countryCode", "")
  734. lang = self.free_config.get("language", "en")
  735. route = f"{country}/{lang}/{mission}"
  736. h = {
  737. "accept": "application/json, text/plain, */*",
  738. "accept-language": "en-US,en;q=0.9",
  739. "origin": "https://visa.vfsglobal.com",
  740. "referer": "https://visa.vfsglobal.com/",
  741. "route": route
  742. }
  743. client_src = self._get_client_source()
  744. h["clientsource"] = client_src
  745. if with_auth and self.jwt_token:
  746. h["authorize"] = self.jwt_token
  747. return h
  748. def _query_earliest_slot(self, apt_config) -> Optional[str]:
  749. """
  750. 查询最早 Slot(403 自动绕盾 + 重试)
  751. """
  752. url = "https://lift-api.vfsglobal.com/appointment/CheckIsSlotAvailable"
  753. max_retries = self.free_config.get("slot_query_max_retries", 2)
  754. data = {
  755. "missioncode": self.free_config.get("missionCode"),
  756. "countrycode": self.free_config.get("countryCode"),
  757. "vacCode": apt_config.get("vacCode"),
  758. "visaCategoryCode": apt_config.get("subcategoryCode"),
  759. "roleName": "Individual",
  760. "loginUser": self.config.account.username,
  761. "payCode": ""
  762. }
  763. headers = self._get_common_headers(with_auth=True)
  764. headers["content-type"] = "application/json;charset=UTF-8"
  765. for attempt in range(1, max_retries + 1):
  766. try:
  767. resp = self._perform_request(
  768. "POST",
  769. url,
  770. headers=headers,
  771. json_data=data
  772. )
  773. break # ✅ 请求成功,跳出重试循环
  774. except PermissionDeniedError:
  775. VSC_WARN(
  776. "vfs_plg",
  777. "[VFS] Earliest slot blocked (403), attempt %d/%d",
  778. attempt, max_retries
  779. )
  780. # 最后一次就不再绕盾了
  781. if attempt >= max_retries:
  782. raise PermissionDeniedError()
  783. self._handle_cloudflare_challenge()
  784. VSC_INFO("vfs_plg", "[VFS] Cloudflare bypass success, retrying...")
  785. continue
  786. # ====== 正常解析响应 ======
  787. if "WaitList" in resp.text:
  788. return "WaitList"
  789. j = resp.json()
  790. if j.get("earliestSlotLists"):
  791. raw_date = j["earliestSlotLists"][0]["date"]
  792. dt = datetime.strptime(raw_date, "%m/%d/%Y %H:%M:%S")
  793. return dt.strftime("%m/%d/%Y")
  794. return ""
  795. def _fmt_date(self, yyyy_mm_dd):
  796. try:
  797. return datetime.strptime(yyyy_mm_dd, "%Y-%m-%d").strftime("%d/%m/%Y")
  798. except:
  799. return yyyy_mm_dd
  800. def _fetch_configurations(self, apt_config: Dict[str, Any]):
  801. # 1. 获取所有中心配置 (query_center)
  802. if not self.center_conf:
  803. self.center_conf = self._query_center()
  804. # 2. 获取 Visa Category 配置
  805. vac_code = apt_config.get("vacCode")
  806. category_code = apt_config.get("categoryCode")
  807. # 检查目标 category_code 是否已在缓存中
  808. if category_code not in self.category_conf:
  809. visa_categories = []
  810. visa_categories = self._query_visa_category(vac_code)
  811. found = False
  812. for vc in visa_categories:
  813. if vc.get("code") == category_code:
  814. self.category_conf[category_code] = vc
  815. found = True
  816. break
  817. # 如果没找到,可能配置错误,但 C++ 没报错,只继续
  818. if not found:
  819. raise NotFoundError(message=f"{self.group_id} Category code {category_code} not found in VAC {vac_code}")
  820. # 3. 获取 Visa SubCategory 配置
  821. sub_category_code = apt_config.get("subcategoryCode")
  822. if sub_category_code not in self.subcategory_conf:
  823. visa_subcategories = self._query_visa_sub_category(vac_code, category_code)
  824. found = False
  825. for svc in visa_subcategories:
  826. if svc.get("code") == sub_category_code:
  827. self.subcategory_conf[sub_category_code] = svc
  828. found = True
  829. break
  830. if not found:
  831. raise NotFoundError(message=f"{self.group_id} SubCategory code {sub_category_code} not found")
  832. def _query_center(self) -> List:
  833. mission = self.free_config.get("missionCode")
  834. country = self.free_config.get("countryCode")
  835. url = f"https://lift-api.vfsglobal.com/master/center/{mission}/{country}/en-US"
  836. headers = self._get_common_headers(with_auth=False)
  837. resp = self._perform_request("GET", url, headers=headers)
  838. return resp.json()
  839. def _query_visa_category(self, center_code: str) -> List:
  840. mission = self.free_config.get("missionCode")
  841. country = self.free_config.get("countryCode")
  842. enc_center = urllib.parse.quote(center_code)
  843. url = f"https://lift-api.vfsglobal.com/master/visacategory/{mission}/{country}/{enc_center}/en-US"
  844. headers = self._get_common_headers(with_auth=False)
  845. resp = self._perform_request("GET", url, headers=headers)
  846. return resp.json()
  847. def _query_visa_sub_category(self, center_code: str, category_code: str) -> List:
  848. mission = self.free_config.get("missionCode")
  849. country = self.free_config.get("countryCode")
  850. enc_center = urllib.parse.quote(center_code)
  851. enc_cat = urllib.parse.quote(category_code)
  852. url = f"https://lift-api.vfsglobal.com/master/subvisacategory/{mission}/{country}/{enc_center}/{enc_cat}/en-US"
  853. headers = self._get_common_headers(with_auth=False)
  854. resp = self._perform_request("GET", url, headers=headers)
  855. return resp.json()
  856. def _read_otp_email(self) -> str:
  857. """
  858. 读取 OTP 邮件
  859. """
  860. master_email = "visafly666@gmail.com"
  861. recipient = self.config.account.username
  862. sender = "donotreply at vfshelpline.com"
  863. subject_keywords = "One Time Password"
  864. body_keywords = "OTP"
  865. now_utc = datetime.utcnow()
  866. formatted_utc_time = now_utc.strftime("%Y-%m-%d %H:%M:%S")
  867. VSC_INFO("vfs_plg", "[%s] Waiting for OTP email sent after %s...", self.group_id, formatted_utc_time)
  868. # 3. 轮询查收
  869. for i in range(12):
  870. content_out = VSCloudApi.Instance().fetch_mail_content(
  871. master_email,
  872. sender,
  873. recipient,
  874. subject_keywords,
  875. body_keywords,
  876. formatted_utc_time,
  877. 300
  878. )
  879. if content_out:
  880. match = re.search(r'\b\d{6}\b', content_out)
  881. if match:
  882. otp = match.group(0)
  883. VSC_INFO("vfs_plg", "[%s] OTP code found: %s", self.group_id, otp)
  884. return otp
  885. time.sleep(5)
  886. raise NotFoundError(message="OTP email not found (timeout)")
  887. def _submit_login_otp(self, cf_token: str, otp: str):
  888. """
  889. 提交 OTP 验证码进行登录
  890. """
  891. VSC_INFO("vfs_plg", "[%s] Submitting Login OTP...", self.group_id)
  892. # 1. 准备基础数据
  893. email = self.config.account.username
  894. password = self.config.account.password
  895. enc_password = self._encrypt_password(password)
  896. mission_code = self.free_config.get("missionCode", "")
  897. country_code = self.free_config.get("countryCode", "")
  898. # 2. 生成加密 Source (每次请求时间戳不同,建议重新生成)
  899. client_src = self._get_client_source()
  900. orange_src = self._get_orange_source(email)
  901. # 3. 构造请求
  902. url = "https://lift-api.vfsglobal.com/user/login"
  903. headers = self._get_common_headers(with_auth=False)
  904. headers.update({
  905. "clientsource": client_src,
  906. "orangex": orange_src,
  907. "content-type": "application/x-www-form-urlencoded"
  908. })
  909. # 为了稳健,如果传入为空,尝试重新获取。
  910. if not cf_token:
  911. VSC_DEBUG("vfs_plg", "[%s] CF Token is empty, regenerating for OTP...", self.group_id)
  912. cf_token = self._handle_cloudflare_challenge()
  913. data = {
  914. "username": email,
  915. "password": enc_password,
  916. "missioncode": mission_code,
  917. "countrycode": country_code,
  918. "languageCode": "en-US",
  919. "captcha_version": "cloudflare-v1",
  920. "captcha_api_key": cf_token,
  921. "otp": otp # 关键字段:OTP 验证码
  922. }
  923. # 4. 发送请求 (POST form-urlencoded)
  924. resp = self._perform_request("POST", url, headers=headers, data=data)
  925. resp_json = resp.json()
  926. if resp_json["accessToken"]:
  927. self.jwt_token = resp_json["accessToken"]
  928. VSC_INFO("vfs_plg", "[%s] OTP Login successful, JWT obtained.", self.group_id)
  929. return
  930. raise PermissionDeniedError(message=resp.text)
  931. def _submit_no_addition_service(self, urn):
  932. url = "https://lift-api.vfsglobal.com/vas/mapvas"
  933. headers = self._get_common_headers(with_auth=True)
  934. headers["content-type"] = "application/json;charset=UTF-8"
  935. data = {
  936. "loginUser": self.config.account.username,
  937. "missionCode": self.free_config.get("missionCode"),
  938. "countryCode": self.free_config.get("countryCode"),
  939. "urn": urn,
  940. "applicants": []
  941. }
  942. # C++ 只请求不检查结果,或者只要200就行
  943. self._perform_request("POST", url, headers=headers, json_data=data)
  944. def _query_fee(self, apt_config, urn) -> Tuple[float, str]:
  945. url = "https://lift-api.vfsglobal.com/appointment/fees"
  946. headers = self._get_common_headers(with_auth=True)
  947. headers["content-type"] = "application/json;charset=UTF-8"
  948. data = {
  949. "missionCode": self.free_config.get("missionCode"),
  950. "countryCode": self.free_config.get("countryCode"),
  951. "centerCode": apt_config.get("vacCode"),
  952. "loginUser": self.config.account.username,
  953. "urn": urn,
  954. "languageCode": "en-US"
  955. }
  956. resp = self._perform_request("POST", url, headers=headers, json_data=data)
  957. j = resp.json()
  958. return float(j.get("totalamount", 0.0)), j["feeDetails"][0].get("currency", "")
  959. def _schedule(self, apt_config, urn, amount, currency, slot_id) -> Dict:
  960. url = "https://lift-api.vfsglobal.com/appointment/schedule"
  961. headers = self._get_common_headers(with_auth=True)
  962. headers["content-type"] = "application/json;charset=UTF-8"
  963. data = {
  964. "missionCode": self.free_config.get("missionCode"),
  965. "countryCode": self.free_config.get("countryCode"),
  966. "centerCode": apt_config.get("vacCode"),
  967. "loginUser": self.config.account.username,
  968. "urn": urn,
  969. "notificationType": "none",
  970. "paymentdetails": {
  971. "paymentmode": "Online",
  972. "RequestRefNo": "",
  973. "clientId": "",
  974. "merchantId": "",
  975. "amount": amount,
  976. "currency": currency
  977. },
  978. "allocationId": slot_id,
  979. "CanVFSReachoutToApplicant": True
  980. }
  981. resp = self._perform_request("POST", url, headers=headers, json_data=data)
  982. return resp.json()
  983. def _pay_request(self, payload) -> str:
  984. # C++: 检查 301/302 Redirect Location
  985. url = f"https://online.vfsglobal.com/PG-Component/Payment/PayRequest?payLoad={payload}"
  986. headers = {
  987. "accept": "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8",
  988. "referer": "https://visa.vfsglobal.com/",
  989. "user-agent": self.user_agent
  990. }
  991. # allow_redirects=False 以捕获 Location header
  992. resp = self.session.get(url, headers=headers, allow_redirects=False)
  993. if resp.status_code in [301, 302]:
  994. loc = resp.headers.get("Location", "")
  995. if loc.startswith("http"):
  996. return loc
  997. else:
  998. return "https://online.vfsglobal.com" + loc if loc.startswith("/") else "https://online.vfsglobal.com/" + loc
  999. else:
  1000. raise NotFoundError(message='payment link not found')
  1001. def _save_http_session(self, page_url):
  1002. """
  1003. 提取 cookies, local_storage, 存入 VSCloudApi
  1004. """
  1005. cookies_dict = {}
  1006. # 方式 1: curl_cffi 的 cookies 对象通常支持 get_dict()
  1007. if hasattr(self.session.cookies, "get_dict"):
  1008. cookies_dict = self.session.cookies.get_dict()
  1009. else:
  1010. # 方式 2: 迭代 (兼容标准 CookieJar)
  1011. for c in self.session.cookies:
  1012. cookies_dict[c.name] = c.value
  1013. cookies_str = json.dumps(cookies_dict)
  1014. # 简单生成 SessionID hash
  1015. ua_str = self.user_agent or "unknown_ua"
  1016. raw = cookies_str + ua_str + page_url
  1017. session_id = hashes.Hash(hashes.SHA256(), backend=default_backend())
  1018. session_id.update(raw.encode())
  1019. sid = session_id.finalize().hex()
  1020. proxy_str = ""
  1021. if self.config.proxy.ip:
  1022. proxy_str = f"{self.config.proxy.scheme}://"
  1023. if self.config.proxy.username:
  1024. proxy_str += f"{self.config.proxy.username}:{self.config.proxy.password}@"
  1025. proxy_str += f"{self.config.proxy.ip}:{self.config.proxy.port}"
  1026. return VSCloudApi.Instance().create_http_session(
  1027. sid, cookies_str, "", ua_str, proxy_str, page_url
  1028. )