def _get_mp_info(cls, to_user_id_list, shop_id): """获取发送人的微信openid与微信对象""" app_id = MP_APPID app_secret = MP_APPSECRET template_id = cls._default_template_id # 森果自己的微信公众号和零售共用一个 redis_conn = get_redis_connection("default") access_token = redis_conn.get("access_token") access_token = access_token.decode("utf-8") if access_token else None wechat_client = WeChatClient(appid=app_id, secret=app_secret, access_token=access_token, timeout=5) if not access_token: access_token = wechat_client.fetch_access_token() redis_conn.setex("access_token", 3600, access_token.get("access_token")) user_openid_list = list_openid_by_user_ids_and_appid( to_user_id_list, app_id) touser_list = [ user_openid.wx_openid for user_openid in user_openid_list ] return touser_list, template_id, wechat_client
def update_access_token(self): now = self._now() client = WeChatClient(self.app_id, self.app_secret) res = client.fetch_access_token() self.access_token_content = res.get('access_token') self.access_token_expires_at = now + datetime.timedelta( seconds=res.get('expires_in') - 60) self.save()
def get_user_info(self, openid=None, lang='zh_CN'): """Get user infomation :param openid: WeChat openid, optional :param access_token: WeChat OAuth2 access token, optional :param lang: Preferred language code, optional :return: JSON data """ access_token = self.access_token client = WeChatClient(self.app_id, self.app_secret) return client._get('user/info', params={ 'access_token': access_token, 'openid': openid, 'lang': lang })
def app_factory( global_config, appid, secret, configure='/var/lib/antilles/wechat_agent.yml', timeout=30, cached_timeout=3600, **local_conf ): import falcon from wechatpy.client import WeChatClient from .resource import Configure, Message app = falcon.API() client = WeChatClient( appid, secret, timeout=timeout ) app.add_route( '/config', Configure( configure, client ) ) app.add_route( '/', Message( configure, client, cached_timeout=cached_timeout ) ) return app
def get_public_code(self, app_id, app_secret, scene, page, qichang_cloud_api): if app_id and app_secret: client = WeChatClient(app_id, app_secret) try: resp = client.wxa.get_wxa_code_unlimited(scene=scene, page=page) except (Exception, ): public_code = None else: content_type = resp.headers.get("Content-Type", "") if "image" not in content_type: public_code = None else: public_code = resp.content else: store_type = BoolConfig.objects.filter(name="store_type").first() if store_type and store_type.content == "cloud": public_code = self.get_public_code_from_cloud( app_id, scene, page, qichang_cloud_api) else: public_code = None return public_code
def mp_send_template_message(app_id, touser, template_id, data, url=None, mini_program=None): """ 发送公众号模板消息 Params: app_id 是 微信应用 app_id touser 是 用户 ID 。 就是你收到的 `Message` 的 source template_id 是 模板 ID。在公众平台线上模板库中选用模板获得 data 是 模板消息数据 url 否 链接地址 mini_program 否 跳小程序所需数据, 如:`{'appid': 'appid', 'pagepath': 'index?foo=bar'}` """ if app_id not in settings.WECHAT_APP_MAP: return data = data if (data and isinstance(data, dict)) else {} try: appsecret = settings.WECHAT_APP_MAP[app_id]['appsecret'] session = RedisStorage(get_redis_connection())\ if settings.CACHES['default']['BACKEND'] == 'django_redis.cache.RedisCache'\ else MemoryStorage() client = WeChatClient(app_id, appsecret, session=session) return client.message.send_template(touser, template_id, data, url=url, mini_program=mini_program) except Exception as e: logger.error(f'mp_send_template_error:{e}')
def validate(self, data): phone, pa = data['phone'], data['phone_access'] try: access = PhoneAccess.objects.get(phone=phone, phone_access=pa) if phone != '17704818161': access.delete() except PhoneAccess.DoesNotExist: raise ValidationError('验证码错误') try: user = User.objects.get(username=phone) except User.DoesNotExist: raise ValidationError('用户不存在') code = data['code'] redis_client = Redis.from_url(getattr(settings, 'REDIS_URL')) session_interface = RedisStorage(redis_client, prefix="wechatpy") appid = getattr(settings, 'WXA_APPID') secret = getattr(settings, 'WXA_SECRET') if not appid or not secret: raise ValidationError('微信小程序未配置') wechat_client = WeChatClient(appid, secret, session=session_interface) try: wx_data = wechat_client.wxa.code_to_session(code) except WeChatClientException: raise ValidationError('code已使用') users = User.objects.exclude(username=phone).filter( wechart_oid=wx_data['openid']) if users: raise ValidationError('其它用户已绑定此微信,请更换微信号后进行绑定') user.wechart_oid = wx_data['openid'] user.save() return data
def init(self, env): dbname = env.cr.dbname global WxEnvDict if dbname in WxEnvDict: del WxEnvDict[dbname] WxEnvDict[dbname] = self Param = env['ir.config_parameter'].sudo() self.wx_token = Param.get_param('wx_token') or '' self.wx_aeskey = Param.get_param('wx_aeskey') or '' self.wx_appid = Param.get_param('wx_appid') or '' self.wx_AppSecret = Param.get_param('wx_AppSecret') or '' self.client = WeChatClient(self.wx_appid, self.wx_AppSecret) self.wxclient = self.client try: if self.wx_aeskey: self.crypto_handle = WeChatCrypto(self.wx_token, self.wx_aeskey, self.wx_appid) except: _logger.error(u'初始化微信公众号客户端实例失败,请在微信对接配置中填写好相关信息!') try: users = env['wx.user'].sudo().search([('last_uuid', '!=', None)]) for obj in users: if obj.last_uuid_time: self.recover_uuid( obj.openid, obj.last_uuid, fields.Datetime.from_string(obj.last_uuid_time)) except: env.cr.rollback() import traceback traceback.print_exc()
def init(self, env, from_ui=False): self.init_data(env) dbname = env.cr.dbname global AppEnvDict if dbname in AppEnvDict: del AppEnvDict[dbname] AppEnvDict[dbname] = self #Param = env['ir.config_parameter'].sudo() config = env['wx.app.config'].sudo().get_cur() Token = config.token AESKey = config.aeskey AppID = config.app_id AppSecret = config.secret self.client = WeChatClient(AppID, AppSecret, session=self.gen_session()) self.token = Token _logger.info('Create crypto: %s %s %s' % (Token, AESKey, AppID)) try: self.crypto_handle = WeChatCrypto(Token, AESKey, AppID) except: _logger.error(u'初始化微信小程序客户端实例失败,请在微信对接配置中填写好相关信息!') if from_ui: raise ValidationError(u'对接失败,请检查相关信息是否填写正确')
def wrap(api, app_id, app_secret=None): return api( client=WeChatClient( appid=app_id, secret=app_secret or settings.WECHAT_APP_MAP[app_id]["appsecret"], session=session, ) )
def get_access_token(): # print(1) redis_client = redis.Redis(host="127.0.0.1", port=6379, db=5) os.environ.setdefault("DJANGO_SETTINGS_MODULE", "up_down_chain.settings") # project_name 项�~[��~P~M称 django.setup() wechat_client = WeChatClient( settings.WXAPPID, settings.WXAPPSECRET, ) access_token = wechat_client.fetch_access_token()["access_token"] time.sleep(5) redis_client.setex("access_token", access_token, 7000) return "ok"
def __init__(self): self.token = "" self.get_token() self.appid = config.APP_ID self.appsecret = config.APPSECRET self.client = WeChatClient(self.appid, self.appsecret) threading.Timer(6000, self.get_token())
def createQrByDeviceId(deviceId): client = WeChatClient(API_ID, API_SECRET) res = client.device.create_qrcode([deviceId]) try: ticket = json.loads(res)["code_list"][0]["ticket"] #TODO return ticket except: return res
def customSendImage(user, filename): f = open(filename) client = WeChatClient(API_ID, API_SECRET) res = client.media.upload("image", f) f.close() data = json.loads(res) try: return client.message.send_image(user, data["media_id"]) except: return res
def __init__( self, msg, ): self.msg = msg self.path = current_app.config['CODE_PATH'], redis_client = Redis.from_url(current_app.config['REDIS_STORAGE']) session_interface = RedisStorage(redis_client, prefix="ACCESS_TOKEN") self.client = WeChatClient(current_app.config['APP_ID'], current_app.config['SECRET'], session=session_interface)
def downloadMedia(mediaId,savePath): try: wechat_client = WeChatClient(appid=APPID,secret=APPSECRET) weChat_Media = WeChatMedia(wechat_client) response = weChat_Media.download(media_id=mediaId) with open(savePath, 'wb') as fd: for chunk in response.iter_content(8096): fd.write(chunk) print("下载媒体文件成功,filePath=",savePath) except Exception as e: print('下载文件出错:',e)
def main(): wechat_client = WeChatClient(setting.WECHAT_APP_ID, setting.WECHAT_APP_SECRET) # Dirty hack bot.wechat_client = wechat_client # 注册一个新的聊天机器人 bot.register_cmd( 'TDD', CommandItem(desc='* T(dd): 使用淘逗逗2号机器人聊天', re='(?i)^t(dd)?$', method=tuling_bot(bot))) app.run(host=app.config.get('HOST'))
def jsapi_ticket(self): now = self._now() if now > self.jsapi_ticket_expires_at: client = WeChatClient(self.app_id, self.app_secret, self.access_token) res = client.jsapi.get_ticket() self.jsapi_ticket_content = res.get('ticket') self.jsapi_ticket_expires_at = now + datetime.timedelta( seconds=res.get('expires_in') - 60) self.save() return self.jsapi_ticket_content
def preview_send(self): from ..controllers import client entry = client.wxenv(self.env) wxclient = entry.wxclient wx_client = WeChatClient(wxclient.appid, wxclient.appsecret, access_token=wxclient.token) entry.init(self.env) for obj in self: res = wx_client.message.send_mass_article( obj.preview_user_id.openid, obj.wx_media_id.media_id, is_to_all=False, preview=True) _logger.info('>>> preview_send ret: %s', res)
def send_wechat_template(self, data): """ template {{first.DATA}} title1:{{keyword1.DATA}} title2:{{keyword2.DATA}} title3:{{keyword3.DATA}} {{remark.DATA}} """ if not wechat_available: result_json = {"errcode": 40002} return result_json if redis_available and self.redis != "": redis_client = Redis.from_url(self.redis) session_interface = RedisStorage(redis_client, prefix="wechatpy") wechat_client = WeChatClient(self.appid, self.secret, session=session_interface) else: wechat_client = WeChatClient(self.appid, self.secret) for user in self.users.split(","): result_json = wechat_client.message.send_template( user, self.template, data) return result_json
def mass_send(self): from ..controllers import client entry = client.wxenv(self.env) wxclient = entry.wxclient wx_client = WeChatClient(wxclient.appid, wxclient.appsecret, access_token=wxclient.token) entry.init(self.env) for obj in self: res = wx_client.message.send_mass_article(None, obj.wx_media_id.media_id, is_to_all=True, preview=False) _logger.info('>>> mass_send ret: %s', res) obj.write({'msg_id': res.get('msg_id')})
def create_menu(request): """ 自定义菜单 :param request: :return: """ client = WeChatClient(APP_ID, APP_SECRET) client.menu.create({ "button": [{ "type": "click", "name": "功能详情", "key": "func_detail" }, { "name": "每日推送", "sub_button": [{ "type": "click", "name": "每日音乐", "key": "daily_music" }, { "type": "click", "name": "每日新闻", "key": "daily_push" }, { "type": "click", "name": "每日美图", "key": "daily_image" }] }, { "name": "菜单", "sub_button": [{ "type": "view", "name": "个人博客", "url": "https://acczmt.top" }, { "type": "view", "name": "Github", "url": "https://github.com/accZMT" }, { "type": "click", "name": "关注我", "key": "V1001_GOOD" }] }] }) return HttpResponse("ok")
def upload_articles(self, articless, name): from ..controllers import client entry = client.wxenv(self.env) wxclient = entry.wxclient wx_client = WeChatClient(wxclient.appid, wxclient.appsecret, access_token=wxclient.token) wx_file_path = get_module_resource('wx_tools', 'static/wx') news_up = wx_client.media.upload_articles(articless) if news_up: news_up['update_time'] = news_up["created_at"] news_up['name'] = name news_up['media_type'] = 'news' news_up['source_type'] = 'ARTICLE' obj = self.create(news_up) return news_up
def validate(self, data): code = data['code'] redis_client = Redis.from_url(getattr(settings, 'REDIS_URL')) session_interface = RedisStorage(redis_client, prefix="wechatpy") appid = getattr(settings, 'WXA_APPID') secret = getattr(settings, 'WXA_SECRET') if not appid or not secret: raise ValidationError('微信小程序未配置') wechat_client = WeChatClient(appid, secret, session=session_interface) try: data = wechat_client.wxa.code_to_session(code) except WeChatClientException: raise ValidationError('code已使用') try: User.objects.get(wechart_oid=data['openid']) except User.DoesNotExist: raise ValidationError('用户不存在') return data
def init(self, env, from_ui=False): self.init_data(env) dbname = env.cr.dbname global WxEnvDict if dbname in WxEnvDict: del WxEnvDict[dbname] WxEnvDict[dbname] = self config = env['wx.config'].sudo().get_cur() self.wx_token = config.wx_token self.wx_aeskey = config.wx_aeskey self.wx_appid = config.wx_appid self.wx_AppSecret = config.wx_AppSecret if config.action: self.subscribe_auto_msg = config.action.get_wx_reply() self.client = WeChatClient(self.wx_appid, self.wx_AppSecret, session=self.gen_session()) self.wxclient = self.client try: if self.wx_aeskey: self.crypto_handle = WeChatCrypto(self.wx_token, self.wx_aeskey, self.wx_appid) except: _logger.error(u'初始化微信公众号客户端实例失败,请在微信对接配置中填写好相关信息!') if from_ui: raise ValidationError(u'对接失败,请检查相关信息是否填写正确') if config.action: self.subscribe_auto_msg = config.action.get_wx_reply() try: users = env['wx.user'].sudo().search([('last_uuid','!=',None)]) for obj in users: if obj.last_uuid_time: self.recover_uuid(obj.openid, obj.last_uuid, fields.Datetime.from_string(obj.last_uuid_time)) except: env.cr.rollback() import traceback;traceback.print_exc() print('wx client init: %s %s'%(self.OPENID_UUID, self.UUID_OPENID))
def add_material(request): if request.method == "GET": return render(request, 'add_media.html') if request.method == "POST": # 上传临时素材并且存入数据库, 注意上穿的图片名字不能是中文 media_type = request.POST.get("media_type", "") media_file = request.FILES.get("media_file") title = request.POST.get("title", "") introduction = request.POST.get("introduction", "") # 主要作用获取access_token client = WeChatClient(APP_ID, APP_SECRET) from wechatpy.client.api import WeChatMedia media = WeChatMedia(client) info = media.upload(media_type, media_file) material = MaterialModel() material.media_type = media_type material.title = title material.introduction = introduction material.media_id = info["media_id"] material.save() return HttpResponse("OK")
def add_permanent_material(request): """ 上传永久素材 :param request: :return: """ media_type = request.POST.get("media_type", "") media_file = request.FILES.get("media_file") title = request.POST.get("title", "") introduction = request.POST.get("introduction", "") client = WeChatClient(APP_ID, APP_SECRET) from wechatpy.client.api import WeChatMaterial mater = WeChatMaterial(client) info = mater.add(media_type, media_file, title, introduction) print(info) """ {'media_id': 'mHTllUWQjRS27E5rctmlCAqaV-sXOTgvpGx7ST8h2m4', 'url': 'http://mmbiz.qpic.cn/mmbiz_jpg/iap38Z2kZ6R4giciaKIWR9LdXXO3JL1eVjecQECB1nCO3EA9jEQjFUuDJYaJn0VFpDunaKSibePiafUmgqniaJlkUciaA/0?wx_fmt=jpeg'} """ return HttpResponse("OK")
def init(self, env): dbname = env.cr.dbname global AppEnvDict if dbname in AppEnvDict: del AppEnvDict[dbname] AppEnvDict[dbname] = self #Param = env['ir.config_parameter'].sudo() config = env['wx.app.config'].sudo().get_cur() Token = config.token AESKey = config.aeskey AppID = config.app_id AppSecret = config.secret self.client = WeChatClient(AppID, AppSecret) self.token = Token _logger.info('Create crypto: %s %s %s' % (Token, AESKey, AppID)) try: self.crypto_handle = WeChatCrypto(Token, AESKey, AppID) except: _logger.error(u'初始化微信小程序客户端实例失败,请在微信对接配置中填写好相关信息!')
def POST(self): try: xml = web.data() msg = parse_message(xml) if msg.type == 'text': content = msg.content if content.startswith(('表情包:', '表情包:')): words = ''.join(content.replace(':', ':').split(':')[1:]) wechat_client = WeChatClient( appid='wx19a2591b2a719add', secret='c46fa65dbc2803b90431fbf9c803cbd4', ) access_token = wechat_client.access_token json_data = pics.upload_pic(pics.get_random_pic(words), access_token) # print(json_data) if 'errcode' not in json_data: media_id = json_data['media_id'] reply = ImageReply(message=msg) reply.media_id = media_id # print(web.url() + ' get_pic. words: ' + words + ' return: ' + str(json_data)) logger.info(web.url() + ' get_pic. words: ' + words + ' return: ' + str(json_data)) else: reply = TextReply(message=msg) reply.content = json_data['link'] logger.warning(web.url() + ' get_pic faild,return link. words:' + words + ' return: ' + json_data['link']) elif content.startswith(('影视:', '影视:')): words = ''.join(content.replace(':', ':').split(':')[1:]) if words == '': string = '没有输入要搜索的名字!' logger.info(web.url() + ' get_movie without words') else: data = search(words) data1 = data[0] data2 = data[1] if len(data1) != 0: string = '' if len(data1) <= 12: for each in data1: string += '%s %s %s %s\n' % (each[0], each[1], each[3], each[4]) else: for each in data1[:12]: string += '%s %s %s %s\n' % (each[0], each[1], each[3], each[4]) elif len(data2) != 0: string = '' if len(data2) <= 12: for each in data2: string += '%s %s %s %s\n' % (each[0], each[1], each[3], each[4]) else: for each in data2[:12]: string += '%s %s %s %s\n' % (each[0], each[1], each[3], each[4]) else: string = '竟然没有搜索到!!!\n请检查名称输入的是否正确,请尽量使用中文哦' # print(web.url() + ' get_pic. words: ' + words + ' data: ' + str(data) + ' return: ' + string) logger.info(web.url() + ' get_movie. words: ' + words + ' data: ' + str(data) + ' return: ' + string) reply = TextReply(message=msg) reply.content = string elif content.startswith(('在线:', '在线:')): words = ''.join(content.replace(':', ':').split(':')[1:]) if words == '': string = '没有输入要搜索的名字!' logger.info(web.url() + ' see_movie without words') else: data = get_link(words) if data: string = data else: string = '竟然没有搜索到!!!\n请检查名称输入的是否正确,请试试英文名哦' # print(web.url() + ' see_pic. words: ' + words + ' data: ' + str(data) + ' return: ' + string) logger.info(web.url() + ' see_movie. words: ' + words + ' data: ' + str(data) + ' return: ' + string) reply = TextReply(message=msg) reply.content = string else: reply = TextReply(message=msg) response = get_response(content) logger.info(web.url() + ' turing. words: ' + content + ' response: ' + response) reply.content = response elif msg.type == 'event' and msg.event: mscontent = msg.event if mscontent == "subscribe": string = '终于等到你!欢迎关注Snoopy同学~\n' \ '输入"表情包:xxx"获取自定义文字的表情\n' \ '输入"影视:xxx"获取电影的网盘链接\n' \ '输入"在线:xxx"获取在线观看视频的链接,需要复制到浏览器使用哦~' reply = TextReply(message=msg) reply.content = string elif mscontent == "unsubscribe": string = '有什么不足之处还请谅解,我会慢慢改进,欢迎您以后再来' reply = TextReply(message=msg) reply.content = string # 转换成 XML reply_xml = reply.render() return reply_xml except Exception as e: logger.error(e) # print(e) return "success"
# -*- coding:utf-8 -*- import logging from wechatpy.client import WeChatClient import sys reload(sys) sys.setdefaultencoding('utf8') logger = logging.getLogger('myapp') AppID = 'wxad25526b9589c4c9' AppSecret = '27b5ffa5802f8664ff0c38eefe6983c5' client = WeChatClient(appid=AppID, secret=AppSecret) def fun(user_id): logger.info('action') user = client.user.get(user_id) logger.info(user) menu = client.menu.get() logger.info(menu) client.message.send_text('user_id', 'content') def register_user(user_id): user = client.user.get(user_id) logger.info(user['city']) """ {u'province': u'\u6e56\u5357',