ShopifyController.py 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404
  1. from datetime import datetime
  2. import concurrent.futures
  3. import pytz
  4. import requests
  5. from django.db.models import Q, F
  6. from django.views import View
  7. from Crypto.Cipher import AES
  8. from Crypto.Util.Padding import pad
  9. from django.contrib.auth.hashers import check_password, make_password
  10. import concurrent.futures
  11. from Controller.CheckUserData import DataValid
  12. from Model.models import Device_User, CountryModel, LanguageModel, CountryLanguageModel
  13. from Object.RedisObject import RedisObject
  14. from Object.ResponseObject import ResponseObject
  15. import base64
  16. import hmac
  17. import hashlib
  18. import os
  19. import json
  20. from Ansjer.config import SHOPIFY_CONFIG
  21. from Service.CommonService import CommonService
  22. class ShopifyMultipass:
  23. @staticmethod
  24. def generate_multipass_token(secret, customer_data):
  25. """
  26. 使用指定的密钥对加密并签名JSON数据,返回Base64编码的Multipass令牌
  27. """
  28. # 第一步:将客户数据转换为JSON格式
  29. json_data = json.dumps(customer_data)
  30. # 第二步:生成加密密钥和签名密钥
  31. hash_digest = hashlib.sha256(secret.encode()).digest()
  32. encryption_key = hash_digest[:16] # 128位加密密钥
  33. signature_key = hash_digest[16:32] # 128位签名密钥
  34. # 第三步:加密JSON数据
  35. iv = os.urandom(16) # 随机初始化向量
  36. cipher = AES.new(encryption_key, AES.MODE_CBC, iv)
  37. ciphertext = cipher.encrypt(pad(json_data.encode(), AES.block_size))
  38. # 第四步:签名加密数据
  39. data_to_sign = iv + ciphertext
  40. signature = hmac.new(signature_key, data_to_sign, hashlib.sha256).digest()
  41. # 第五步:Base64编码
  42. multipass_token = base64.urlsafe_b64encode(iv + ciphertext + signature).decode()
  43. return multipass_token
  44. @staticmethod
  45. def search_customer_by_email(store_name, access_token, email):
  46. # 设置请求URL
  47. url = f"https://{store_name}.myshopify.com/admin/api/2024-10/customers/search.json"
  48. params = {
  49. "query": f"email:{email}"
  50. }
  51. # 设置请求头
  52. headers = {
  53. "X-Shopify-Access-Token": access_token,
  54. }
  55. # 发送GET请求
  56. response = requests.get(url, headers=headers, params=params)
  57. # 返回响应的JSON数据
  58. return response.json()
  59. class ShopifyView(View):
  60. def get(self, request, *args, **kwargs):
  61. request.encoding = 'utf-8'
  62. operation = kwargs.get('operation')
  63. request_dict = request.GET
  64. return self.validation(request, request_dict, operation)
  65. def post(self, request, *args, **kwargs):
  66. request.encoding = 'utf-8'
  67. operation = kwargs.get('operation')
  68. request_dict = request.POST
  69. return self.validation(request, request_dict, operation)
  70. def validation(self, request, request_dict, operation):
  71. language = request_dict.get('language', 'cn')
  72. response = ResponseObject(language, "pc")
  73. if operation == 'shopifyLogin':
  74. return self.shopify_login(request_dict, response)
  75. elif operation == 'shopifyRegister':
  76. return self.shopify_register(request_dict, response)
  77. # 查询FAPP注册账号情况
  78. elif operation == 'searchCustomer':
  79. return self.search_customer(request_dict, response)
  80. # 官网检测账号接口
  81. elif operation == 'searchAccount':
  82. return self.search_account(request_dict, response)
  83. elif operation == 'getCountryDomainList':
  84. return self.get_country_domain_list(request_dict, response)
  85. # 忘记密码
  86. elif operation == 'shopifyChangePassword':
  87. return self.shopify_change_password(request_dict, response)
  88. elif operation == 'verifyAuthcode':
  89. return self.verify_authcode(request_dict, response)
  90. else:
  91. return response.json(414)
  92. @staticmethod
  93. def shopify_login(request_dict, response):
  94. email = request_dict.get("email", None)
  95. password = request_dict.get("password", None)
  96. account_region = request_dict.get("accountRegion", "")
  97. account_iso2 = request_dict.get("accountIso2", "")
  98. shopify_country = request_dict.get("shopifyCountry", "")
  99. if not all([email, password]):
  100. return response.json(444)
  101. user_qs = Device_User.objects.filter(Q(username=email) | Q(userEmail=email))
  102. if not user_qs.exists():
  103. return response.json(104)
  104. users = user_qs.values(
  105. 'role__rid', 'role__roleName', 'userID', 'NickName',
  106. 'username', 'userEmail', 'phone', 'password', 'userIconPath'
  107. )[0]
  108. if not check_password(password, users['password']):
  109. return response.json(111)
  110. # 获取当前时间并格式化时间戳
  111. now = datetime.now(pytz.timezone('America/New_York'))
  112. timestamp = now.strftime('%Y-%m-%dT%H:%M:%S%z')
  113. timestamp = timestamp[:-2] + ':' + timestamp[-2:]
  114. customer_data = {
  115. "email": email,
  116. "created_at": timestamp,
  117. }
  118. # 定义默认配置键
  119. secret_key = "eu_multipass_secret"
  120. store_name_key = "eu_store_name"
  121. # 根据条件选择配置键
  122. if shopify_country:
  123. secret_key = f"{shopify_country}_multipass_secret"
  124. store_name_key = f"{shopify_country}_store_name"
  125. elif account_region == "us" and account_iso2 == "jp":
  126. secret_key = "jp_multipass_secret"
  127. store_name_key = "jp_store_name"
  128. elif account_region == "us":
  129. secret_key = "us_multipass_secret"
  130. store_name_key = "us_store_name"
  131. elif account_region == "eu" and account_iso2 == "de":
  132. secret_key = "de_multipass_secret"
  133. store_name_key = "de_store_name"
  134. elif account_region == "eu" and account_iso2 == "uk":
  135. secret_key = "uk_multipass_secret"
  136. store_name_key = "uk_store_name"
  137. # 获取配置并生成重定向URL
  138. multipass_secret = SHOPIFY_CONFIG[secret_key]
  139. store_name = SHOPIFY_CONFIG[store_name_key]
  140. token = ShopifyMultipass.generate_multipass_token(multipass_secret, customer_data)
  141. redirect_url = f"https://{store_name}.zositech.com/account/login/multipass/{token}"
  142. return response.json(0, redirect_url)
  143. @staticmethod
  144. def shopify_register(request_dict, response):
  145. email = request_dict.get("email", None)
  146. password = request_dict.get("password", None)
  147. authcode = request_dict.get("authCode", None)
  148. if not all([email, password, authcode]):
  149. return response.json(444)
  150. data_valid = DataValid()
  151. re_flag = data_valid.password_validate(password)
  152. if re_flag is not True:
  153. return response.json(109)
  154. reds = RedisObject()
  155. identifyingCode = reds.get_data(key=email + '_identifyingCode')
  156. # 判断验证码是否过期
  157. if identifyingCode is False:
  158. return response.json(120)
  159. # 验证码是否正确
  160. if authcode != identifyingCode:
  161. return response.json(121)
  162. # 注册
  163. if Device_User.objects.filter(Q(username=email) | Q(userEmail=email)).exists():
  164. return response.json(103)
  165. # 创建用户
  166. password = make_password(password)
  167. new_userID = CommonService.getUserID(μs=False, setOTAID=True)
  168. user_data = {
  169. "username": email,
  170. "NickName": email,
  171. "userEmail": email,
  172. "password": password,
  173. "userID": new_userID,
  174. "is_active": True,
  175. "user_isValid": True,
  176. }
  177. Device_User.objects.create(**user_data)
  178. reds.del_data(key=email + '_identifyingCode')
  179. return response.json(0)
  180. def search_account(self, request_dict, response):
  181. email = request_dict.get("email")
  182. if not email:
  183. return response.json(444)
  184. store_configs = [
  185. ("us", SHOPIFY_CONFIG["us_store_name"], SHOPIFY_CONFIG["us_token"]),
  186. ("eu", SHOPIFY_CONFIG["eu_store_name"], SHOPIFY_CONFIG["eu_token"]),
  187. ("de", SHOPIFY_CONFIG["de_store_name"], SHOPIFY_CONFIG["de_token"]),
  188. ("uk", SHOPIFY_CONFIG["uk_store_name"], SHOPIFY_CONFIG["uk_token"]),
  189. ("jp", SHOPIFY_CONFIG["jp_store_name"], SHOPIFY_CONFIG["jp_token"]),
  190. ]
  191. def search_customer(store_name, token):
  192. return ShopifyMultipass.search_customer_by_email(store_name, token, email)
  193. try:
  194. shopify_results = {}
  195. with concurrent.futures.ThreadPoolExecutor() as executor:
  196. future_to_country = {executor.submit(search_customer, store_name, token): country for
  197. country, store_name, token in store_configs}
  198. for future in concurrent.futures.as_completed(future_to_country):
  199. country = future_to_country[future]
  200. shopify_results[country] = future.result()
  201. shopify_country = next((country for country, result in shopify_results.items() if result["customers"]), "")
  202. account_country = self.call_search_customer(email)
  203. servers_continent = "us" if account_country["us"] else "eu" if account_country["eu"] else ""
  204. if servers_continent:
  205. account_region_list = []
  206. if account_country.get("us"):
  207. account_region_list.append({
  208. "region": "us",
  209. "url": "https://www.dvema.com/shopify/shopifyLogin",
  210. "accountCountry": account_country["us"],
  211. "shopifyCountry": shopify_country
  212. })
  213. if account_country.get("eu"):
  214. account_region_list.append({
  215. "region": "eu",
  216. "url": "https://api.zositeche.com/shopify/shopifyLogin",
  217. "accountCountry": account_country["eu"],
  218. "shopifyCountry": shopify_country
  219. })
  220. return response.json(0, {"accountStatus": 3, "accountRegionList": account_region_list})
  221. elif shopify_country:
  222. if shopify_country == "eu":
  223. url = "https://eu.zositech.com/account/login"
  224. elif shopify_country == "jp":
  225. url = "https://www.zosi.jp/account/login"
  226. elif shopify_country == "de":
  227. url = "https://www.zositech.de/account/login"
  228. elif shopify_country == "uk":
  229. url = "https://www.zositech.co.uk/account/login"
  230. else:
  231. url = "https://www.zositech.com/account/login"
  232. return response.json(0, {"accountStatus": 2, "url": url})
  233. else:
  234. url = "注册链接"
  235. return response.json(0, {"accountStatus": 1, "url": url})
  236. except Exception as e:
  237. print(e)
  238. return response.json(500, 'error_line:{}, error_msg:{}'.format(e.__traceback__.tb_lineno, repr(e)))
  239. @staticmethod
  240. def call_search_customer(email):
  241. urls = {
  242. "us": "https://www.dvema.com/shopify/searchCustomer",
  243. "eu": "https://api.zositeche.com/shopify/searchCustomer"
  244. }
  245. params = {"email": email} # Use the provided email parameter
  246. customer_region = {}
  247. def fetch_customer(region, url):
  248. try:
  249. response = requests.get(url=url, params=params)
  250. response.raise_for_status() # Raise an error for bad responses
  251. customer_country = response.json().get("result", None)
  252. return region, customer_country if not all(customer_country) else None
  253. except requests.RequestException:
  254. return region, None
  255. with concurrent.futures.ThreadPoolExecutor() as executor:
  256. future_to_region = {executor.submit(fetch_customer, region, url): region for region, url in urls.items()}
  257. for future in concurrent.futures.as_completed(future_to_region):
  258. region, customer_country = future.result()
  259. customer_region[region] = customer_country
  260. return customer_region
  261. @staticmethod
  262. def search_customer(request_dict, response):
  263. email = request_dict.get("email")
  264. user_qs = Device_User.objects.filter(Q(username=email) | Q(userEmail=email))
  265. if not user_qs.exists():
  266. return response.json(104)
  267. user_region_id = user_qs.values_list('region_country', flat=True).first()
  268. country_code = CountryModel.objects.filter(id=user_region_id).values_list("country_code", flat=True).first()
  269. return response.json(0, country_code)
  270. @staticmethod
  271. def get_country_domain_list(request_dict, response):
  272. lang = request_dict.get('lang', 'en')
  273. time_stamp = request_dict.get('time_stamp', None)
  274. time_stamp_token = request_dict.get('time_stamp_token', None)
  275. if not all([time_stamp, time_stamp_token]):
  276. return response.json(444)
  277. try:
  278. # 时间戳token校验
  279. if not CommonService.check_time_stamp_token(time_stamp_token, time_stamp):
  280. return response.json(13)
  281. lang_qs = LanguageModel.objects.filter(lang=lang)
  282. language = lang_qs[0]
  283. country_qs = CountryLanguageModel.objects.filter(language_id=language.id)
  284. country_qs = country_qs.annotate(api=F('country__region__zosi_api'))
  285. country_qs = country_qs.values('country_id', 'country_name', 'api').order_by('country_id')
  286. country_list = []
  287. for country in country_qs:
  288. country['api'] = country['api'] + 'shopify/shopifyRegister'
  289. country_list.append(country)
  290. return response.json(0, country_list)
  291. except Exception as e:
  292. print(e)
  293. return response.json(500, 'error_line:{}, error_msg:{}'.format(e.__traceback__.tb_lineno, repr(e)))
  294. @staticmethod
  295. def shopify_change_password(request_dict, response):
  296. email = request_dict.get("email", None)
  297. password = request_dict.get("password", None)
  298. authcode = request_dict.get("authCode", None)
  299. if not all([email, password, authcode]):
  300. return response.json(444)
  301. try:
  302. reds = RedisObject()
  303. identifyingCode = reds.get_data(key=email + '_forgetPwdResetCode')
  304. # 判断验证码是否过期
  305. if identifyingCode is False:
  306. return response.json(120)
  307. # 验证码是否正确
  308. if authcode != identifyingCode:
  309. return response.json(121)
  310. user_qs = Device_User.objects.filter(Q(username=email) | Q(userEmail=email))
  311. if not user_qs.exists():
  312. return response.json(174)
  313. password = make_password(password)
  314. user_qs.update(password=password)
  315. reds.del_data(key=email + '_forgetPwdResetCode')
  316. return response.json(0)
  317. except Exception as e:
  318. return response.json(500, 'error_line:{}, error_msg:{}'.format(e.__traceback__.tb_lineno, repr(e)))
  319. @staticmethod
  320. def verify_authcode(request_dict, response):
  321. """
  322. 在修改密码的时候改变验证码
  323. """
  324. email = request_dict.get("email", None)
  325. authcode = request_dict.get("authCode", None)
  326. code_type = request_dict.get("code_type", None)
  327. if not all([email, authcode, code_type]):
  328. return response.json(444)
  329. try:
  330. code_type = int(code_type)
  331. if code_type == 1:
  332. reds_key = "_forgetPwdResetCode"
  333. elif code_type == 2:
  334. reds_key = "_identifyingCode"
  335. else:
  336. return response.json(444)
  337. reds = RedisObject()
  338. identifyingCode = reds.get_data(key=email + reds_key)
  339. if identifyingCode is False:
  340. return response.json(120)
  341. # 验证码是否正确
  342. if authcode != identifyingCode:
  343. return response.json(121)
  344. user_qs = Device_User.objects.filter(Q(username=email) | Q(userEmail=email))
  345. if not user_qs.exists():
  346. return response.json(174)
  347. return response.json(0)
  348. except Exception as e:
  349. return response.json(500, 'error_line:{}, error_msg:{}'.format(e.__traceback__.tb_lineno, repr(e)))