wechat.py 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255
  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 code2Session(appid, secret, code):
  10. '''登录凭证校验'''
  11. url = 'https://api.weixin.qq.com/sns/jscode2session?appid=' + appid + '&secret=' + secret + '&js_code=' + code + '&grant_type=authorization_code'
  12. result = requests.get(url)
  13. result = result.json()
  14. if 'errcode' in result and result['errcode']:
  15. raise CustomError(u'微信请求失败' + str(result['errcode']) + ':' + result['errmsg'])
  16. return result
  17. @staticmethod
  18. def getPreAuthCode(component_appid, component_access_token):
  19. """
  20. 第三方平台 获得预授权码
  21. 结果{"pre_auth_code": "Cx_Dk6qiBE0Dmx4EmlT3oRfArPvwSQ-oa3NL_fwHM7VI08r52wazoZX2Rhpz1dEw", "expires_in": 600}
  22. """
  23. url = 'https://api.weixin.qq.com/cgi-bin/component/api_create_preauthcode?component_access_token=' + component_access_token
  24. param = {
  25. 'component_appid': component_appid,
  26. }
  27. result = requests.post(url, data=json.dumps(param))
  28. result = result.json()
  29. if 'errcode' in result and result['errcode']:
  30. raise CustomError(u'微信请求失败' + str(result['errcode']) + ' :' + result['errmsg'])
  31. return result
  32. @staticmethod
  33. def getComponentAccessToken(component_appid, component_appsecret, component_verify_ticket):
  34. """第三方平台 获得access_token"""
  35. url = 'https://api.weixin.qq.com/cgi-bin/component/api_component_token'
  36. param = {
  37. 'component_appid': component_appid,
  38. 'component_appsecret': component_appsecret,
  39. 'component_verify_ticket': component_verify_ticket
  40. }
  41. result = requests.post(url, data=json.dumps(param))
  42. result = result.json()
  43. if 'errcode' in result and result['errcode']:
  44. raise CustomError(u'微信请求失败'+ str(result['errcode']) + ' :' + result['errmsg'])
  45. return result
  46. @staticmethod
  47. def getAuthorizationInfo(component_appid, authorization_code, component_access_token):
  48. """第三方平台 获得授权信息"""
  49. url = 'https://api.weixin.qq.com/cgi-bin/component/api_query_auth?component_access_token=' + component_access_token
  50. param = {
  51. 'component_appid': component_appid,
  52. 'authorization_code': authorization_code,
  53. }
  54. result = requests.post(url, data=json.dumps(param))
  55. result = result.json()
  56. if 'errcode' in result and result['errcode']:
  57. raise CustomError(u'微信请求失败'+ str(result['errcode']) + ' :' + result['errmsg'])
  58. return result
  59. @staticmethod
  60. def getAuthorizerInfo(component_appid, authorizer_appid, component_access_token):
  61. """第三方平台 获得授权方信息"""
  62. url = 'https://api.weixin.qq.com/cgi-bin/component/api_get_authorizer_info?component_access_token=' + component_access_token
  63. param = {
  64. 'component_appid': component_appid,
  65. 'authorizer_appid': authorizer_appid,
  66. }
  67. result = requests.post(url, data=json.dumps(param))
  68. result = result.json()
  69. if 'errcode' in result and result['errcode']:
  70. raise CustomError(u'微信请求失败'+ str(result['errcode']) + ' :' + result['errmsg'])
  71. return result
  72. @staticmethod
  73. def getAuthorizerAccessToken(component_appid, authorizer_appid, authorizer_refresh_token, component_access_token):
  74. """第三方平台 获得授权方 access_token"""
  75. url = 'https://api.weixin.qq.com/cgi-bin/component/api_authorizer_token?component_access_token=' + component_access_token
  76. param = {
  77. 'component_appid': component_appid,
  78. 'authorizer_appid': authorizer_appid,
  79. 'authorizer_refresh_token': authorizer_refresh_token
  80. }
  81. result = requests.post(url, data=json.dumps(param))
  82. result = result.json()
  83. if 'errcode' in result and result['errcode']:
  84. raise CustomError(u'微信请求失败'+ str(result['errcode']) + ' :' + result['errmsg'])
  85. return result
  86. @staticmethod
  87. def getCodeTemplateList(component_access_token):
  88. '''获取代码模版列表'''
  89. url = 'https://api.weixin.qq.com/wxa/gettemplatelist?access_token=' + component_access_token
  90. result = requests.get(url)
  91. result = result.json()
  92. if 'errcode' in result and result['errcode']:
  93. raise CustomError(u'微信请求失败'+ str(result['errcode']) + ' :' + result['errmsg'])
  94. return result['template_list']
  95. @staticmethod
  96. def commitCode(access_token, template_id, user_version, user_desc):
  97. '''小程序提交代码'''
  98. url = 'https://api.weixin.qq.com/wxa/commit?access_token=' + access_token
  99. param = {
  100. 'template_id': template_id,
  101. 'ext_json': "{\"extEnable\": false,\"extAppid\": \"\"}",
  102. 'user_version': user_version,
  103. 'user_desc': 'test'
  104. }
  105. result = requests.post(url, data=json.dumps(param))
  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 submitAuditCode(access_token):
  112. '''将上传的代码提交审核'''
  113. url = 'https://api.weixin.qq.com/wxa/submit_audit?access_token=' + access_token
  114. result = requests.post(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 getLastSubmitAuditCodeStatus(access_token):
  121. '''查询最新一次提交审核代码的审核状态'''
  122. url = 'https://api.weixin.qq.com/wxa/get_latest_auditstatus?access_token=' + access_token
  123. result = requests.get(url)
  124. result = result.json()
  125. if 'errcode' in result and result['errcode']:
  126. raise CustomError(u'微信请求失败' + str(result['errcode']) + ' :' + result['errmsg'])
  127. return result
  128. @staticmethod
  129. def modify_domain(access_token, action, requestdomain, wsrequestdomain, uploaddomain, downloaddomain):
  130. '''设置小程序服务器域名'''
  131. url = 'https://api.weixin.qq.com/wxa/modify_domain?access_token=' + access_token
  132. param = {
  133. "action": action,
  134. "requestdomain": requestdomain,
  135. "wsrequestdomain": wsrequestdomain,
  136. "uploaddomain": uploaddomain,
  137. "downloaddomain": downloaddomain
  138. }
  139. result = requests.post(url, data=json.dumps(param))
  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