wechat.py 15 KB

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