wechat.py 15 KB

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