1200字范文,内容丰富有趣,写作的好帮手!
1200字范文 > FastAPI 实现网页授权获取微信用户基本信息-正式环境

FastAPI 实现网页授权获取微信用户基本信息-正式环境

时间:2019-10-10 00:13:33

相关推荐

FastAPI 实现网页授权获取微信用户基本信息-正式环境

文章目录

一、怎么实现微信扫码登录?二、公众号设置三、配置MP_verify_lgErIaiJeOtfLiru.txt四、获取开发者密码五、使用步骤第一步:用户同意授权,获取code第二步:通过code换取网页授权access_token第三步:拉取用户信息(需scope为 snsapi_userinfo)

一、怎么实现微信扫码登录?

该模式整体流程为:

第三方发起微信授权登录请求,微信用户允许授权第三方应用后,微信会拉起应用或重定向到第三方网站,并且带上授权临时票据code参数;通过code参数加上AppID和AppSecret等,通过API换取access_token;通过access_token进行接口调用,获取用户基本数据资源或帮助用户实现基本操作。

获取access_token时序图:

二、公众号设置

注意:个人认证的公众号没有 网页授权获取微信用户基本信息 的权限

三、配置MP_verify_lgErIaiJeOtfLiru.txt

# coding=gbkfrom fastapi import FastAPIfrom starlette.staticfiles import StaticFilesapp = FastAPI()app.mount("/", StaticFiles(directory="./app/static"), name="static")

四、获取开发者密码

获取AppSecret 需要 注册微信扫码,然后输入公众号登录密码。

五、使用步骤

第一步:用户同意授权,获取code

获取code有二种方式,在网站应用微信登录开发指南中有详细描述。

第一种是需要跳转到微信域下,显示二维码供用户扫码登录,用户授权成功后带code跳转回平台链接

第二种在平台内使用js内嵌微信登录二维码,用户授权成功后带code跳转回平台链接,可以根据平台需要修改二维码样式

本次文章使用的由链接直接获取code并回调至平台

https://open./connect/oauth2/authorize?appid=APPID&redirect_uri=REDIRECT_URI&response_type=code&scope=SCOPE&state=STATE#wechat_redirect

参数说明:

1.SCOPE参数是应用授权作用域,snsapi_base (不弹出授权页面,直接跳转,只能获取用户openid),snsapi_userinfo (弹出授权页面,可通过openid拿到昵称、性别、所在地。并且, 即使在未关注的情况下,只要用户授权,也能获取其信息 )

2.REDIRECT_URI参数是重定向地址,需要进行UrlEncode

生成的用于获取code的链接

https://open./connect/oauth2/authorize?appid=wx648f8575ec49b50a&redirect_uri=http%3a%2f%2f127.0.0.1%3a8000%2f%2fauth%2flogin%2fwx%2f&response_type=code&scope=snsapi_base&state=111#wechat_redirect

也可以是用这个链接自己生成一个二维码,方便手机测试

第二步:通过code换取网页授权access_token

代码如下:

@router.get("/login/wx/",tags=["微信登录"],responses=ResponsesExampleVale({"code": 200,"message": "登录成功!","content": {}}))async def login_wx(request: Request,code: str, # 返回类型,请填写code"state: str, # 重定向后会带上state参数,开发者可以填写a-zA-Z0-9的参数值,最多128字节):# 通过code换取网页授权access_tokenlogger.info(f"code: {code}, state: {state}")data = await WXAPI.userinfo(code)if data:return HttpResponseModel(code=200,message="获取成功",content=data)

第三步:拉取用户信息(需scope为 snsapi_userinfo)

代码如下:

# conding=gbkfrom app.utils.soa import RequestSessionManagerfrom aiohttp import ClientResponseErrorfrom extensions.logger import loggerimport jsonclass WXAPI:appID = "APPID"appsecret = "appsecret"@classmethodasync def __request(cls, url):with RequestSessionManager() as requests:async with requests.get(url=url, timeout=10) as resp:try:resp.raise_for_status()data = json.loads(await resp.text())logger.info(f"ret {data}")return dataexcept ClientResponseError as e:logger.info(e)@classmethodasync def access_token(cls, code):""" 通过code换取网页授权access_token """url = f"https://api./sns/oauth2/access_token" \f"?appid={cls.appID}" \f"&secret={cls.appsecret}" \f"&code={code}" \f"&grant_type=authorization_code"return await cls.__request(url)@classmethodasync def userinfo(cls, code):""" 拉取用户信息 """data = await cls.access_token(code)if data:if data['scope'] == "snsapi_userinfo":url = f"https://api./sns/userinfo" \f"?access_token={data['access_token']}" \f"&openid={data['openid']}" \f"&lang=zh_CN"return await cls.__request(url)else:return {"appid": data['openid']}


本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。