class WeChatOAuthTestCase(unittest.TestCase): app_id = '123456' secret = '123456' redirect_uri = 'http://localhost' def setUp(self): self.oauth = WeChatOAuth( self.app_id, self.secret, self.redirect_uri ) def test_get_authorize_url(self): authorize_url = self.oauth.authorize_url self.assertEqual( 'https://open.weixin.qq.com/connect/oauth2/authorize?appid=123456&redirect_uri=http%3A%2F%2Flocalhost' '&response_type=code&scope=snsapi_base#wechat_redirect', authorize_url ) def test_get_qrconnect_url(self): url = self.oauth.qrconnect_url self.assertEqual( 'https://open.weixin.qq.com/connect/qrconnect?appid=123456&redirect_uri=http%3A%2F%2Flocalhost' '&response_type=code&scope=snsapi_login#wechat_redirect', url ) def test_fetch_access_token(self): with HTTMock(wechat_api_mock): res = self.oauth.fetch_access_token('123456') self.assertEqual('ACCESS_TOKEN', res['access_token']) def test_refresh_access_token(self): with HTTMock(wechat_api_mock): res = self.oauth.refresh_access_token('123456') self.assertEqual('ACCESS_TOKEN', res['access_token']) def test_get_user_info(self): with HTTMock(wechat_api_mock): self.oauth.fetch_access_token('123456') res = self.oauth.get_user_info() self.assertEqual('OPENID', res['openid']) def test_check_access_token(self): with HTTMock(wechat_api_mock): self.oauth.fetch_access_token('123456') res = self.oauth.check_access_token() self.assertEqual(True, res) def test_reraise_requests_exception(self): @urlmatch(netloc=r'(.*\.)?api\.weixin\.qq\.com$') def _wechat_api_mock(url, request): return {'status_code': 404, 'content': '404 not found'} try: with HTTMock(_wechat_api_mock): self.oauth.fetch_access_token('123456') except WeChatClientException as e: self.assertEqual(404, e.response.status_code)
class WeChatOAuthTestCase(unittest.TestCase): app_id = "123456" secret = "123456" redirect_uri = "http://localhost" def setUp(self): self.oauth = WeChatOAuth(self.app_id, self.secret, self.redirect_uri) def test_get_authorize_url(self): authorize_url = self.oauth.authorize_url self.assertEqual( "https://open.weixin.qq.com/connect/oauth2/authorize?appid=123456&redirect_uri=http%3A%2F%2Flocalhost" "&response_type=code&scope=snsapi_base#wechat_redirect", authorize_url, ) def test_get_qrconnect_url(self): url = self.oauth.qrconnect_url self.assertEqual( "https://open.weixin.qq.com/connect/qrconnect?appid=123456&redirect_uri=http%3A%2F%2Flocalhost" "&response_type=code&scope=snsapi_login#wechat_redirect", url, ) def test_fetch_access_token(self): with HTTMock(wechat_api_mock): res = self.oauth.fetch_access_token("123456") self.assertEqual("ACCESS_TOKEN", res["access_token"]) def test_refresh_access_token(self): with HTTMock(wechat_api_mock): res = self.oauth.refresh_access_token("123456") self.assertEqual("ACCESS_TOKEN", res["access_token"]) def test_get_user_info(self): with HTTMock(wechat_api_mock): self.oauth.fetch_access_token("123456") res = self.oauth.get_user_info() self.assertEqual("OPENID", res["openid"]) def test_check_access_token(self): with HTTMock(wechat_api_mock): self.oauth.fetch_access_token("123456") res = self.oauth.check_access_token() self.assertEqual(True, res) def test_reraise_requests_exception(self): @urlmatch(netloc=r"(.*\.)?api\.weixin\.qq\.com$") def _wechat_api_mock(url, request): return {"status_code": 404, "content": "404 not found"} try: with HTTMock(_wechat_api_mock): self.oauth.fetch_access_token("123456") except WeChatClientException as e: self.assertEqual(404, e.response.status_code)
class WeChatOAuthTestCase(unittest.TestCase): app_id = "123456" secret = "123456" redirect_uri = "http://localhost" def setUp(self): self.oauth = WeChatOAuth(self.app_id, self.secret, self.redirect_uri) def test_get_authorize_url(self): authorize_url = self.oauth.authorize_url self.assertEqual( "https://open.weixin.qq.com/connect/oauth2/authorize?appid=123456&redirect_uri=http%3A//localhost&response_type=code&scope=snsapi_base#wechat_redirect", # NOQA authorize_url, ) def test_get_qrconnect_url(self): url = self.oauth.qrconnect_url self.assertEqual( "https://open.weixin.qq.com/connect/qrconnect?appid=123456&redirect_uri=http%3A//localhost&response_type=code&scope=snsapi_login#wechat_redirect", # NOQA url, ) def test_fetch_access_token(self): with HTTMock(wechat_api_mock): res = self.oauth.fetch_access_token("123456") self.assertEqual("ACCESS_TOKEN", res["access_token"]) def test_refresh_access_token(self): with HTTMock(wechat_api_mock): res = self.oauth.refresh_access_token("123456") self.assertEqual("ACCESS_TOKEN", res["access_token"]) def test_get_user_info(self): with HTTMock(wechat_api_mock): self.oauth.fetch_access_token("123456") res = self.oauth.get_user_info() self.assertEqual("OPENID", res["openid"]) def test_check_access_token(self): with HTTMock(wechat_api_mock): self.oauth.fetch_access_token("123456") res = self.oauth.check_access_token() self.assertEqual(True, res) def test_reraise_requests_exception(self): @urlmatch(netloc=r"(.*\.)?api\.weixin\.qq\.com$") def _wechat_api_mock(url, request): return {"status_code": 404, "content": "404 not found"} try: with HTTMock(_wechat_api_mock): self.oauth.fetch_access_token("123456") except WeChatClientException as e: self.assertEqual(404, e.response.status_code)
class WeChatOAuthTestCase(unittest.TestCase): app_id = '123456' secret = '123456' redirect_uri = 'http://localhost' def setUp(self): self.oauth = WeChatOAuth(self.app_id, self.secret, self.redirect_uri) def test_get_authorize_url(self): authorize_url = self.oauth.authorize_url self.assertEqual( 'https://open.weixin.qq.com/connect/oauth2/authorize?appid=123456&redirect_uri=http%3A//localhost&response_type=code&scope=snsapi_base#wechat_redirect', # NOQA authorize_url) def test_get_qrconnect_url(self): url = self.oauth.qrconnect_url self.assertEqual( 'https://open.weixin.qq.com/connect/qrconnect?appid=123456&redirect_uri=http%3A//localhost&response_type=code&scope=snsapi_login#wechat_redirect', # NOQA url) def test_fetch_access_token(self): with HTTMock(wechat_api_mock): res = self.oauth.fetch_access_token('123456') self.assertEqual('ACCESS_TOKEN', res['access_token']) def test_refresh_access_token(self): with HTTMock(wechat_api_mock): res = self.oauth.refresh_access_token('123456') self.assertEqual('ACCESS_TOKEN', res['access_token']) def test_get_user_info(self): with HTTMock(wechat_api_mock): self.oauth.fetch_access_token('123456') res = self.oauth.get_user_info() self.assertEqual('OPENID', res['openid']) def test_check_access_token(self): with HTTMock(wechat_api_mock): self.oauth.fetch_access_token('123456') res = self.oauth.check_access_token() self.assertEqual(True, res) def test_reraise_requests_exception(self): @urlmatch(netloc=r'(.*\.)?api\.weixin\.qq\.com$') def _wechat_api_mock(url, request): return {'status_code': 404, 'content': '404 not found'} try: with HTTMock(_wechat_api_mock): self.oauth.fetch_access_token('123456') except WeChatClientException as e: self.assertEqual(404, e.response.status_code)
def authenticate(self, code=None, redirect_uri=None, state=None): oauth_client = WeChatOAuth(app_id=settings.WX_APPID, secret=settings.WX_APPSECRET, redirect_uri=redirect_uri, scope='snsapi_base', state=state) try: oauth_client.fetch_access_token(code) return UserModel.objects.get(pk=oauth_client.open_id) except WeChatOAuthException as e: logger.warning('Failed to get access token due to %s', e) return None except UserModel.DoesNotExist: return make_guest(pk=oauth_client.open_id, nickname=oauth_client.open_id)
def authenticate(self, code=None, redirect_uri=None, state=None): oauth_client = WeChatOAuth( app_id=settings.WX_APPID, secret=settings.WX_APPSECRET, redirect_uri=redirect_uri, scope='snsapi_base', state=state ) UserModel = get_user_model() try: oauth_client.fetch_access_token(code) return UserModel.objects.get(pk=oauth_client.open_id) except WeChatOAuthException as e: logger.warning('Failed to get access token due to %s', e) return None except UserModel.DoesNotExist: return make_guest(pk=oauth_client.open_id, nickname=oauth_client.open_id)
def returned_wrapper(request, *args, **kwargs): try: user = request.session.get('user', None) if user is None: code = request.GET.get('code', None) auth = WeChatOAuth(settings.WECHAT_APPKEY, settings.WECHAT_SECRET, redirect_uri=request.build_absolute_uri( request.get_full_path())) if code is None: return HttpResponseRedirect(auth.authorize_url) access = auth.fetch_access_token(code) # auth.refresh_access_token(access.get('refresh_token')) userinfo = auth.get_user_info() request.session['user'] = userinfo request.session['access'] = access request.session.set_expiry(int(access.get('expires_in'))) except WeChatOAuthException as e: # raise e auth = WeChatOAuth(settings.WECHAT_APPKEY, settings.WECHAT_SECRET, redirect_uri=request.build_absolute_uri( request.get_full_path())) return HttpResponseRedirect(auth.authorize_url) return func(request, *args, **kwargs)
def get_authenticate_header(self, request): """ If a request is unauthenticated, set wechat login url in the WWW-Authenticate header. """ current_state = request.META.get('HTTP_X_REFERER') or request.META.get('HTTP_REFERER', '/') oauth_client = WeChatOAuth( app_id=settings.WX_APPID, secret=settings.WX_APPSECRET, redirect_uri=self.request.build_absolute_uri(reverse('oauth_complete')), scope='snsapi_base', state=quote_plus(current_state) ) return oauth_client.authorize_url
class WeChatOAuthTestCase(unittest.TestCase): app_id = '123456' secret = '123456' redirect_uri = 'http://localhost' def setUp(self): self.oauth = WeChatOAuth( self.app_id, self.secret, self.redirect_uri ) def test_get_authorize_url(self): authorize_url = self.oauth.authorize_url self.assertEqual( 'https://open.weixin.qq.com/connect/oauth2/authorize?appid=123456&redirect_uri=http%3A//localhost&response_type=code&scope=snsapi_base#wechat_redirect', # NOQA authorize_url ) def test_get_qrconnect_url(self): url = self.oauth.qrconnect_url self.assertEqual( 'https://open.weixin.qq.com/connect/qrconnect?appid=123456&redirect_uri=http%3A//localhost&response_type=code&scope=snsapi_login#wechat_redirect', # NOQA url ) def test_fetch_access_token(self): with HTTMock(wechat_api_mock): res = self.oauth.fetch_access_token('123456') self.assertEqual('ACCESS_TOKEN', res['access_token']) def test_refresh_access_token(self): with HTTMock(wechat_api_mock): res = self.oauth.refresh_access_token('123456') self.assertEqual('ACCESS_TOKEN', res['access_token']) def test_get_user_info(self): with HTTMock(wechat_api_mock): self.oauth.fetch_access_token('123456') res = self.oauth.get_user_info() self.assertEqual('OPENID', res['openid']) def test_check_access_token(self): with HTTMock(wechat_api_mock): self.oauth.fetch_access_token('123456') res = self.oauth.check_access_token() self.assertEqual(True, res)
def get(self, request): # 微信授权配置 OauthWX = WeChatOAuth(app_id=settings.WXAPPID, secret=settings.WXAPPSECRET, redirect_uri=settings.REDIRECT_URI, scope=settings.SCOPE, state='/') # 微信授权url auth_url = OauthWX.authorize_url # pc_auth_url = OauthWX.qrconnect_url return Response({'auth_url': auth_url})
class WeChatOAuthTestCase(unittest.TestCase): app_id = '123456' secret = '123456' redirect_uri = 'http://localhost' def setUp(self): self.oauth = WeChatOAuth(self.app_id, self.secret, self.redirect_uri) def test_get_authorize_url(self): authorize_url = self.oauth.authorize_url self.assertEqual( 'https://open.weixin.qq.com/connect/oauth2/authorize?appid=123456&redirect_uri=http%3A//localhost&response_type=code&scope=snsapi_base#wechat_redirect', # NOQA authorize_url) def test_get_qrconnect_url(self): url = self.oauth.qrconnect_url self.assertEqual( 'https://open.weixin.qq.com/connect/qrconnect?appid=123456&redirect_uri=http%3A//localhost&response_type=code&scope=snsapi_login#wechat_redirect', # NOQA url) def test_fetch_access_token(self): with HTTMock(wechat_api_mock): res = self.oauth.fetch_access_token('123456') self.assertEqual('ACCESS_TOKEN', res['access_token']) def test_refresh_access_token(self): with HTTMock(wechat_api_mock): res = self.oauth.refresh_access_token('123456') self.assertEqual('ACCESS_TOKEN', res['access_token']) def test_get_user_info(self): with HTTMock(wechat_api_mock): self.oauth.fetch_access_token('123456') res = self.oauth.get_user_info() self.assertEqual('OPENID', res['openid']) def test_check_access_token(self): with HTTMock(wechat_api_mock): self.oauth.fetch_access_token('123456') res = self.oauth.check_access_token() self.assertEqual(True, res)
def wechat(request): redirect_uri = 'http://oauth.gjingxi.com/oauth/wechat/' codes = request.GET.get('code', None) oauth = WeChatOAuth(settings.WECHAT_APPKEY.strip(), settings.WECHAT_SECRET, redirect_uri=redirect_uri, scope='snsapi_userinfo') if codes is None: return HttpResponseRedirect(oauth.authorize_url) try: access = oauth.fetch_access_token(codes) oauth.refresh_access_token(access.get('refresh_token')) user = oauth.get_user_info() return HttpResponse(json.dumps(user)) except Exception as e: print e return HttpResponse(e.message)
def authorize(request, func): ''' 认证接口 :param request: :return: ''' code = request.GET.get('code', None) auth = WeChatOAuth(settings.WECHAT_APPKEY, settings.WECHAT_SECRET, redirect_uri=request.build_absolute_uri( request.get_full_path())) if code is None: return HttpResponseRedirect(auth.authorize_url) access = auth.fetch_access_token(code) auth.refresh_access_token(access.get('refresh_token')) user = auth.get_user_info() return JsonResponse(user)
def buy(request): code_ = request.GET.get('code', None) oauth = WeChatOAuth(settings.WECHAT_APPKEY, settings.WECHAT_SECRET, redirect_uri=request.build_absolute_uri( request.get_full_path())) if code_ is None: return HttpResponseRedirect(oauth.authorize_url) access = oauth.fetch_access_token(code_) oauth.refresh_access_token(access.get('refresh_token')) user = oauth.get_user_info() request.session['openid'] = user.get('openid') # nick = user.get('nickname') items = get_object_or_404(Goods, pk=request.GET.get('id')) items.quantity = request.GET.get('q') items.amount = float(float(items.price) * float(items.quantity)) items.nick = user.get('nickname') return render(request, 'mobile/buy/pay.html', locals())
def get(self, request): # 登陆成功后code code = request.query_params.get('code') if not code: print(1) return Response({'message': '缺少code'}, status=status.HTTP_400_BAD_REQUEST) # 微信授权配置 OauthQQ = WeChatOAuth(app_id=settings.WXAPPID, secret=settings.WXAPPSECRET, redirect_uri=settings.REDIRECT_URI, scope=settings.SCOPE, state='/') try: OauthQQ.fetch_access_token(code) # 用户信息 wx_user_content = OauthQQ.get_user_info() except Exception: return Response({'message': '微信服务器异常'}, status=status.HTTP_503_SERVICE_UNAVAILABLE) # 判断用户是否绑定缘道美 try: OAuthWXUser.objects.get(openid=wx_user_content['openid']) except Exception as e: if len(wx_user_content['province']) == 0: wx_user_content['province'] = "0" if len(wx_user_content['city']) == 0: wx_user_content['city'] = "0" print(wx_user_content) # 获取序列化器,校验数据 try: serializer = WXAuthUserSerializer(data=wx_user_content) serializer.is_valid(raise_exception=True) serializer.save() except Exception as e: print(e) # 加密openid返回token # access_token_openid = generate_save_token(wx_user_content['openid']) # return Response({'access_token': access_token_openid}) # oauth_user_wx = OAuthWXUser.objects.get(openid=wx_user_content['openid']) # 如果用户微信已经绑定缘道美,直接生成JWT token,并返回 jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER user = authenticate(username=wx_user_content['openid'], password=wx_user_content["unionid"]) payload = jwt_payload_handler(user) token = jwt_encode_handler(payload) login(request, user) # 暂时返回token..具体看需求 response = Response({ 'token': token, 'user_id': user.id, 'username': user.first_name, 'headimgUrl': user.headimgUrl }) return response
from wechatpy import WeChatClient, WeChatOAuth, WeChatPay from wechatpy import parse_message, create_reply from wechatpy.crypto import WeChatCrypto from wechatpy.exceptions import InvalidAppIdException from wechatpy.exceptions import InvalidSignatureException from wechatpy.utils import check_signature from weshop.utils import ezlogger from configs.config import Config from . import wechat from .chatbot import bot_reply logger = ezlogger.get_logger('wechat', use_stream=False) wechat_client = WeChatClient(Config.WECHAT_APP_ID, Config.WECHAT_APP_SECRET) wechat_oauth = WeChatOAuth(app_id=Config.WECHAT_APP_ID, secret=Config.WECHAT_APP_SECRET, scope='snsapi_userinfo', redirect_uri='') wechat_pay = WeChatPay(appid=Config.WECHAT_APP_ID, api_key=Config.WEPAY_API_KEY, mch_id=Config.WEPAY_MCH_ID, mch_cert=Config.WEPAY_MCH_CERT_PATH, mch_key=Config.WEPAY_MCH_KEY_PATH) wechat_client.menu.create({ "button": [{ "type": "view", "name": "快速订水", "url": "http://www.rockbot.top/weshop/quickbuy" }, { "type": "view", "name": "水站商城",
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) oauth_session.set('refresh_token', token['refresh_token'], 7000) if access_token: try:
def setUp(self): self.oauth = WeChatOAuth(self.app_id, self.secret, self.redirect_uri)
def get(self, request): """ 处理微信事件推送 --- parameters: - name: code description: 授权码 type: string paramType: query required: true - name: invitation_code description: 邀请码 type: string paramType: query required: false - name: url description: 跳转前端 url type: string paramType: query required: true """ invitation_code = request.GET.get('invitation_code', '') invitation_code = InvitationCode.objects.filter( code=invitation_code).first() redirect_url = request.GET.get('url', '') oauth_code = request.GET.get('code', '') redirect_url_parts = list(urlparse(redirect_url)) if not redirect_url: return BackstageHTTPResponse( code=BackstageHTTPResponse.API_HTTP_CODE_INVILID_PARAMS, message='缺少跳转url', ).to_response() if not oauth_code: return BackstageHTTPResponse( code=BackstageHTTPResponse.API_HTTP_CODE_INVILID_PARAMS, message='缺少授权码', ).to_response() oauth = WeChatOAuth(settings.WECHAT_APPID, settings.WECHAT_APPSECRET, redirect_url) oauth.fetch_access_token(oauth_code) wechat_user = oauth.get_user_info() WechatUser.objects.update_or_create(openid=oauth.open_id, defaults=wechat_user) user = User.objects.filter(openid=oauth.open_id, is_active=True).first() if not user: url = settings.A3_FE_REGISTER_URL url += '?invitation_code=%s&openid=%s' % (getattr( invitation_code, 'code', ''), oauth.open_id) return Response(status=HTTP_302_FOUND, headers={'Location': url}) logger.info('redirect_url_parts: %s' % redirect_url_parts) new_query_dict = QueryDict('', mutable=True) original_url_path = re.findall(r'([^?]*)(?:\?.*)?', redirect_url_parts[5])[0] if '?' in redirect_url_parts[5]: original_url_query = re.findall(r'\?(.*)', redirect_url_parts[5])[0] new_query_dict.update(QueryDict(original_url_query, mutable=True)) if user: user.update_wechat_mobile(logger=logger) login(request, user) # 微信不允许跨域携带 cookie,通过 header 来传 session_key new_query_dict.update({'session_id': request.session.session_key}) if invitation_code: new_query_dict.update({ 'invitation_code': invitation_code.code, }) new_query_dict.update({'openid': oauth.open_id}) if redirect_url_parts[2].strip('/'): redirect_url_parts[ 2] = redirect_url_parts[2] + '#%s' % original_url_path else: redirect_url_parts[2] = '/#%s' % original_url_path redirect_url_parts[4] = new_query_dict.urlencode() redirect_url_parts[5] = '' redirect_url = urlunparse(redirect_url_parts) return Response(status=HTTP_302_FOUND, headers={'Location': redirect_url})
def setUp(self): self.oauth = WeChatOAuth( self.app_id, self.secret, self.redirect_uri )