# coding=utf-8 import requests import json from django.conf import settings from util.exceptions import CustomError from util.file_operation import PathAndRename from django.utils import timezone class WeChat(object): @staticmethod def checkAppid(appid): if not appid: raise CustomError(u'未找到相应的小程序!') if appid != settings.APPID: raise CustomError(u'未找到相应的小程序!') @staticmethod def getPreAuthCode(component_appid, component_access_token): """ 第三方平台 获得预授权码 结果{"pre_auth_code": "Cx_Dk6qiBE0Dmx4EmlT3oRfArPvwSQ-oa3NL_fwHM7VI08r52wazoZX2Rhpz1dEw", "expires_in": 600} """ url = 'https://api.weixin.qq.com/cgi-bin/component/api_create_preauthcode?component_access_token=' + component_access_token param = { 'component_appid': component_appid, } result = requests.post(url, data=json.dumps(param)) result = result.json() if 'errcode' in result and result['errcode']: raise CustomError(u'微信请求失败' + str(result['errcode']) + ' :' + result['errmsg']) return result @staticmethod def getComponentAccessToken(component_appid, component_appsecret, component_verify_ticket): """第三方平台 获得access_token""" url = 'https://api.weixin.qq.com/cgi-bin/component/api_component_token' param = { 'component_appid': component_appid, 'component_appsecret': component_appsecret, 'component_verify_ticket': component_verify_ticket } result = requests.post(url, data=json.dumps(param)) result = result.json() if 'errcode' in result and result['errcode']: raise CustomError(u'微信请求失败'+ str(result['errcode']) + ' :' + result['errmsg']) return result @staticmethod def getAuthorizationInfo(component_appid, authorization_code, component_access_token): """第三方平台 获得授权信息""" url = 'https://api.weixin.qq.com/cgi-bin/component/api_query_auth?component_access_token=' + component_access_token param = { 'component_appid': component_appid, 'authorization_code': authorization_code, } result = requests.post(url, data=json.dumps(param)) result = result.json() if 'errcode' in result and result['errcode']: raise CustomError(u'微信请求失败'+ str(result['errcode']) + ' :' + result['errmsg']) return result @staticmethod def getAuthorizerInfo(component_appid, authorizer_appid, component_access_token): """第三方平台 获得授权方信息""" url = 'https://api.weixin.qq.com/cgi-bin/component/api_get_authorizer_info?component_access_token=' + component_access_token param = { 'component_appid': component_appid, 'authorizer_appid': authorizer_appid, } result = requests.post(url, data=json.dumps(param)) result = result.json() if 'errcode' in result and result['errcode']: raise CustomError(u'微信请求失败'+ str(result['errcode']) + ' :' + result['errmsg']) return result @staticmethod def getAuthorizerAccessToken(component_appid, authorizer_appid, authorizer_refresh_token, component_access_token): """第三方平台 获得授权方 access_token""" url = 'https://api.weixin.qq.com/cgi-bin/component/api_authorizer_token?component_access_token=' + component_access_token param = { 'component_appid': component_appid, 'authorizer_appid': authorizer_appid, 'authorizer_refresh_token': authorizer_refresh_token } result = requests.post(url, data=json.dumps(param)) result = result.json() if 'errcode' in result and result['errcode']: raise CustomError(u'微信请求失败'+ str(result['errcode']) + ' :' + result['errmsg']) return result @staticmethod def getCodeTemplateList(component_access_token): '''获取代码模版列表''' url = 'https://api.weixin.qq.com/wxa/gettemplatelist?access_token=' + component_access_token result = requests.get(url) result = result.json() if 'errcode' in result and result['errcode']: raise CustomError(u'微信请求失败'+ str(result['errcode']) + ' :' + result['errmsg']) return result['template_list'] @staticmethod def getDraftTemplateList(component_access_token): '''获取草稿箱列表''' url = 'https://api.weixin.qq.com/wxa/gettemplatedraftlist?access_token=' + component_access_token result = requests.get(url) result = result.json() if 'errcode' in result and result['errcode']: raise CustomError(u'微信请求失败'+ str(result['errcode']) + ' :' + result['errmsg']) return result['draft_list'] @staticmethod def addToemplate(component_access_token, draft_id): '''上传草稿到标准模板''' url = 'https://api.weixin.qq.com/wxa/addtotemplate?access_token=' + component_access_token param = { 'draft_id': draft_id, } result = requests.post(url, data=json.dumps(param)) result = result.json() if 'errcode' in result and result['errcode']: raise CustomError(u'微信请求失败'+ str(result['errcode']) + ' :' + result['errmsg']) return result @staticmethod def commitCode(access_token, template_id, user_version, user_desc): '''小程序提交代码''' url = 'https://api.weixin.qq.com/wxa/commit?access_token=' + access_token param = { 'template_id': template_id, 'ext_json': "{\"extEnable\": false,\"extAppid\": \"\"}", 'user_version': user_version, 'user_desc': 'test' } result = requests.post(url, data=json.dumps(param)) result = result.json() if 'errcode' in result and result['errcode']: raise CustomError(u'微信请求失败'+ str(result['errcode']) + ' :' + result['errmsg']) return result @staticmethod def submitAuditCode(access_token): '''将上传的代码提交审核''' url = 'https://api.weixin.qq.com/wxa/submit_audit?access_token=' + access_token result = requests.post(url) result = result.json() if 'errcode' in result and result['errcode']: raise CustomError(u'微信请求失败' + str(result['errcode']) + ' :' + result['errmsg']) return result @staticmethod def getLastSubmitAuditCodeStatus(access_token): '''查询最新一次提交审核代码的审核状态''' url = 'https://api.weixin.qq.com/wxa/get_latest_auditstatus?access_token=' + access_token result = requests.get(url) result = result.json() if 'errcode' in result and result['errcode']: raise CustomError(u'微信请求失败' + str(result['errcode']) + ' :' + result['errmsg']) return result @staticmethod def modify_domain(access_token, action, requestdomain, wsrequestdomain, uploaddomain, downloaddomain): '''设置小程序服务器域名''' url = 'https://api.weixin.qq.com/wxa/modify_domain?access_token=' + access_token param = { "action": action, "requestdomain": requestdomain, "wsrequestdomain": wsrequestdomain, "uploaddomain": uploaddomain, "downloaddomain": downloaddomain } result = requests.post(url, data=json.dumps(param)) result = result.json() if 'errcode' in result and result['errcode']: raise CustomError(u'微信请求失败' + str(result['errcode']) + ' :' + result['errmsg']) return result @staticmethod def code2Session(appid, secret, code): '''登录凭证校验''' url = 'https://api.weixin.qq.com/sns/jscode2session?appid='+ appid + '&secret=' + secret + '&js_code=' + code + '&grant_type=authorization_code' result = requests.get(url) result = result.json() if 'errcode' in result and result['errcode']: raise CustomError(u'微信请求失败' + str(result['errcode']) + ':' + result['errmsg']) return result @staticmethod def getAccessToken(appid, secret,): '''获取小程序验证token''' url = 'https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid='+ appid + '&secret=' + secret result = requests.get(url) result = result.json() if 'errcode' in result and result['errcode']: raise CustomError(u'微信请求失败' + str(result['errcode']) + ':' + result['errmsg']) return result @staticmethod def addPlugin(access_token): '''小程序插件管理''' url = 'https://api.weixin.qq.com/wxa/plugin?access_token=' + access_token param = { 'action': 'apply', 'plugin_appid': 'wxfa43a4a7041a84de' } result = requests.post(url, data=json.dumps(param)) result = result.json() if 'errcode' in result and result['errcode'] and str(result['errcode']) != '89237': raise CustomError(u'微信请求失败' + str(result['errcode']) + ':' + result['errmsg']) return result @staticmethod def getTemplateList(access_token): '''获取当前帐号下的个人模板列表''' url = 'https://api.weixin.qq.com/wxaapi/newtmpl/gettemplate?access_token=' + access_token result = requests.get(url) result = result.json() if 'errcode' in result and result['errcode']: raise CustomError(u'微信请求失败' + str(result['errcode']) + ':' + result['errmsg']) return result['data'] @staticmethod def sendSubscribeMessage(access_token, openid, template_id, page, data): '''发送订阅消息''' url = 'https://api.weixin.qq.com/cgi-bin/message/subscribe/send?access_token=' + access_token param = { 'touser': openid, 'template_id': template_id, 'page': page, 'data': data } print(9999999,param) result = requests.post(url, data=json.dumps(param)) print('-------------------------') result = result.json() print(result) #result = requests.post(url, data=json.dumps(param)) #result = result.json() #if 'errcode' in result and result['errcode'] and str(result['errcode']) != '89237': # raise CustomError(u'微信请求失败' + str(result['errcode']) + ':' + result['errmsg']) #return result @staticmethod def getWXAppCode(access_token, page, param): '''获取小程序二维码''' url = 'https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token={}'.format(access_token) data = {"scene": "{}".format(param), # "width": 1280, # 默认430 "line_color": {"r": 43, "g": 162, "b": 69}, # 自定义颜色 "is_hyaline": True} result = requests.post(url, json=data) # print('-------------------------',result) upload_path = PathAndRename("wx_code/") filename = "%s%s.png" % ( upload_path.path, timezone.now().strftime('%Y%m%d%H%M%S%f'), ) filename = filename.lower() full_filename = "%s%s" % (settings.MEDIA_ROOT, filename) with open(full_filename, 'wb') as destination: destination.write(result.content) return filename @staticmethod def getCommodityCode(access_token, page, commodity_id, company_no): '''获取商品二维码''' url = 'https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token={}'.format(access_token) data = {"scene": "company_no={}&device_id={}".format(company_no, commodity_id), # "width": 1280, # 默认430 "line_color": {"r": 43, "g": 162, "b": 69}, # 自定义颜色 "is_hyaline": True} result = requests.post(url, json=data) upload_path = PathAndRename("device/") filename = "%s%s.png" % ( upload_path.path, commodity_id, ) filename = filename.lower() full_filename = "%s%s" % (settings.MEDIA_ROOT, filename) with open(full_filename, 'wb') as destination: destination.write(result.content) return filename @staticmethod def releaseCode(access_token): '''已审核代码发布''' url = 'https://api.weixin.qq.com/wxa/release?access_token=' + access_token result = requests.post(url, data=json.dumps({})) result = result.json() if 'errcode' in result and result['errcode']: raise CustomError(u'微信请求失败' + str(result['errcode']) + ' :' + result['errmsg']) return result @staticmethod def createFastRegisterWXApp(name, code, code_type, legal_persona_wechat, legal_persona_name, component_phone, component_access_token): '''快速注册企业小程序''' url = 'https://api.weixin.qq.com/cgi-bin/component/fastregisterweapp?action=create&component_access_token=' + component_access_token param = { "name": name, # 企业名 "code": code, # 企业代码 "code_type": code_type, # 企业代码类型(1:统一社会信用代码, 2:组织机构代码,3:营业执照注册号) "legal_persona_wechat": legal_persona_wechat, # 法人微信 "legal_persona_name": legal_persona_name, # 法人姓名 "component_phone": component_phone, #第三方联系电话 } result = requests.post(url, data=json.dumps(param)) result = result.json() if 'errcode' in result and result['errcode']: raise CustomError(u'微信请求失败' + str(result['errcode']) + ' :' + result['errmsg']) return result @staticmethod def searchFastRegisterWXApp(name, legal_persona_wechat, legal_persona_name, component_access_token): '''查询注册企业小程序任务状态''' url = 'https://api.weixin.qq.com/cgi-bin/component/fastregisterweapp?action=search&component_access_token=' + component_access_token param = { "name": name, # 企业名 "legal_persona_wechat": legal_persona_wechat, # 法人微信 "legal_persona_name": legal_persona_name, # 法人姓名 } result = requests.post(url, data=json.dumps(param)) result = result.json() if 'errcode' in result and result['errcode']: raise CustomError(u'微信请求失败' + str(result['errcode']) + ' :' + result['errmsg']) return result