實現步驟
2 第二步:通過code換取網頁授權access_token
4 第四步:拉取用戶信息(需scope為 snsapi_userinfo)
參考文檔
准備材料
一個服務號(已認證),確保網頁授權權限已開通
1、點擊修改,跳轉到公眾號設置頁,此處需要添加一個域名文件校驗
2、通過authorize獲取的code
調用https://open.weixin.qq.com/connect/oauth2/authorize
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"/> <meta http-equiv="X-UA-Compatible" content="IE=edge"/> <meta name="viewport" content="width=device-width, initial-scale=1.0"/> <title>Document</title> </head> <style> </style> <body> <div id="container"> </div> <script> window.appId = `${appId}`
//注意:此處redirect_uri需要使用encodeURIComponent(該方法瀏覽器自帶)轉義 let local = "http://xxx" // 跳轉到授權頁面 window.location.href = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=" + window.appId + "&redirect_uri=" + encodeURIComponent(local) + "&response_type=code&scope=snsapi_userinfo&state=1#wechat_redirect"; </script> </body> </html>
參數說明:
snsapi_base與snsapi_userinfo屬於微信網頁授權獲取用戶信息的兩種作用域
snsapi_base只能獲取access_token和openID
snsapi_userinfo可以獲取更詳細的用戶資料,比如頭像、昵稱、性別等,該種形式會喚醒授權頁面
3、調用https://api.weixin.qq.com/sns/oauth2/access_token,獲取access_token
返回值如下
{"access_token":"accesstoken","refresh_token":"refreshtoken","openid":"openId","scope":"snsapi_userinfo","expires_in":7200}
常見錯誤碼發生情況
{"errcode":40029,"errmsg":"invalid code, rid: 620e3db2-410d5515-117f31ac"}
這種問題一般都發生在code上,要檢查code是不是有值並且是不是重復調用了
4、根據accessToken和openId查詢用戶信息,調用https://api.weixin.qq.com/sns/userinfo?access_token=accessToken&openid=openIdlang=zh_CN
返回值如下
{"country":"","province":"","city":"","openid":"openid","sex":0,"nickname":"sum墨","headimgurl":"https://thirdwx.qlogo.cn/mmopen/vi_32/KqPuMLU8JmRIlicUSvia4PR0vNKWKLFmfR6icibJ2Us7EyZXbZaKBd30qjGYJJSkmdHoib66wiaicQia61R34xC7Jr8EJg/132","language":"","privilege":[]}