UniApp開發(fā)H5接入微信登錄的全過程
最近的uniapp開發(fā)中遇到了H5調(diào)微信授權(quán)登錄的業(yè)務(wù),記錄一下解決方法
微信授權(quán)
微信授權(quán)分為兩種類型:
靜默授權(quán):scope=snsapi_base。沒有彈窗,只能獲取到用戶的openid。
非靜默授權(quán):scope=snsapi_userinfo。有彈窗,需要用戶手動(dòng)點(diǎn)擊同意授權(quán),可獲取到用戶的openid、昵稱、頭像、性別。
以下為官方文檔中對(duì)兩種授權(quán)的解釋
關(guān)于網(wǎng)頁授權(quán)的兩種scope的區(qū)別說明
1、以snsapi_base為scope發(fā)起的網(wǎng)頁授權(quán),是用來獲取進(jìn)入頁面的用戶的openid的,并且是靜默授權(quán)并自動(dòng)跳轉(zhuǎn)到回調(diào)頁的。用戶感知的就是直接進(jìn)入了回調(diào)頁(往往是業(yè)務(wù)頁面)
2、以snsapi_userinfo為scope發(fā)起的網(wǎng)頁授權(quán),是用來獲取用戶的基本信息的。但這種授權(quán)需要用戶手動(dòng)同意,并且由于用戶同意過,所以無須關(guān)注,就可在授權(quán)后獲取該用戶的基本信息。
3、用戶管理類接口中的“獲取用戶基本信息接口”,是在用戶和公眾號(hào)產(chǎn)生消息交互或關(guān)注后事件推送后,才能根據(jù)用戶OpenID來獲取用戶基本信息。這個(gè)接口,包括其他微信接口,都是需要該用戶(即openid)關(guān)注了公眾號(hào)后,才能調(diào)用成功的。
微信授權(quán)的流程:
在微信的開放文檔中有詳細(xì)的說明,建議先閱讀文檔理清思路
解決思路
明白了具體的授權(quán)流程之后我們就可以來實(shí)現(xiàn)我們的業(yè)務(wù)了
1.正則匹配請求地址中的參數(shù)函數(shù)
getUrlCode(name) {
return decodeURIComponent((new RegExp('[?|&]' + name + '=' + '([^&;]+?)(&|#|;|$)').exec(location.href) ||[, ''])[1].replace(/\+/g, '%20')) || null
},2.進(jìn)入頁面時(shí)調(diào)用這個(gè)函數(shù)去看地址中有沒有code參數(shù)
getCode() {
let code = this.getUrlCode('code')
if (code === null || code === '') {
window.location. +
this.$common.wx.appID +
'&redirect_uri=' + encodeURIComponent(this.$common.wx.wxcallback) +
'&response_type=code&scope=snsapi_userinfo&state=1#wechat_redirect'
} else {
uni.$u.http.get('/rest/getOpenId', {
params: {
code: code
}
}).then(res => {
let openId = res.openid;
if (openId != null && openId != '') {
this.openId = openId
console.log(this.openId)
}
}).catch(err => {
})
}
},如果沒有code參數(shù)的話則請求微信官方的接口并獲取包含code的回調(diào)鏈接
3.使用code換取openid及access_token等參數(shù)
當(dāng)鏈接中有code的時(shí)候攜帶code請求下一個(gè)接口去獲取openid和access_token等參數(shù),這部分我是用Java寫的后端來實(shí)現(xiàn)的,代碼如下:
package tech.niua.rest.H5Controller;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.apache.http.HttpEntity;
import org.apache.http.HttpStatus;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import tech.niua.admin.common.constant.WeiXinProperties;
import tech.niua.common.model.ResultCode;
import tech.niua.common.model.ResultJson;
import tech.niua.core.annotation.Log;
import java.io.IOException;
@RestController
@RequestMapping("/rest")
public class H5Controller {
@Autowired
WeiXinProperties weiXinProperties;
/**
* 根據(jù)code獲取openid
*
* @param code
* @return
*/
@Log(value = "根據(jù)code獲取openid")
@GetMapping("/getOpenId")
public ResultJson getOpenId(String code) throws IOException {
String url = "https://api.weixin.qq.com/sns/oauth2/access_token?&appid=" + weiXinProperties.getAppid() + "&secret=" + weiXinProperties.getAppSecret() + "&code=" + code + "&grant_type=authorization_code";
CloseableHttpClient client = HttpClients.createDefault();
HttpGet httpGet = new HttpGet(url);
CloseableHttpResponse res = client.execute(httpGet);
if (res.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
HttpEntity entity = res.getEntity();
String result = EntityUtils.toString(entity, "UTF-8");
JSONObject jsonObject = JSON.parseObject(result);
return ResultJson.ok(jsonObject);
}
return ResultJson.failure(ResultCode.BAD_REQUEST);
}
}請求成功的話微信的接口會(huì)返回類似如下參數(shù)
{
"access_token":"ACCESS_TOKEN",
"expires_in":7200,
"refresh_token":"REFRESH_TOKEN",
"openid":"OPENID",
"scope":"SCOPE"
}參數(shù)說明
| 參數(shù) | 描述 |
|---|---|
| access_token | 網(wǎng)頁授權(quán)接口調(diào)用憑證,注意:此access_token與基礎(chǔ)支持的access_token不同 |
| expires_in | access_token接口調(diào)用憑證超時(shí)時(shí)間,單位(秒) |
| refresh_token | 用戶刷新access_token |
| openid | 用戶唯一標(biāo)識(shí),請注意,在未關(guān)注公眾號(hào)時(shí),用戶訪問公眾號(hào)的網(wǎng)頁,也會(huì)產(chǎn)生一個(gè)用戶和公眾號(hào)唯一的OpenID |
| scope | 用戶授權(quán)的作用域,使用逗號(hào)(,)分隔 |
請求錯(cuò)誤時(shí)會(huì)返回如下
{"errcode":40029,"errmsg":"invalid code"}4.拉取用戶信息(需scope為 snsapi_userinfo)
如果網(wǎng)頁授權(quán)作用域?yàn)閟nsapi_userinfo,則此時(shí)開發(fā)者可以通過access_token和openid拉取用戶信息了。
請求方法
http:GET(請使用https協(xié)議) https://api.weixin.qq.com/sns/userinfo?access_token=ACCESS_TOKEN&openid=OPENID&lang=zh_CN
參數(shù)說明
| 參數(shù) | 描述 |
|---|---|
| access_token | 網(wǎng)頁授權(quán)接口調(diào)用憑證,注意:此access_token與基礎(chǔ)支持的access_token不同 |
| openid | 用戶的唯一標(biāo)識(shí) |
| lang | 返回國家地區(qū)語言版本,zh_CN 簡體,zh_TW 繁體,en 英語 |
返回說明
正確時(shí)返回的JSON數(shù)據(jù)包如下:
{
"openid": "OPENID",
"nickname": NICKNAME,
"sex": 1,
"province":"PROVINCE",
"city":"CITY",
"country":"COUNTRY",
"headimgurl":"https://thirdwx.qlogo.cn/mmopen/g3MonUZtNHkdmzicIlibx6iaFqAc56vxLSUfpb6n5WKSYVY0ChQKkiaJSgQ1dZuTOgvLLrhJbERQQ4eMsv84eavHiaiceqxibJxCfHe/46",
"privilege":[ "PRIVILEGE1" "PRIVILEGE2" ],
"unionid": "o6_bmasdasdsad6_2sgVt7hMZOPfL"
}| 參數(shù) | 描述 |
|---|---|
| openid | 用戶的唯一標(biāo)識(shí) |
| nickname | 用戶昵稱 |
| sex | 用戶的性別,值為1時(shí)是男性,值為2時(shí)是女性,值為0時(shí)是未知 |
| province | 用戶個(gè)人資料填寫的省份 |
| city | 普通用戶個(gè)人資料填寫的城市 |
| country | 國家,如中國為CN |
| headimgurl | 用戶頭像,最后一個(gè)數(shù)值代表正方形頭像大小(有0、46、64、96、132數(shù)值可選,0代表640*640正方形頭像),用戶沒有頭像時(shí)該項(xiàng)為空。若用戶更換頭像,原有頭像URL將失效。 |
| privilege | 用戶特權(quán)信息,json 數(shù)組,如微信沃卡用戶為(chinaunicom) |
| unionid | 只有在用戶將公眾號(hào)綁定到微信開放平臺(tái)帳號(hào)后,才會(huì)出現(xiàn)該字段。 |
錯(cuò)誤時(shí)微信會(huì)返回JSON數(shù)據(jù)包如下(示例為openid無效):
{"errcode":40003,"errmsg":" invalid openid "}這樣業(yè)務(wù)就實(shí)現(xiàn)了,具體的其他接口請參照
微信開放文檔 (qq.com)https://developers.weixin.qq.com/doc/offiaccount/OA_Web_Apps/Wechat_webpage_authorization.html
總結(jié)
到此這篇關(guān)于UniApp開發(fā)H5接入微信登錄的文章就介紹到這了,更多相關(guān)UniApp H5接入微信登錄內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
JS如何對(duì)Iframe內(nèi)外頁面進(jìn)行操作總結(jié)
iframe標(biāo)簽是一個(gè)內(nèi)聯(lián)框架,即用來在當(dāng)前HTML頁面中嵌入另一個(gè)文檔的,且所有主流瀏覽器都支持iframe標(biāo)簽,這篇文章主要給大家介紹了關(guān)于JS如何對(duì)Iframe內(nèi)外頁面進(jìn)行操作的相關(guān)資料,需要的朋友可以參考下2021-10-10
設(shè)置checkbox為只讀(readOnly)的兩種方式
設(shè)置checkbox為只讀的方法有很多,在本文為大家詳細(xì)介紹下兩種比較實(shí)用的方法,感興趣的朋友不要錯(cuò)過2013-10-10
原生js實(shí)現(xiàn)的移動(dòng)端可拖動(dòng)進(jìn)度條插件功能詳解
這篇文章主要介紹了原生js實(shí)現(xiàn)的移動(dòng)端可拖動(dòng)進(jìn)度條插件功能,結(jié)合實(shí)例形式詳細(xì)分析了javascript拖動(dòng)進(jìn)度條插件的具體定義與使用技巧,需要的朋友可以參考下2019-08-08

