Skip to content

Instantly share code, notes, and snippets.

@tonyseek
Last active April 6, 2019 12:54
Show Gist options
  • Save tonyseek/c31557e70065948a849d to your computer and use it in GitHub Desktop.
Save tonyseek/c31557e70065948a849d to your computer and use it in GitHub Desktop.
Fixes the nonstandard OAuth interface of Tencent WeChat with Flask-OAuthlib.
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)
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
@huxuan
Copy link

huxuan commented May 5, 2015

Great Job!

@junnplus
Copy link

junnplus commented Apr 8, 2016

在跳轉授權頁面url裏面,參數應該需要排序
http://mp.weixin.qq.com/wiki/4/9ac2e7b1f1d22e9e57260f6553822520.html

尤其注意:由于授权操作安全等级较高,所以在发起授权请求时,微信会对授权链接做正则强匹配校验,如果链接的参数顺序不对,授权页面将无法正常访问

所以

url = url.replace(query=url_encode(args), fragment='wechat_redirect')

應該替換成

url = url.replace(query=url_encode(args, sort=True), fragment='wechat_redirect')

@tonyseek
Copy link
Author

@junnplus 已修正, thx!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment