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 __init__(self, component_appid, component_appsecret, component_token, encoding_aes_key, session=None): """ :param component_appid: 第三方平台appid :param component_appsecret: 第三方平台appsecret :param component_token: 公众号消息校验Token :param encoding_aes_key: 公众号消息加解密Key """ self.component_appid = component_appid self.component_appsecret = component_appsecret self.expires_at = None self.crypto = WeChatCrypto(component_token, encoding_aes_key, component_appid) self.session = session or MemoryStorage() if isinstance(session, six.string_types): from shove import Shove from wechatpy.session.shovestorage import ShoveStorage querystring = get_querystring(session) prefix = querystring.get('prefix', ['wechatpy'])[0] shove = Shove(session) storage = ShoveStorage(shove, prefix) self.session = storage
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 __init__(self, appid, access_token=None, session=None, timeout=None, auto_retry=True): self.appid = appid self.expires_at = None self.session = session or MemoryStorage() self.timeout = timeout self.auto_retry = auto_retry if isinstance(session, six.string_types): from shove import Shove from wechatpy.session.shovestorage import ShoveStorage querystring = get_querystring(session) prefix = querystring.get('prefix', ['wechatpy'])[0] shove = Shove(session) storage = ShoveStorage(shove, prefix) self.session = storage if access_token: self.session.set(self.access_token_key, access_token)
def __init__( self, component_appid, component_appsecret, component_token, encoding_aes_key, session=None, auto_retry=True, ): """ :param component_appid: 第三方平台appid :param component_appsecret: 第三方平台appsecret :param component_token: 公众号消息校验Token :param encoding_aes_key: 公众号消息加解密Key """ self._http = requests.Session() self.component_appid = component_appid self.component_appsecret = component_appsecret self.expires_at = None self.crypto = WeChatCrypto(component_token, encoding_aes_key, component_appid) self.session = session or MemoryStorage() self.auto_retry = auto_retry if isinstance(session, str): from shove import Shove from wechatpy.session.shovestorage import ShoveStorage querystring = get_querystring(session) prefix = querystring.get("prefix", ["wechatpy"])[0] shove = Shove(session) storage = ShoveStorage(shove, prefix) self.session = storage
def __init__(self, appid, access_token=None, session=None, timeout=None, auto_retry=True): self._http = requests.Session() self.appid = appid self.session = session or MemoryStorage() self.timeout = timeout self.auto_retry = auto_retry if access_token: self.session.set(self.access_token_key, access_token)
def __init__(self, access_token=None, session=None): self.expires_at = None self.session = session or MemoryStorage() if isinstance(session, six.string_types): from shove import Shove from wechatpy.session.shovestorage import ShoveStorage querystring = get_querystring(session) prefix = querystring.get('prefix', ['wechatpy'])[0] shove = Shove(session) storage = ShoveStorage(shove, prefix) self.session = storage self.session.set('access_token', access_token)
def __init__(self, component_appid, component_appsecret, session=None): """ :param component_appid: 第三方平台appid :param component_appsecret: 第三方平台appsecret :param component_verify_ticket: 微信后台推送的ticket,此ticket会定时推送 """ self.component_appid = component_appid self.component_appsecret = component_appsecret self.expires_at = None self.session = session or MemoryStorage() if isinstance(session, six.string_types): from shove import Shove from wechatpy.session.shovestorage import ShoveStorage querystring = get_querystring(session) prefix = querystring.get('prefix', ['wechatpy'])[0] shove = Shove(session) storage = ShoveStorage(shove, prefix) self.session = storage
def __init__( self, component_appid, component_appsecret, component_token, encoding_aes_key, session=None, auto_retry=True, ): """ :param component_appid: 第三方平台appid :param component_appsecret: 第三方平台appsecret :param component_token: 公众号消息校验Token :param encoding_aes_key: 公众号消息加解密Key """ self._http = requests.Session() self.component_appid = component_appid self.component_appsecret = component_appsecret self.expires_at = None self.crypto = WeChatCrypto(component_token, encoding_aes_key, component_appid) self.session = session or MemoryStorage() self.auto_retry = auto_retry
def __init__(self): threading.Thread.__init__(self, name="Sending Thread") from wechatpy.session.memorystorage import MemoryStorage self.session = MemoryStorage() self.pollablequeue = _PollableQueue() self.wechatclients = {}
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 wechatpy.session.memorystorage import MemoryStorage from b2c.general.helpers import get_merchant_from_merchant_user from b2c.general.mixins import SimpleCodenamePermissionMixin from b2c.users.models import MerchantConfig from b2c.users.models.merchant import Merchant from b2c.users.permissions import IsMerchantUserPermission from b2c.users.services import update_merchant_config, cancel_authorize from b2c.wxapp import wechat_api from b2c.wxapp.services import component from b2c.wxapp.models.wx_app_review_state_type import WXAppReviewStateType from b2c.wxapp.services import wx_mch_user_create_or_update, get_access_token, submit_audit_all_merchant from config.settings.base import WE_CHAT_APP logger = logging.getLogger('django') memorystorage = MemoryStorage() ymj_base_url = 'https://elk.yimeijian.cn/v1/' # 发起小程序授权回调 ymj_start_auth_callback = ymj_base_url + 'ab/proxy_wxapp/auth_callback/' # 授权结束后回调页面 ymj_end_auth_callback = '.yimeijian.cn/#/setting/small_program_auth' # 微信授权URL wx_auth_url = 'https://mp.weixin.qq.com/cgi-bin/componentloginpage?component_appid=' # 体验二维码 wx_qrcode_url = 'https://api.weixin.qq.com/wxa/get_qrcode?access_token=' def wxapp_auth_view(request, merchant_id):
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))
self.secret = secret client = Client() client1 = Client() print(id(client)) print(id(client1)) print(str(client().access_token)) print(client().access_token) access_token_memory = MemoryStorage() c = WeChatClient(appid, secret, session=access_token_memory) print(c.access_token) print(c.access_token) c = WeChatClient(appid, secret, session=access_token_memory) print(c.access_token) print(c.access_token) ## 在web应用中注意WeChatClient的session使用同一个存储对象,保证access_token_memory 按策略刷新。避免业务量较大应用access token获取次数超限 # 4300887784 # 4300887784 # 5_IXxqjJcVePWbniDrUfSppsISOKPaGo9dtxlgtZ73B9Tx4OWc1k1l-lkc-J7mJM1pOPIUTmS3vXp4CvkwMbYLRAn8PkoW6yIL1NHTjmLlkm2cqp4X3KIb6G319jIZHKgADAIQT # 5_rj2TjX42W5oYG3iHUfSppsISOKPaGo9dtxlgtZ73B9Tx4OWc1k1l-lkc-J6FgfVPt-E2w1pf5ztKBSeCe5f8egQbfgjM9ebcmhi_WU13QtLQW4gXDFT2cngTY7gXFPgADANVF
# -*- coding: utf-8 -*- ################################################################################### # Copyright (C) 2019 SuXueFeng License GNU ################################################################################### import json import logging import requests from requests import ReadTimeout, ConnectTimeout from odoo import api, models from wechatpy.enterprise import WeChatClient from wechatpy.session.memorystorage import MemoryStorage from odoo.http import request mem_storage = MemoryStorage() _logger = logging.getLogger(__name__) def app_client(): """ 返回用于自建应用的客户端实例 :return: 企业微信客户端实例 """ corp_id = request.env['ir.config_parameter'].sudo().get_param('weixin_ent_base.ent_wx_corp_id') secret = request.env['ir.config_parameter'].sudo().get_param('weixin_ent_base.ent_wx_secret') return WeChatClient(corp_id, secret, session=mem_storage) def address_client(): """ 返回用于通讯录的客户端实例