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_session(self, config): if config['WECHAT_SESSION_TYPE'] == 'redis': from wechatpy.session.redisstorage import RedisStorage from redis import Redis if config.get('WECHAT_SESSION_REDIS_URL'): redis = Redis.from_url(config['WECHAT_SESSION_REDIS_URL']) else: redis = Redis(host=config.get('WECHAT_SESSION_REDIS_HOST', 'localhost'), port=config.get('WECHAT_SESSION_REDIS_PORT', 6379), db=config.get('WECHAT_SESSION_REDIS_DB', 0), password=config.get('WECHAT_SESSION_REDIS_PASS', None)) prefix = config['WECHAT_SESSION_PREFIX'] self._redis_prefix = prefix self._redis = redis session_interface = RedisStorage(redis, prefix=prefix) elif config['WECHAT_SESSION_TYPE'] == 'memcached': from wechatpy.session.memcachedstorage import MemcachedStorage mc = self._get_mc_client(config['WECHAT_SESSION_MEMCACHED']) session_interface = MemcachedStorage( mc, prefix=config['WECHAT_SESSION_PREFIX']) elif config['WECHAT_SESSION_TYPE'] == 'leancloud': from .storage import LeanCloudStorage session_interface = LeanCloudStorage() else: from wechatpy.session.memorystorage import MemoryStorage session_interface = MemoryStorage() return session_interface
def test_redis_session_storage_init(self): from redis import Redis from wechatpy.session.redisstorage import RedisStorage redis = Redis() session = RedisStorage(redis) client = WeChatClient(self.app_id, self.secret, session=session) self.assertTrue(isinstance(client.session, RedisStorage))
def init_app(self, app): self.app = app config = app.config config.setdefault('WECHAT_APPID', None) config.setdefault('WECHAT_SECRET', None) config.setdefault('WECHAT_TYPE', 0) config.setdefault('WECHAT_SESSION_TYPE', None) config.setdefault('WECHAT_SESSION_PREFIX', 'flask-wechatpy') config.setdefault('WECHAT_AUTO_RETRY', True) config.setdefault('WECHAT_TIMEOUT', None) assert config['WECHAT_APPID'] is not None assert config['WECHAT_SECRET'] is not None if config['WECHAT_TYPE'] == 0: from wechatpy import WeChatClient else: from wechatpy.enterprise import WeChatClient if config['WECHAT_SESSION_TYPE'] == 'redis': from wechatpy.session.redisstorage import RedisStorage from redis import Redis if config.get('WECHAT_SESSION_REDIS_URL'): redis = Redis.from_url(config['WECHAT_SESSION_REDIS_URL']) else: redis = Redis(host=config.get('WECHAT_SESSION_REDIS_HOST', 'localhost'), port=config.get('WECHAT_SESSION_REDIS_PORT', 6379), db=config.get('WECHAT_SESSION_REDIS_DB', 0), password=config.get('WECHAT_SESSION_REDIS_PASS', None)) session_interface = RedisStorage( redis, prefix=config['WECHAT_SESSION_PREFIX']) elif config['WECHAT_SESSION_TYPE'] == 'memcached': from wechatpy.session.memcachedstorage import MemcachedStorage mc = self._get_mc_client(config['WECHAT_SESSION_MEMCACHED']) session_interface = MemcachedStorage( mc, prefix=config['WECHAT_SESSION_PREFIX']) elif config['WECHAT_SESSION_TYPE'] == 'shove': pass else: session_interface = None self._wechat_client = WeChatClient( config['WECHAT_APPID'], config['WECHAT_SECRET'], session=session_interface, timeout=config['WECHAT_TIMEOUT'], auto_retry=config['WECHAT_AUTO_RETRY'], ) if not hasattr(app, 'extensions'): app.extensions = {} app.extensions['wechatpy'] = self
def __init__(self, appid, secret, redis_client=None): session_interface = None if redis_client: session_interface = RedisStorage(redis_client, prefix="wechatpy") client = WeChatClient(appid, secret, session=session_interface) self.menu = wechatMenu(client) self.qrcode = wechatQrcode(client) self.send = wechatSend(client) self.user = wechatUser(client)
def set_session(self, redis=None, shove=None, mc=None, prefix="wechatpy"): if redis is not None: from wechatpy.session.redisstorage import RedisStorage self.session = RedisStorage(redis, prefix) elif shove is not None: from wechatpy.session.shovestorage import ShoveStorage self.session = ShoveStorage(shove, prefix) elif mc is not None: from wechatpy.session.memcachedstorage import MemcachedStorage self.session = MemcachedStorage(mc, prefix)
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 test_redis_session_storage_access_token(self): from redis import Redis from wechatpy.session.redisstorage import RedisStorage redis = Redis() session = RedisStorage(redis) client = WeChatClient(self.app_id, self.secret, session=session) with HTTMock(wechat_api_mock): token = client.fetch_access_token() self.assertEqual('1234567890', token['access_token']) self.assertEqual(7200, token['expires_in']) self.assertEqual('1234567890', client.access_token)
def _get_wechatclient(): app_id = current_app.config.get('app_id') secret = current_app.config.get('secret') redirect_uri = current_app.config.get('redirect_uri') redis_url = current_app.config.get('REDIS_HOST') redis_port = current_app.config.get('REDIS_PORT') redis_db = current_app.config.get('REDIS_DB') redis_client = redis.Redis.from_url('redis://{}:{}/{}'.format( redis_url, redis_port, redis_db)) session_interface = RedisStorage(redis_client, prefix="wechatpy") wechatclient = WeChatClient(app_id, secret, session=session_interface) return wechatclient
def test_client_expires_at_consistency(self): from redis import Redis from wechatpy.session.redisstorage import RedisStorage redis = Redis() session = RedisStorage(redis) client1 = WeChatClient(self.app_id, self.secret, session=session) client2 = WeChatClient(self.app_id, self.secret, session=session) assert client1.expires_at == client2.expires_at expires_at = time.time() + 7200 client1.expires_at = expires_at assert client1.expires_at == client2.expires_at == expires_at
def __init__(self): self.redis_client = Redis(host=redis_host, password=redis_password) self.session_interface = RedisStorage(self.redis_client, prefix="wechatpy") self.wechat_client = WeChatClient(appid, secret, session=self.session_interface) self.template_id = { Instrument.F20: template_id_remind_f20, Instrument.FIB: template_id_remind_fib } self.mysql = pymysql.connect(host=mysql_host, password=mysql_password, db='wechat_tem', charset='utf8', autocommit=True)
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 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
gconf = yaml.load(file(ospath + '/gconf.yml', 'r'))[run_mode] gconf['uptime'] = time.strftime("%Y%m%d%H%M%S", time.localtime(time.time())) gconf['run_mode'] = run_mode srv = yaml.load(file(ospath + '/srv.yml', 'r'))[run_mode] wx = yaml.load(file(ospath + '/wx.yml', 'r'))[run_mode] errorDesc = yaml.load(file(ospath + '/errorDesc.yml', 'r')) upFile = upyun.UpYun(gconf['up_file_bucket'], gconf['up_file_uname'], gconf['up_file_pwd'], timeout=30, endpoint=upyun.ED_AUTO) msgDict = {} pool = redis.ConnectionPool(**srv['redis']) rdb = redis.StrictRedis(connection_pool=pool) mdb = MongoClient(srv['mongo']['host'], srv['mongo']['port']) mdb.admin.authenticate(srv['mongo']['uname'], srv['mongo']['pwd'], mechanism='SCRAM-SHA-1') mdb = mdb[srv['mongo']['db']] wxclient = WeChatClient(wx['APP_ID'], wx['APP_SECRET'], session=RedisStorage(rdb))
def init(self, env): dbname = env.cr.dbname global WxEnvDict if dbname in WxEnvDict: del WxEnvDict[dbname] WxEnvDict[dbname] = self try: config = env['wx.config'].sudo().get_cur() action = config.action except: import traceback traceback.print_exc() action = None if action: self.subscribe_auto_msg = config.action.get_wx_reply() Param = env['ir.config_parameter'].sudo() self.wx_token = Param.get_param('wx_token') or '' self.wx_appid = Param.get_param('wx_appid') or '' self.wx_AppSecret = Param.get_param('wx_AppSecret') or '' self.server_url = Param.get_param('server_url') or '' self.session_storage = Param.get_param('session_storage') or '' self.wxclient.config["APP_ID"] = self.wx_appid self.wxclient.config["APP_SECRET"] = self.wx_AppSecret self.wxclient.config["server_url"] = self.server_url if not self.session_storage: session_storage = MemoryStorage() _logger.info("启用MemoryStorage") else: _logger.info("启用RedisStorage%s" % self.wx_appid) db = redis.Redis(host=self.session_storage, port=6379) session_storage = RedisStorage(db, prefix=self.wx_appid) try: # 获取以前的token是否需要获取新的Token AccessToken self.wxclient.session = session_storage # self.wxclient._token = session_storage.get(self.access_token_key) _ = self.wxclient.token except Exception as e: print(e) import traceback traceback.print_exc() _logger.error(u'初始化微信客户端token失败,请在微信对接配置中填写好相关信息!') robot = WeRoBot(token=self.wx_token, enable_session=True, logger=_logger, session_storage=session_storage) enable_pretty_logging(robot.logger) self.robot = robot try: wechatpy_client = WeChatClient(self.wx_appid, self.wx_AppSecret, access_token=self.wxclient.token, session=session_storage) self.wechatpy_client = wechatpy_client except Exception as e: print(e) _logger.error("加载微信token错误。") 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))
# -*- coding: utf-8 -*- import os from wechatpy.client import WeChatClient import requests from wechatpy.session.redisstorage import RedisStorage from redis import Redis __redis_client = Redis.from_url('redis://127.0.0.1:6379/0') __session_interface = RedisStorage( __redis_client, prefix='s2a' ) wechat_client = WeChatClient( appid=os.environ.get('APP_ID'), secret=os.environ.get('APP_SECRET'), session=__session_interface )
import time from sanic import Sanic from sanic.response import json from sanic_cors import CORS, cross_origin from redis import Redis from wechatpy import WeChatClient from wechatpy.session.redisstorage import RedisStorage from wechatpy.utils import random_string # wechatpy redis_client = Redis.from_url("redis://127.0.0.1:6379/0") session_interface = RedisStorage(redis_client, prefix="wechatpy") appid = "wx864c69fe65dd3965" secret = "61e14f509405ddb041b5c08c552691ee" client = WeChatClient(appid=appid, secret=secret, session=session_interface) app = Sanic() CORS(app) @app.route("/") async def test(request): return json({"hello": "world"}) @app.route("/jssdk_config") async def jssdk_config(request): url = request.headers.get("referer") ticket = client.jsapi.get_jsapi_ticket() timestamp = int(time.time())
from django.conf import settings from django.core.cache import cache from wechatpy.client import WeChatClient from wechatpy.client.api import WeChatWxa from wechatpy.session.redisstorage import RedisStorage from wechatpy.session.memorystorage import MemoryStorage from django_redis import get_redis_connection session = ( RedisStorage(get_redis_connection()) if settings.CACHES["default"]["BACKEND"] == "django_redis.cache.RedisCache" else MemoryStorage() ) 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 wxa(app_id, app_secret=None): return wrap(WeChatWxa, app_id=app_id, app_secret=app_secret) def wechat_client(app_id, app_secret=None):
from __future__ import absolute_import, unicode_literals from wechatpy import WeChatOAuth from flask import request, abort, jsonify from wechatpy.exceptions import * from wechatpy.session.redisstorage import RedisStorage from halo import redis_client, app from wechatpy.utils import json TOKEN = app.config['TOKEN'] AES_KEY = app.config['AES_KEY'] APPID = app.config['APPID'] APPSECRET = app.config['APPSECRET'] redirect_uri = 'http://m.ayhalo.com' oauth_session = RedisStorage(redis_client, prefix="oauth") oauth = WeChatOAuth(APPID, APPSECRET, redirect_uri, scope='snsapi_userinfo', state='halo') def get_init(): code = request.args.get('code', '') token = oauth.fetch_access_token(code) openid = token['openid'] access_token = token['access_token'] oauth_session.set('access_token', token['access_token'], 7000)
class WeClient(object): we_client = WeChatClient(appid=settings.MP_APP_ID, secret=settings.MP_APP_SECRET, session=RedisStorage(redis_client, prefix='wechat')) ACCOUNT_VIEW_BTN_EVENT = 'ACCOUNT_VIEW_BTN_EVENT' # 账户中心 CUSTOMER_SERVICE_BTN_EVENT = 'CUSTOMER_SERVICE_BTN_EVENT' # 联系客服 ACCOUNT_VIEW_URI = f'https://open.weixin.qq.com/connect/oauth2/authorize?appid={settings.MP_APP_ID}' \ f'&redirect_uri={settings.MP_HOST}/&response_type=code&scope=snsapi_userinfo' PLATFORM_VIEW_URI = f'https://open.weixin.qq.com/connect/oauth2/authorize?appid={settings.MP_APP_ID}' \ f'&redirect_uri={settings.MP_HOST}/platform&response_type=code&scope=snsapi_userinfo' IOS_VIEW_URI = f'https://open.weixin.qq.com/connect/oauth2/authorize?appid={settings.MP_APP_ID}' \ f'&redirect_uri={settings.MP_HOST}/ios&response_type=code&scope=snsapi_userinfo' ANDROID_VIEW_URI = f'https://open.weixin.qq.com/connect/oauth2/authorize?appid={settings.MP_APP_ID}' \ f'&redirect_uri={settings.MP_HOST}/android&response_type=code&scope=snsapi_userinfo' @classmethod def create_mp_menu(cls): if not settings.ENV.is_production(): return # 创建公众号-自定义菜单: https://mp.weixin.qq.com/wiki?t=resource/res_main&id=mp1421141013 menu_data = { 'button': [{ 'type': 'click', 'name': '账号中心', 'key': cls.ACCOUNT_VIEW_BTN_EVENT, }, { 'name': 'WIFI连接教程', 'sub_button': [ { 'type': 'view', 'name': '上网教程 (苹果手机)', 'url': cls.IOS_VIEW_URI, }, { 'type': 'view', 'name': '上网教程 (安卓手机)', 'url': cls.ANDROID_VIEW_URI, }, { 'type': 'click', 'name': '联系客服', 'key': cls.CUSTOMER_SERVICE_BTN_EVENT, }, { 'type': 'view', 'name': '房东二维码 (仅房东用)', 'url': cls.PLATFORM_VIEW_URI, }, ] }] } cls.we_client.menu.create(menu_data) return @classmethod def create_qrcode(cls, scene_str: str, expire_seconds: int = 30, is_permanent=False): """ https://developers.weixin.qq.com/doc/offiaccount/Account_Management/Generating_a_Parametric_QR_Code.html :param scene_str: :param expire_seconds: :param is_permanent: :return: {"ticket":"gQH47joAAAAAAAAAASxod2G3sUw==","expire_seconds":60,"url":"http://weixin.qq.com/q/kZgfwMTm72WWPkovabbI"} ticket: 获取的二维码ticket,凭借此ticket可以在有效时间内换取二维码。 expire_seconds: 该二维码有效时间,以秒为单位。 最大不超过2592000(即30天)。 url: 二维码图片解析后的地址,开发者可根据该地址自行生成需要的二维码图片 """ assert isinstance(scene_str, str) data = { 'expire_seconds': expire_seconds, 'action_name': 'QR_LIMIT_STR_SCENE' if is_permanent else 'QR_STR_SCENE', 'action_info': { 'scene': { 'scene_str': scene_str }, } } return cls.we_client.qrcode.create(data)
env.setdefault(k, v) redis_host = env["REDIS_HOST"] redis_port = int(env["REDIS_PORT"]) redis_pwd = env["REDIS_PWD"] wechat_corp_id = env["WECHAT_CORP_ID"] wechat_secret = env["WECHAT_SECRET"] wechat_crypto_token = env['WECHAT_CRYPTO_TOKEN'] wechat_crypto_encoding_aes_key = env['WECHAT_CRYPTO_AES_KEY'] wechat_invite_code = env['WECHAT_INVITE_CODE'] wechat_create_menu = distutils.util.strtobool(env['WECHAT_CREATE_MENU']) agent_id = env['AGENT_ID'] image_id = env['IMAGE_ID'] debug = distutils.util.strtobool(env['DEBUG']) logging.basicConfig(level=logging.DEBUG if debug else logging.INFO) for i in [redis_host, redis_port, redis_pwd, wechat_corp_id, wechat_secret, wechat_crypto_token, wechat_crypto_encoding_aes_key, agent_id]: if i == 'set_it': logging.error(env.items()) logging.error('部分变量未设置,请检查你的变量设置是否正确。') time.sleep(30) exit(-1) if wechat_create_menu: create_menu() r = redis.Redis(host=redis_host, port=redis_port, db=0, password=redis_pwd) crypto = WeChatCrypto(token=wechat_crypto_token, encoding_aes_key=wechat_crypto_encoding_aes_key, corp_id=wechat_corp_id) client = WeChatClient(corp_id=wechat_corp_id, secret=wechat_secret, session=RedisStorage(r)) # 启用京东登录事件循环 jd_qrcode.start_loop() run()
def session_interface(): return RedisStorage( Redis.redis_client(), prefix="wechatpy" )
# encoding: utf-8 from __future__ import absolute_import, unicode_literals from django.conf import settings from django.core.files.uploadedfile import InMemoryUploadedFile from redis import Redis from six import BytesIO from wechatpy import WeChatClient from wechatpy.crypto import WeChatWxaCrypto from wechatpy.session.redisstorage import RedisStorage redis_client = Redis.from_url(settings.REDIS_CACHE_URL) wechat = WeChatClient(settings.WECHAT_APPID, settings.WECHAT_APPSECRET, session=RedisStorage(redis_client, prefix="wechat_session::%s" % settings.WECHAT_APPID)) def decrypt_message(session_key, iv, encrypted_data): crypto = WeChatWxaCrypto(session_key, iv, settings.WECHAT_APPID) return crypto.decrypt_message(encrypted_data) def get_wxa_code_unlimited_file(file_name, scene, **kwargs): file = BytesIO() kw = dict() for k in ('width', 'auto_color', 'line_color', 'page', 'is_hyaline'): if k in kwargs: kw[k] = kwargs[k] content = wechat.wxa.get_wxa_code_unlimited(scene, **kw)
def init_Wechat(): session_inferface = RedisStorage(redis_client, prefix="weixin") client = WeChatClient(APPID, APPSECRET, session=session_inferface) return client