Esempio n. 1
0
    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
Esempio n. 2
0
def short_urls(url):
    if not url:
        return url

    m2 = hashlib.md5()
    m2.update(url)
    fp = m2.hexdigest()
    fp = 'runtime/%s' % fp

    if os.path.exists(fp):
        with open(fp) as f:
            s = f.read()

        return s

    try:
        client = WeChatClient(settings.WECHAT_APPKEY, settings.WECHAT_SECRET)
        short_url = client.misc.short_url(long_url=url)['short_url']

        with open(fp, 'w') as f:
            f.write(short_url)
    except Exception as e:
        short_url = url

    return short_url
Esempio n. 3
0
    def get(self, request, args):
        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=MP_APPID,
                                     secret=MP_APPSECRET,
                                     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"))
        jsapi_ticket = redis_conn.get("jsapi_ticket")
        jsapi_ticket = jsapi_ticket.decode("utf-8") if jsapi_ticket else None
        if not jsapi_ticket:
            jsapi_ticket = wechat_client.jsapi.get_jsapi_ticket()
            redis_conn.setex("jsapi_ticket", 7100, jsapi_ticket)
        noncestr = "".join(
            random.sample(string.ascii_letters + string.digits, 10))
        timestamp = int(time.time())
        signature = wechat_client.jsapi.get_jsapi_signature(
            noncestr, jsapi_ticket, timestamp, args.get("url"))
        data = {
            "appID": MP_APPID,
            "timestamp": timestamp,
            "nonceStr": noncestr,
            "signature": signature,
        }

        return self.send_success(data=data)
Esempio n. 4
0
    def wechat(cls, content):
        # pip install wechatpy
        # pip install pycrypto  cryptography  2选1

        from wechatpy import WeChatClient
        import datetime

        client = WeChatClient('oqZI700TICQqEk_LHluLxgsk2-qQ',
                              '5354b6234736845c82345e')
        template_id = 'SVxtZHeS77EvBLyzl234tifLYt-234pORiN345No'
        openid = 'oV4P22J234JcnJD3YK34567c'

        data = {
            'msg': {
                "value": content,
                "color": "#173177"
            },
            'time': {
                "value": datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S'),
                "color": "#173177"
            },
        }

        try:
            client.message.send_template(openid, template_id, data)
        except Exception as ex:
            print(ex)
Esempio n. 5
0
def createMenu(request):
    print("go into ajax createMenu.")
    client = WeChatClient(APPID, AppSecret)
    response = client.menu.create({
        "button": [{
            "name":
            "底价分类",
            "sub_button": [
                {
                    "type": "view",
                    "name": "团购",
                    "url": "http://39.106.98.42/djshop/wechat/groupbuyPanel"
                },
                {
                    "type": "view",
                    "name": "外卖",
                    "url": "http://39.106.98.42/djshop/wechat/takeoutPanel"
                },
                {
                    "type": "view",
                    "name": "约车",
                    "url": "http://39.106.98.42/djshop/wechat/carorderPanel"
                },
                {
                    "type": "view",
                    "name": "电影票",
                    "url": "http://39.106.98.42/djshop/wechat/moviePanel"
                },
            ]
        }, {
            "name":
            "底价消息",
            "sub_button": [
                {
                    "type": "click",
                    "name": "省钱必看",
                    "key": "piggy"
                },
                {
                    "type": "click",
                    "name": "近期优惠",
                    "key": "jasper"
                },
            ]
        }, {
            "type": "media_id",
            "name": "商务合作",
            "media_id": "Sf7M0xlLiNfkGlXla8hyVbx0TjvKPhxrs6ECOlDfmIs"
        }]
    })
    pprint.pprint(response)
    context = {
        "title": 'wechatpy.client.api.WeChatMenu.create',
        "errcode": response['errcode'],
        "errmsg": response['errmsg']
    }
    # openFile = open('/home/helen/projects/djshop/djshoproj/static/wechat/img/COACH_1.jpg', 'rb')
    # material = client.material.add('image', openFile)
    # pprint.pprint(material)
    return render(request, 'wechat/createMenu.html', context)
Esempio n. 6
0
def create_menu(request):
    client = WeChatClient(APPID, APPSECRET)
    client.menu.create({
        "button": [
            {
                "type": "click",
                "name": "我的博客",
                "key": "articuly_blog"
            },
            {
                "name":
                "菜单",
                "sub_button": [
                    {
                        "type": "view",
                        "name": "搜索",
                        "url": "http://www.baidu.com/"
                    },
                    {
                        "type": "click",
                        "name": "赞一下我们",
                        "key": "V1001_GOOD"
                    },
                    {
                        "name": "发送位置",
                        "type": "location_select",
                        "key": "rselfmenu_2_0"
                    },
                ]
            },
        ]
    })
    return HttpResponse('菜单已创建成功')
Esempio n. 7
0
def handler(message, *args, **kwargs):
    queryset = Goods.objects.filter(title__isnull=False)
    results = queryset.all()

    if not results:
        return None

    message = '''
===================
'''
    quantity = 1

    for result in results:
        url = 'http://ws.gjingxi.com/buy/?id=%d&q=%d&uin=%s&nick=%s' % (int(
            result.id), int(quantity), uin, nick)
        client = WeChatClient(settings.WECHAT_APPKEY, settings.WECHAT_SECRET)
        short_url = client.misc.short_url(long_url=url)['short_url']

        amount = float(float(result.price) * float(quantity))
        price = result.price
        title = result.title
        units = result.units

        message += '''商品: %(title)s
价格: %(price).2f 元
%(short_url)s
-------------------
''' % locals()

    return message.strip().strip('-------------------')
Esempio n. 8
0
def add_material(request):
    # 上传临时素材并且存入数据库, 注意上穿的图片名字不能是中文
    media_type = request.POST.get("media_type", "")
    # print(request.FILES.values())
    # for i in request.FILES.values():
    #     print(type(i))
    media_file = request.FILES.get("media_file")
    # print(type(media_file))
    # print(dir(media_file))
    title = request.POST.get("title", "")
    introduction = request.POST.get("introduction", "")

    # 主要是获得access_token
    client = WeChatClient('wxeac1aed88d8117f1',
                          '24397d8edd0a39d21c169a87f351c916')

    from wechatpy.client.api import WeChatMedia
    # 初始化上传临时媒体文件的类
    media = WeChatMedia(client)
    info = media.upload(media_type, media_file)
    # info = client.WeChatMedia.add(media_type, media_file.open(),title,introduction)
    print(info)
    material = MaterialModel()
    material.media_type = media_type
    material.title = title
    material.introduction = introduction
    material.media_id = info['media_id']
    material.save()
    return HttpResponse("OK")
Esempio n. 9
0
def wxClient():
    """
    创建微信客户端对象
    :return:
    """
    client = WeChatClient(settings.WECHAT_APPID, settings.WECHAT_SECRET, session=session_interface)
    return client
Esempio n. 10
0
def defi_menu(request):
    client = WeChatClient(APPID, APPSECRET, accessToken.send_request())
    client.menu.create({
        "button": [{
            "name":
            "公司注册",
            "sub_button": [{
                "type":
                "view",
                "name":
                "订单提交",
                "url":
                "http://whw.free.idcfengye.com/first/userInfo/"
            }, {
                "type": "view",
                "name": "进度查询",
                "url": "http://whw.free.idcfengye.com/first/check/"
            }, {
                "type": "click",
                "name": "赞一下我们",
                "key": "V1001_GOOD"
            }]
        }]
    })
    return HttpResponse('创建成功')
Esempio n. 11
0
    def test_shove_storage_init_with_prefix(self):
        from wechatpy.session.shovestorage import ShoveStorage

        uri = "memory://?prefix=custom_prefix"
        client = WeChatClient(self.app_id, self.secret, session=uri)
        self.assertTrue(isinstance(client.session, ShoveStorage))
        self.assertEqual("custom_prefix", client.session.prefix)
Esempio n. 12
0
    def init_with_config(self, config):
        session_interface = self._init_session(config)

        if config['WECHAT_TYPE'] == 17:
            from wechatpy.component import WeChatComponent
            self._is_component = True
            return WeChatComponent(
                config['WECHAT_APPID'],
                config['WECHAT_SECRET'],
                config['WECHAT_TOKEN'],
                config['WECHAT_AES_KEY'],
                session=session_interface,
            )

        if config['WECHAT_TYPE'] == 0:
            from wechatpy import WeChatClient
        else:
            from wechatpy.enterprise import WeChatClient

        return WeChatClient(
            config['WECHAT_APPID'],
            config['WECHAT_SECRET'],
            session=session_interface,
            timeout=config['WECHAT_TIMEOUT'],
            auto_retry=config['WECHAT_AUTO_RETRY'],
        )
Esempio n. 13
0
 def test_memory_session_storage_access_token(self):
     client = WeChatClient(self.app_id, self.secret)
     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)
Esempio n. 14
0
def type_event(db: Session, message):
    if "Ticket" in message:
        client = WeChatClient(wechat.app_id, wechat.secret)
        user = crud.user.get_by_wx_openid(db, message['FromUserName'])
        # 不存在时创建用户
        if not user:
            try:
                # 获取微信
                wechat_user = client.user.get(message['FromUserName'])
            except Exception as e:
                print(e)
                nickname = "nickname" + str(random.randint(100, 999))
                headimgurl = "https://ss3.bdstatic.com/70cFv8Sh_Q1YnxGkpoWK1HF6hhy/it/u=1517507934,1319873565&fm=26&gp=0.jpg"
                wechat_user = {
                    "openid": message['FromUserName'],
                    "nickname": nickname,
                    "headimgurl": headimgurl
                }
                # raise e
            crud.user.create_by_wechat(db=db,
                                       wx_openid=message['FromUserName'],
                                       name=wechat_user["nickname"],
                                       avatar=wechat_user["headimgurl"])
        Cache.put(message['Ticket'], message['FromUserName'], 5)
    return ''
Esempio n. 15
0
def create_menu(request):
    client = WeChatClient('wxeac1aed88d8117f1',
                          '24397d8edd0a39d21c169a87f351c916')
    client.menu.create({
        "button": [{
            "type": "click",
            "name": "今日歌曲",
            "key": "V1001_TODAY_MUSIC"
        }, {
            "type": "click",
            "name": "歌手简介",
            "key": "V1001_TODAY_SINGER"
        }, {
            "name":
            "菜单",
            "sub_button": [{
                "type": "click",
                "name": "关于我",
                'key': 'V1001_ABOUT_ME'
            }, {
                "type": "view",
                "name": "视频",
                "url": "http://v.qq.com/"
            }, {
                "type": "click",
                "name": "赞一下我们",
                "key": "V1001_GOOD"
            }]
        }]
    })
    return HttpResponse('ok')
Esempio n. 16
0
def sendTemplate(weixin_user, message_template):
    weixin_account = WeixinAccounts.getByOriginalId(weixin_user.account_original_id)
    # account = Account.objects.get(original_id=weixin_user.account_original_id)
    client = WeChatClient(weixin_account.app_id, weixin_account.app_secret)
    client.message.send_template(weixin_user.openid, template_id=message_template.template_id,
                                 top_color=message_template.top_color, data=message_template.data,
                                 url=message_template.url)
Esempio n. 17
0
def create_menu(request):
    # 第一个参数是公众号里面的appID,第二个参数是appsecret
    client = WeChatClient("wx1c53a7cf55314e85",
                          "d28ecedbf5ff74fe268595ea035a6b6f")
    client.menu.create({
        "button": [{
            "name":
            "智能访客",
            "sub_button": [{
                "type": "view",
                "name": "访客预约",
                "url": "http://3fcba1c69bb95399.natapp.cc/wx",
                "sub_button": []
            }]
        }, {
            "name":
            "产品演示",
            "sub_button": [{
                "type": "view",
                "name": "资产管理",
                "url": "http://127.0.0.1",
                "sub_button": []
            }]
        }, {
            "type": "click",
            "name": "关于戊辰",
            "key": "V1001_GOOD"
        }]
    })
    return HttpResponse('ok')
Esempio n. 18
0
    def test_shove_storage_init(self):
        from wechatpy.session.shovestorage import ShoveStorage

        uri = 'memory://'
        client = WeChatClient(self.app_id, self.secret, session=uri)
        self.assertTrue(isinstance(client.session, ShoveStorage))
        self.assertEqual('wechatpy', client.session.prefix)
Esempio n. 19
0
def create_wechat_menu(app_name):
	print('--------------------------------------------------------')
	app_id = frappe.get_value('Wechat App', app_name, 'app_id')
	secret = frappe.get_value('Wechat App', app_name, 'secret')
	domain = "http://" + (frappe.get_value('Wechat App', app_name, 'domain') or "mm.symgrid.com")

	# Top Menu
	top_menu_list = frappe.get_all("Wechat AppMenu",
									filters={'parent': app_name, 'group_index': 0},
									fields=["menu", "alias", "`group`"],
									order_by="`group`")
	menu_buttons = []
	for menu in top_menu_list:
		doc = frappe.get_doc("Wechat Menu", menu.menu)
		menu_button = {
			"type": doc.menu_type or "view",
			"name": menu.alias or doc.menu_name
		}
		if doc.route:
			url = domain + "/wechat/" + doc.route + "/" + app_name
		else:
			url = domain + "/wechat/home/" + app_name
		menu_button["url"] = WeChatOAuth(app_id, secret, url).authorize_url

		# Sub menu
		sub_menu_list = frappe.get_all("Wechat AppMenu",
										filters={'parent': app_name, '`group`': menu.group},
										fields=["menu", "alias", "group_index"],
										order_by="group_index")

		for sub_menu in sub_menu_list:
			if sub_menu.group_index == 0:
				continue
			if "sub_button" not in menu_button:
				menu_button = {
					"name": menu_button['name'],
					"sub_button": []
				}
			doc = frappe.get_doc("Wechat Menu", sub_menu.menu)
			m = {
				"type": doc.menu_type or "view",
				"name": sub_menu.alias or doc.menu_name
			}
			if doc.route:
				url = domain + "/wechat/" + doc.route + "/" + app_name
			else:
				url = domain + "/wechat/home/" + app_name
			m["url"] = WeChatOAuth(app_id, secret, url).authorize_url
			menu_button["sub_button"].append(m)

		menu_buttons.append(menu_button)

	menu = {
		"button": menu_buttons
	}
	print(json.dumps(menu))
	client = WeChatClient(app_id, secret)
	client.menu.create(menu)
	print('--------------------------------------------------------')
Esempio n. 20
0
def init_template_message():
    """发送模板文本消息"""

    client = WeChatClient(WECHAT_APPID, WECHAT_SECRET)
    # res = client.template.set_industry(1, 4)
    # print('>>>', res)
    res = client.template.get_industry()
    print('>>>', res)
Esempio n. 21
0
def create_wechat_menu():
    """create wechat menu"""

    print('>>>>', WECHAT_APPID, WECHAT_SECRET)
    client = WeChatClient(WECHAT_APPID, WECHAT_SECRET)

    with open(WECHAT_MENU_FILE) as f:
        client.menu.create(json.load(f))
Esempio n. 22
0
 def test_two_client_not_equal(self):
     client2 = WeChatClient("654321", "654321", "987654321")
     self.assertNotEqual(self.client, client2)
     self.assertNotEqual(self.client.user, client2.user)
     self.assertNotEqual(id(self.client.menu), id(client2.menu))
     with HTTMock(wechat_api_mock):
         self.client.fetch_access_token()
         self.assertNotEqual(self.client.access_token, client2.access_token)
Esempio n. 23
0
 def test_shove_storage_access_token(self):
     uri = "memory://"
     client = WeChatClient(self.app_id, self.secret, session=uri)
     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)
Esempio n. 24
0
def sendMessage(openId, text=''):
    APP_ID = 'wx21c7501e68d463df'
    APP_SECRET = '82fcc8a8bb59b2318f1e97a6292a7ecc'
    client = WeChatClient(APP_ID, APP_SECRET)
    try:
        client.message.send_text(openId, text)
    except WeChatClientException as e:
        print e
Esempio n. 25
0
 def init_app(self, app):
     """从 flask app 中初始化
     """
     self.wx_client = WeChatClient(app.config.get('WX_APP_ID'),
                                   app.config.get('WX_SECRET'))
     self.handlers = []
     for handler_class in default_handlers:
         self.register_handler(handler_class(wx_client=self.wx_client))
Esempio n. 26
0
 def test_two_client_not_equal(self):
     client2 = WeChatClient('654321', '654321', '987654321')
     assert self.client != client2
     assert self.client.user != client2.user
     assert id(self.client.menu) != id(client2.menu)
     with HTTMock(wechat_api_mock):
         self.client.fetch_access_token()
         assert self.client.access_token != client2.access_token
Esempio n. 27
0
    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))
Esempio n. 28
0
    def post(self, request):
        appid = 'wx913f229778bb0119'
        secret = '0e927f55e8c7f21b566b70881d8c130e'
        client = WeChatClient(appid, secret, session=CustomStorage())
        # user = client.user.get('openid')
        wxa = WeChatWxa(client)
        token = wxa.code_to_session(js_code=request.data['code'])

        return Response(data={'token': token}, status=status.HTTP_200_OK)
Esempio n. 29
0
    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
Esempio n. 30
0
def create_menu(request):
    # 第一个参数是公众号里面的appID,第二个参数是appsecret
    # 老妈的
    # client = WeChatClient("wx2abf89713b9ec1ce", "7af55f1b8557c382e9507bb106204f57")
    # 测试的
    client = WeChatClient("wx7d69afbab1a0647d",
                          "8026876b1390670f3dca1f8f8e3ddc6f")
    client.menu.del_conditional(
        client.menu.get()["conditionalmenu"][0]["menuid"])
    client.menu.add_conditional({
        "button": [{
            "type":
            "view",
            "name":
            "歌曲44",
            "url":
            "https://router.map.qq.com/short?l=c94ba04ec32777ae43959c56b7c46e5e"
        }, {
            "type": "click",
            "name": "歌手77",
            "key": "V1001_TODAINGER"
        }, {
            "name":
            "菜单",
            "sub_button": [{
                "type":
                "view",
                "name":
                "搜索",
                "url":
                "https://mp.weixin.qq.com/s/xvFRKfLr_83H_5K7qZfBgQ"
            }, {
                "type": "view",
                "name": "视频",
                "url": "http://v.qq.com/"
            }, {
                "type": "click",
                "name": "赞一下我们",
                "key": "V1001_GOOD"
            }]
        }],
        "matchrule": {
            # "group_id": "2",
            "sex": "2",
            "country": "中国",
            # "province": "广东",
            # "city": "广州",
            "client_platform_type": "2"
        }
    })

    # print(client.menu.get_menu_info(),'\n')
    print(client.menu.get())
    # client.menu.delete()
    # print(client.menu.get_menu_info(), '\n', client.menu.get())
    return HttpResponse('ok')