wechat.py 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252
  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. class WeChat(object):
  8. @staticmethod
  9. def getPreAuthCode(component_appid, component_access_token):
  10. """
  11. 第三方平台 获得预授权码
  12. 结果{"pre_auth_code": "Cx_Dk6qiBE0Dmx4EmlT3oRfArPvwSQ-oa3NL_fwHM7VI08r52wazoZX2Rhpz1dEw", "expires_in": 600}
  13. """
  14. url = 'https://api.weixin.qq.com/cgi-bin/component/api_create_preauthcode?component_access_token=' + component_access_token
  15. param = {
  16. 'component_appid': component_appid,
  17. }
  18. result = requests.post(url, data=json.dumps(param))
  19. result = result.json()
  20. if 'errcode' in result and result['errcode']:
  21. raise CustomError(u'微信请求失败' + str(result['errcode']) + ' :' + result['errmsg'])
  22. return result
  23. @staticmethod
  24. def getComponentAccessToken(component_appid, component_appsecret, component_verify_ticket):
  25. """第三方平台 获得access_token"""
  26. url = 'https://api.weixin.qq.com/cgi-bin/component/api_component_token'
  27. param = {
  28. 'component_appid': component_appid,
  29. 'component_appsecret': component_appsecret,
  30. 'component_verify_ticket': component_verify_ticket
  31. }
  32. result = requests.post(url, data=json.dumps(param))
  33. result = result.json()
  34. if 'errcode' in result and result['errcode']:
  35. raise CustomError(u'微信请求失败'+ str(result['errcode']) + ' :' + result['errmsg'])
  36. return result
  37. @staticmethod
  38. def getAuthorizationInfo(component_appid, authorization_code, component_access_token):
  39. """第三方平台 获得授权信息"""
  40. url = 'https://api.weixin.qq.com/cgi-bin/component/api_query_auth?component_access_token=' + component_access_token
  41. param = {
  42. 'component_appid': component_appid,
  43. 'authorization_code': authorization_code,
  44. }
  45. result = requests.post(url, data=json.dumps(param))
  46. result = result.json()
  47. if 'errcode' in result and result['errcode']:
  48. raise CustomError(u'微信请求失败'+ str(result['errcode']) + ' :' + result['errmsg'])
  49. return result
  50. @staticmethod
  51. def getAuthorizerInfo(component_appid, authorizer_appid, component_access_token):
  52. """第三方平台 获得授权方信息"""
  53. url = 'https://api.weixin.qq.com/cgi-bin/component/api_get_authorizer_info?component_access_token=' + component_access_token
  54. param = {
  55. 'component_appid': component_appid,
  56. 'authorizer_appid': authorizer_appid,
  57. }
  58. result = requests.post(url, data=json.dumps(param))
  59. result = result.json()
  60. if 'errcode' in result and result['errcode']:
  61. raise CustomError(u'微信请求失败'+ str(result['errcode']) + ' :' + result['errmsg'])
  62. return result
  63. @staticmethod
  64. def getAuthorizerAccessToken(component_appid, authorizer_appid, authorizer_refresh_token, component_access_token):
  65. """第三方平台 获得授权方 access_token"""
  66. url = 'https://api.weixin.qq.com/cgi-bin/component/api_authorizer_token?component_access_token=' + component_access_token
  67. param = {
  68. 'component_appid': component_appid,
  69. 'authorizer_appid': authorizer_appid,
  70. 'authorizer_refresh_token': authorizer_refresh_token
  71. }
  72. result = requests.post(url, data=json.dumps(param))
  73. result = result.json()
  74. if 'errcode' in result and result['errcode']:
  75. raise CustomError(u'微信请求失败'+ str(result['errcode']) + ' :' + result['errmsg'])
  76. return result
  77. @staticmethod
  78. def getCodeTemplateList(component_access_token):
  79. '''获取代码模版列表'''
  80. url = 'https://api.weixin.qq.com/wxa/gettemplatelist?access_token=' + component_access_token
  81. result = requests.get(url)
  82. result = result.json()
  83. if 'errcode' in result and result['errcode']:
  84. raise CustomError(u'微信请求失败'+ str(result['errcode']) + ' :' + result['errmsg'])
  85. return result['template_list']
  86. @staticmethod
  87. def commitCode(access_token, template_id, user_version, user_desc):
  88. '''小程序提交代码'''
  89. url = 'https://api.weixin.qq.com/wxa/commit?access_token=' + access_token
  90. param = {
  91. 'template_id': template_id,
  92. 'ext_json': "{\"extEnable\": false,\"extAppid\": \"\"}",
  93. 'user_version': user_version,
  94. 'user_desc': 'test'
  95. }
  96. result = requests.post(url, data=json.dumps(param))
  97. result = result.json()
  98. if 'errcode' in result and result['errcode']:
  99. raise CustomError(u'微信请求失败'+ str(result['errcode']) + ' :' + result['errmsg'])
  100. return result
  101. @staticmethod
  102. def submitAuditCode(access_token):
  103. '''将上传的代码提交审核'''
  104. url = 'https://api.weixin.qq.com/wxa/submit_audit?access_token=' + access_token
  105. result = requests.post(url)
  106. result = result.json()
  107. if 'errcode' in result and result['errcode']:
  108. raise CustomError(u'微信请求失败' + str(result['errcode']) + ' :' + result['errmsg'])
  109. return result
  110. @staticmethod
  111. def getLastSubmitAuditCodeStatus(access_token):
  112. '''查询最新一次提交审核代码的审核状态'''
  113. url = 'https://api.weixin.qq.com/wxa/get_latest_auditstatus?access_token=' + access_token
  114. result = requests.get(url)
  115. result = result.json()
  116. if 'errcode' in result and result['errcode']:
  117. raise CustomError(u'微信请求失败' + str(result['errcode']) + ' :' + result['errmsg'])
  118. return result
  119. @staticmethod
  120. def modify_domain(access_token, action, requestdomain, wsrequestdomain, uploaddomain, downloaddomain):
  121. '''设置小程序服务器域名'''
  122. url = 'https://api.weixin.qq.com/wxa/modify_domain?access_token=' + access_token
  123. param = {
  124. "action": action,
  125. "requestdomain": requestdomain,
  126. "wsrequestdomain": wsrequestdomain,
  127. "uploaddomain": uploaddomain,
  128. "downloaddomain": downloaddomain
  129. }
  130. result = requests.post(url, data=json.dumps(param))
  131. result = result.json()
  132. if 'errcode' in result and result['errcode']:
  133. raise CustomError(u'微信请求失败' + str(result['errcode']) + ' :' + result['errmsg'])
  134. return result
  135. @staticmethod
  136. def code2Session(appid, secret, code):
  137. '''登录凭证校验'''
  138. url = 'https://api.weixin.qq.com/sns/jscode2session?appid='+ appid + '&secret=' + secret + '&js_code=' + code + '&grant_type=authorization_code'
  139. result = requests.get(url)
  140. result = result.json()
  141. if 'errcode' in result and result['errcode']:
  142. raise CustomError(u'微信请求失败' + str(result['errcode']) + ':' + result['errmsg'])
  143. return result
  144. @staticmethod
  145. def addPlugin(access_token):
  146. '''小程序插件管理'''
  147. url = 'https://api.weixin.qq.com/wxa/plugin?access_token=' + access_token
  148. param = {
  149. 'action': 'apply',
  150. 'plugin_appid': 'wxfa43a4a7041a84de'
  151. }
  152. result = requests.post(url, data=json.dumps(param))
  153. result = result.json()
  154. if 'errcode' in result and result['errcode'] and str(result['errcode']) != '89237':
  155. raise CustomError(u'微信请求失败' + str(result['errcode']) + ':' + result['errmsg'])
  156. return result
  157. @staticmethod
  158. def getTemplateList(access_token):
  159. '''获取当前帐号下的个人模板列表'''
  160. url = 'https://api.weixin.qq.com/wxaapi/newtmpl/gettemplate?access_token=' + access_token
  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['data']
  166. @staticmethod
  167. def sendSubscribeMessage(access_token, openid, template_id, page, data):
  168. '''发送订阅消息'''
  169. url = 'https://api.weixin.qq.com/cgi-bin/message/subscribe/send?access_token=' + access_token
  170. param = {
  171. 'touser': openid,
  172. 'template_id': template_id,
  173. 'page': page,
  174. 'data': data
  175. }
  176. result = requests.post(url, data=json.dumps(param))
  177. #print('-------------------------')
  178. #result = result.json()
  179. #print(result)
  180. #result = requests.post(url, data=json.dumps(param))
  181. #result = result.json()
  182. #if 'errcode' in result and result['errcode'] and str(result['errcode']) != '89237':
  183. # raise CustomError(u'微信请求失败' + str(result['errcode']) + ':' + result['errmsg'])
  184. #return result
  185. @staticmethod
  186. def releaseCode(access_token):
  187. '''已审核代码发布'''
  188. url = 'https://api.weixin.qq.com/wxa/release?access_token=' + access_token
  189. result = requests.post(url, data=json.dumps({}))
  190. result = result.json()
  191. if 'errcode' in result and result['errcode']:
  192. raise CustomError(u'微信请求失败' + str(result['errcode']) + ' :' + result['errmsg'])
  193. return result
  194. @staticmethod
  195. def getWXAppCode(access_token, page, activity_id):
  196. '''获取小程序二维码'''
  197. url = 'https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token={}'.format(access_token)
  198. data = {"scene": "id=%s" % activity_id,
  199. # "width": 1280, # 默认430
  200. 'page': page,
  201. "line_color": {"r": 43, "g": 162, "b": 69}, # 自定义颜色
  202. "is_hyaline": True}
  203. result = requests.post(url, json=data)
  204. # print('-------------------------',result)
  205. upload_path = PathAndRename("activity/")
  206. filename = "%s%s.png" % (
  207. upload_path.path,
  208. activity_id,
  209. )
  210. filename = filename.lower()
  211. full_filename = "%s%s" % (settings.MEDIA_ROOT, filename)
  212. with open(full_filename, 'wb') as destination:
  213. destination.write(result.content)
  214. return filename