wechat1.py 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348
  1. # coding=utf-8
  2. import requests
  3. import json
  4. from django.conf import settings
  5. from utils.exceptions import CustomError
  6. from utils.file_operation import PathAndRename
  7. from django.utils import timezone
  8. import logging
  9. import urllib3
  10. urllib3.disable_warnings()
  11. logging.captureWarnings(True)
  12. class WeChat(object):
  13. @staticmethod
  14. def getPreAuthCode(component_appid, component_access_token):
  15. """
  16. 第三方平台 获得预授权码
  17. 结果{"pre_auth_code": "Cx_Dk6qiBE0Dmx4EmlT3oRfArPvwSQ-oa3NL_fwHM7VI08r52wazoZX2Rhpz1dEw", "expires_in": 600}
  18. """
  19. url = 'https://api.weixin.qq.com/cgi-bin/component/api_create_preauthcode?component_access_token=' + component_access_token
  20. param = {
  21. 'component_appid': component_appid,
  22. }
  23. result = requests.post(url, data=json.dumps(param), verify=False)
  24. result = result.json()
  25. if 'errcode' in result and result['errcode']:
  26. raise CustomError(u'微信请求失败' + str(result['errcode']) + ' :' + result['errmsg'])
  27. return result
  28. @staticmethod
  29. def getComponentAccessToken(component_appid, component_appsecret, component_verify_ticket):
  30. """第三方平台 获得access_token"""
  31. url = 'https://api.weixin.qq.com/cgi-bin/component/api_component_token'
  32. param = {
  33. 'component_appid': component_appid,
  34. 'component_appsecret': component_appsecret,
  35. 'component_verify_ticket': component_verify_ticket
  36. }
  37. result = requests.post(url, data=json.dumps(param), verify=False)
  38. result = result.json()
  39. if 'errcode' in result and result['errcode']:
  40. raise CustomError(u'微信请求失败'+ str(result['errcode']) + ' :' + result['errmsg'])
  41. return result
  42. @staticmethod
  43. def getAuthorizationInfo(component_appid, authorization_code, component_access_token):
  44. """第三方平台 获得授权信息"""
  45. url = 'https://api.weixin.qq.com/cgi-bin/component/api_query_auth?component_access_token=' + component_access_token
  46. param = {
  47. 'component_appid': component_appid,
  48. 'authorization_code': authorization_code,
  49. }
  50. result = requests.post(url, data=json.dumps(param), verify=False)
  51. result = result.json()
  52. if 'errcode' in result and result['errcode']:
  53. raise CustomError(u'微信请求失败'+ str(result['errcode']) + ' :' + result['errmsg'])
  54. return result
  55. @staticmethod
  56. def getAuthorizerInfo(component_appid, authorizer_appid, component_access_token):
  57. """第三方平台 获得授权方信息"""
  58. url = 'https://api.weixin.qq.com/cgi-bin/component/api_get_authorizer_info?component_access_token=' + component_access_token
  59. param = {
  60. 'component_appid': component_appid,
  61. 'authorizer_appid': authorizer_appid,
  62. }
  63. result = requests.post(url, data=json.dumps(param), verify=False)
  64. result = result.json()
  65. if 'errcode' in result and result['errcode']:
  66. raise CustomError(u'微信请求失败'+ str(result['errcode']) + ' :' + result['errmsg'])
  67. return result
  68. @staticmethod
  69. def getAuthorizerAccessToken(component_appid, authorizer_appid, authorizer_refresh_token, component_access_token):
  70. """第三方平台 获得授权方 access_token"""
  71. url = 'https://api.weixin.qq.com/cgi-bin/component/api_authorizer_token?component_access_token=' + component_access_token
  72. param = {
  73. 'component_appid': component_appid,
  74. 'authorizer_appid': authorizer_appid,
  75. 'authorizer_refresh_token': authorizer_refresh_token
  76. }
  77. result = requests.post(url, data=json.dumps(param), verify=False)
  78. result = result.json()
  79. if 'errcode' in result and result['errcode']:
  80. raise CustomError(u'微信请求失败'+ str(result['errcode']) + ' :' + result['errmsg'])
  81. return result
  82. @staticmethod
  83. def getCodeTemplateList(component_access_token):
  84. '''获取代码模版列表'''
  85. url = 'https://api.weixin.qq.com/wxa/gettemplatelist?access_token=' + component_access_token
  86. result = requests.get(url, verify=False)
  87. result = result.json()
  88. if 'errcode' in result and result['errcode']:
  89. raise CustomError(u'微信请求失败'+ str(result['errcode']) + ' :' + result['errmsg'])
  90. return result['template_list']
  91. @staticmethod
  92. def getDraftTemplateList(component_access_token):
  93. '''获取草稿箱列表'''
  94. url = 'https://api.weixin.qq.com/wxa/gettemplatedraftlist?access_token=' + component_access_token
  95. result = requests.get(url, verify=False)
  96. result = result.json()
  97. if 'errcode' in result and result['errcode']:
  98. raise CustomError(u'微信请求失败'+ str(result['errcode']) + ' :' + result['errmsg'])
  99. return result['draft_list']
  100. @staticmethod
  101. def addToemplate(component_access_token, draft_id):
  102. '''上传草稿到标准模板'''
  103. url = 'https://api.weixin.qq.com/wxa/addtotemplate?access_token=' + component_access_token
  104. param = {
  105. 'draft_id': draft_id,
  106. }
  107. result = requests.post(url, data=json.dumps(param), verify=False)
  108. result = result.json()
  109. if 'errcode' in result and result['errcode']:
  110. raise CustomError(u'微信请求失败'+ str(result['errcode']) + ' :' + result['errmsg'])
  111. return result
  112. @staticmethod
  113. def commitCode(access_token, template_id, user_version, user_desc):
  114. '''小程序提交代码'''
  115. url = 'https://api.weixin.qq.com/wxa/commit?access_token=' + access_token
  116. param = {
  117. 'template_id': template_id,
  118. 'ext_json': "{\"extEnable\": false,\"extAppid\": \"\"}",
  119. 'user_version': user_version,
  120. 'user_desc': 'test'
  121. }
  122. result = requests.post(url, data=json.dumps(param), verify=False)
  123. result = result.json()
  124. if 'errcode' in result and result['errcode']:
  125. raise CustomError(u'微信请求失败'+ str(result['errcode']) + ' :' + result['errmsg'])
  126. return result
  127. @staticmethod
  128. def submitAuditCode(access_token):
  129. '''将上传的代码提交审核'''
  130. url = 'https://api.weixin.qq.com/wxa/submit_audit?access_token=' + access_token
  131. result = requests.post(url, verify=False)
  132. result = result.json()
  133. if 'errcode' in result and result['errcode']:
  134. raise CustomError(u'微信请求失败' + str(result['errcode']) + ' :' + result['errmsg'])
  135. return result
  136. @staticmethod
  137. def getLastSubmitAuditCodeStatus(access_token):
  138. '''查询最新一次提交审核代码的审核状态'''
  139. url = 'https://api.weixin.qq.com/wxa/get_latest_auditstatus?access_token=' + access_token
  140. result = requests.get(url, verify=False)
  141. result = result.json()
  142. if 'errcode' in result and result['errcode']:
  143. raise CustomError(u'微信请求失败' + str(result['errcode']) + ' :' + result['errmsg'])
  144. return result
  145. @staticmethod
  146. def modify_domain(access_token, action, requestdomain, wsrequestdomain, uploaddomain, downloaddomain):
  147. '''设置小程序服务器域名'''
  148. url = 'https://api.weixin.qq.com/wxa/modify_domain?access_token=' + access_token
  149. param = {
  150. "action": action,
  151. "requestdomain": requestdomain,
  152. "wsrequestdomain": wsrequestdomain,
  153. "uploaddomain": uploaddomain,
  154. "downloaddomain": downloaddomain
  155. }
  156. result = requests.post(url, data=json.dumps(param), verify=False)
  157. result = result.json()
  158. if 'errcode' in result and result['errcode']:
  159. raise CustomError(u'微信请求失败' + str(result['errcode']) + ' :' + result['errmsg'])
  160. return result
  161. @staticmethod
  162. def code2Session(appid, secret, code):
  163. '''登录凭证校验'''
  164. url = 'https://api.weixin.qq.com/sns/jscode2session?appid='+ appid + '&secret=' + secret + '&js_code=' + code + '&grant_type=authorization_code'
  165. result = requests.get(url, verify=False)
  166. result = result.json()
  167. if 'errcode' in result and result['errcode']:
  168. raise CustomError(u'微信请求失败' + str(result['errcode']) + ':' + result['errmsg'])
  169. return result
  170. @staticmethod
  171. def getAccessToken(appid, secret,):
  172. '''获取小程序验证token'''
  173. url = 'https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid='+ appid + '&secret=' + secret
  174. result = requests.get(url, verify=False)
  175. result = result.json()
  176. if 'errcode' in result and result['errcode']:
  177. raise CustomError(u'微信请求失败' + str(result['errcode']) + ':' + result['errmsg'])
  178. return result
  179. @staticmethod
  180. def addPlugin(access_token):
  181. '''小程序插件管理'''
  182. url = 'https://api.weixin.qq.com/wxa/plugin?access_token=' + access_token
  183. param = {
  184. 'action': 'apply',
  185. 'plugin_appid': 'wxfa43a4a7041a84de'
  186. }
  187. result = requests.post(url, data=json.dumps(param), verify=False)
  188. result = result.json()
  189. if 'errcode' in result and result['errcode'] and str(result['errcode']) != '89237':
  190. raise CustomError(u'微信请求失败' + str(result['errcode']) + ':' + result['errmsg'])
  191. return result
  192. @staticmethod
  193. def getTemplateList(access_token):
  194. '''获取当前帐号下的个人模板列表'''
  195. url = 'https://api.weixin.qq.com/wxaapi/newtmpl/gettemplate?access_token=' + access_token
  196. result = requests.get(url, verify=False)
  197. result = result.json()
  198. if 'errcode' in result and result['errcode']:
  199. raise CustomError(u'微信请求失败' + str(result['errcode']) + ':' + result['errmsg'])
  200. return result['data']
  201. @staticmethod
  202. def sendSubscribeMessage(access_token, openid, template_id, page, data):
  203. '''发送订阅消息'''
  204. url = 'https://api.weixin.qq.com/cgi-bin/message/subscribe/send?access_token=' + access_token
  205. param = {
  206. 'touser': openid,
  207. 'template_id': template_id,
  208. 'page': page,
  209. 'data': data
  210. }
  211. print(9999999,param)
  212. result = requests.post(url, data=json.dumps(param), verify=False)
  213. print('-------------------------')
  214. result = result.json()
  215. print(result)
  216. #result = requests.post(url, data=json.dumps(param))
  217. #result = result.json()
  218. #if 'errcode' in result and result['errcode'] and str(result['errcode']) != '89237':
  219. # raise CustomError(u'微信请求失败' + str(result['errcode']) + ':' + result['errmsg'])
  220. #return result
  221. @staticmethod
  222. def getWXAppCode(access_token, page, param):
  223. '''获取小程序二维码'''
  224. url = 'https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token={}'.format(access_token)
  225. data = {"scene": "{}".format(param),
  226. # "width": 1280, # 默认430
  227. "line_color": {"r": 43, "g": 162, "b": 69}, # 自定义颜色
  228. "is_hyaline": True}
  229. result = requests.post(url, json=data, verify=False)
  230. # print('-------------------------',result)
  231. upload_path = PathAndRename("wx_code/")
  232. filename = "%s%s.png" % (
  233. upload_path.path,
  234. timezone.now().strftime('%Y%m%d%H%M%S%f'),
  235. )
  236. filename = filename.lower()
  237. full_filename = "%s%s" % (settings.MEDIA_ROOT, filename)
  238. with open(full_filename, 'wb') as destination:
  239. destination.write(result.content)
  240. return filename
  241. @staticmethod
  242. def getCommodityCode(access_token, page, commodity_id, company_no):
  243. '''获取商品二维码'''
  244. url = 'https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token={}'.format(access_token)
  245. data = {"scene": "company_no={}&device_id={}".format(company_no, commodity_id),
  246. # "width": 1280, # 默认430
  247. "line_color": {"r": 43, "g": 162, "b": 69}, # 自定义颜色
  248. "is_hyaline": True}
  249. result = requests.post(url, json=data, verify=False)
  250. upload_path = PathAndRename("device/")
  251. filename = "%s%s.png" % (
  252. upload_path.path,
  253. commodity_id,
  254. )
  255. filename = filename.lower()
  256. full_filename = "%s%s" % (settings.MEDIA_ROOT, filename)
  257. with open(full_filename, 'wb') as destination:
  258. destination.write(result.content)
  259. return filename
  260. @staticmethod
  261. def releaseCode(access_token):
  262. '''已审核代码发布'''
  263. url = 'https://api.weixin.qq.com/wxa/release?access_token=' + access_token
  264. result = requests.post(url, data=json.dumps({}), verify=False)
  265. result = result.json()
  266. if 'errcode' in result and result['errcode']:
  267. raise CustomError(u'微信请求失败' + str(result['errcode']) + ' :' + result['errmsg'])
  268. return result
  269. @staticmethod
  270. def createFastRegisterWXApp(name, code, code_type, legal_persona_wechat, legal_persona_name, component_phone, component_access_token):
  271. '''快速注册企业小程序'''
  272. url = 'https://api.weixin.qq.com/cgi-bin/component/fastregisterweapp?action=create&component_access_token=' + component_access_token
  273. param = {
  274. "name": name, # 企业名
  275. "code": code, # 企业代码
  276. "code_type": code_type, # 企业代码类型(1:统一社会信用代码, 2:组织机构代码,3:营业执照注册号)
  277. "legal_persona_wechat": legal_persona_wechat, # 法人微信
  278. "legal_persona_name": legal_persona_name, # 法人姓名
  279. "component_phone": component_phone, #第三方联系电话
  280. }
  281. result = requests.post(url, data=json.dumps(param), verify=False)
  282. result = result.json()
  283. if 'errcode' in result and result['errcode']:
  284. raise CustomError(u'微信请求失败' + str(result['errcode']) + ' :' + result['errmsg'])
  285. return result
  286. @staticmethod
  287. def searchFastRegisterWXApp(name, legal_persona_wechat, legal_persona_name, component_access_token):
  288. '''查询注册企业小程序任务状态'''
  289. url = 'https://api.weixin.qq.com/cgi-bin/component/fastregisterweapp?action=search&component_access_token=' + component_access_token
  290. param = {
  291. "name": name, # 企业名
  292. "legal_persona_wechat": legal_persona_wechat, # 法人微信
  293. "legal_persona_name": legal_persona_name, # 法人姓名
  294. }
  295. result = requests.post(url, data=json.dumps(param), verify=False)
  296. result = result.json()
  297. if 'errcode' in result and result['errcode']:
  298. raise CustomError(u'微信请求失败' + str(result['errcode']) + ' :' + result['errmsg'])
  299. return result