Last active
April 6, 2019 12:54
-
-
Save tonyseek/c31557e70065948a849d to your computer and use it in GitHub Desktop.
Fixes the nonstandard OAuth interface of Tencent WeChat with Flask-OAuthlib.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from .weixin_compat import fixup_weixin_oauth | |
oauth = OAuth() | |
weixin = oauth.remote_app( | |
'weixin', | |
app_key='WEIXIN', | |
request_token_params={'scope': 'snsapi_base'}, | |
base_url='https://api.weixin.qq.com', | |
authorize_url='https://open.weixin.qq.com/connect/oauth2/authorize', | |
access_token_url='https://api.weixin.qq.com/sns/oauth2/access_token', | |
# important: ignore the 'text/plain' said by weixin api and enforce the | |
# response be parsed as json. | |
content_type='application/json', | |
) | |
fixup_weixin_oauth(weixin) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from werkzeug.urls import url_parse, url_encode | |
def fixup_weixin_oauth(weixin): | |
"""Fixes the nonstandard OAuth interface of Tencent WeChat.""" | |
original_methods = { | |
'authorize': weixin.authorize, | |
'authorized_response': weixin.authorized_response, | |
} | |
def authorize(*args, **kwargs): | |
response = original_methods['authorize'](*args, **kwargs) | |
url = url_parse(response.headers['Location']) | |
args = url.decode_query() | |
# replace the nonstandard argument | |
args['appid'] = args.pop('client_id') | |
# replace the nonstandard fragment | |
url = url.replace(query=url_encode(args, sort=True), fragment='wechat_redirect') | |
response.headers['Location'] = url.to_url() | |
return response | |
def authorized_response(*args, **kwargs): | |
original_access_token_params = weixin.access_token_params | |
weixin.access_token_params = { | |
'appid': weixin.consumer_key, | |
'secret': weixin.consumer_secret, | |
} | |
response = original_methods['authorized_response'](*args, **kwargs) | |
weixin.access_token_params = original_access_token_params | |
return response | |
weixin.authorize = authorize | |
weixin.authorized_response = authorized_response |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
@junnplus 已修正, thx!