每一個(gè)微信小程序?qū)?yīng)每一個(gè)用戶都有一個(gè)固定的ID,這個(gè)ID就是openid。 博主想把“小汽車保養(yǎng)里程碑單機(jī)版”搬上微信小程序,第一件事情應(yīng)該就是在小程序中能夠識(shí)別不同的用戶,每個(gè)用戶自己保存自己的數(shù)據(jù),需要一個(gè)唯一的識(shí)別號(hào),就是這個(gè)openid。
先看看小程序官方的說(shuō)明:
第一步、調(diào)用 wx.login() 獲取 臨時(shí)登錄憑證code ,并回傳到開(kāi)發(fā)者服務(wù)器。
第二步、調(diào)用 auth.code2Session 接口,換取 用戶唯一標(biāo)識(shí) OpenID 。
博主第一次接觸這些功能,感覺(jué)有點(diǎn)復(fù)雜呢,不過(guò)用了一天時(shí)間,也還是搞定了獲取openid。首先在小程序中弄一個(gè)按鈕:
?ts中定義點(diǎn)擊按鈕,第一步訪問(wèn)微信的服務(wù)器獲得一個(gè)code。
user_login: function () {
wx.login({
success: (res0) =>
{
console.log(res0);
// let code = res.code
let that = this
wx.request
({
url: 'https://w1914z4829.zicp.fun/user_code',
method: "POST", //請(qǐng)求的方式
data: { code: res0.code },
success: (res1) => { console.log(res1) , that.setData({ openid_list: res1 }) }
})
},
})
},
拿到code后,繼續(xù)訪問(wèn)自己的后端服務(wù)器。后端服務(wù)器技術(shù)棧是C#的webapi + EFcore + SQLite。后端服務(wù)器接到一個(gè)post請(qǐng)求,code在http的報(bào)文中:
//-------POST---user_code API-----------
app.MapPost("/user_code", async (HttpRequest request) =>
{
var user_code = await request.ReadFromJsonAsync<user_code>();
string openid = null;
if (user_code != null)
{
openid = get_openid(user_code.code);
Console.Write("openid:" + openid);
}
return openid;
});
后端服務(wù)器再去請(qǐng)求微信的服務(wù)器:
string get_openid(string js_code)//獲取前端傳過(guò)來(lái)的值
{
string url = "https://api.weixin.qq.com/sns/jscode2session?appid=wx1853c69dc576xxxx&secret=6859400ccef19af901a8cbfb167exxxx&js_code=" + js_code + "&grant_type=authorization_code";
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.Method = "GET";
request.ContentType = "text/html;charset=UTF-8";
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
Stream myResponseStream = response.GetResponseStream();
StreamReader myStreamReader = new StreamReader(myResponseStream, Encoding.UTF8);
string retString = myStreamReader.ReadToEnd();
myStreamReader.Close();
myResponseStream.Close();
return retString;
}
微信服務(wù)器返回了openid給我的后端服務(wù)器,還返回了session key,暫時(shí)不知道拿來(lái)做什么。
后端服務(wù)器API把openid返回給了微信小程序,小程序把openid顯示了出來(lái)。
文章來(lái)源:http://www.zghlxwxcb.cn/news/detail-599808.html
?有了這個(gè)openid,小程序就可以區(qū)分用戶的數(shù)據(jù),我只需要在數(shù)據(jù)庫(kù)的表中加一個(gè)openid字段,每次用戶提交數(shù)據(jù),保存上相應(yīng)的openid,這些數(shù)據(jù)就自然屬于這個(gè)用戶了。文章來(lái)源地址http://www.zghlxwxcb.cn/news/detail-599808.html
到了這里,關(guān)于用戶登錄 openid(微信小程序無(wú)師自通三)的文章就介紹完了。如果您還想了解更多內(nèi)容,請(qǐng)?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!