微信小程序獲取用戶唯一標(biāo)識(shí)(不用授權(quán))
? ? ? ?在做微信小程序開發(fā)時(shí),根據(jù)應(yīng)用的需要,可能會(huì)要求獲得用戶不同的信息和硬件設(shè)備不同的使用權(quán)限。前者比如:用戶標(biāo)識(shí)、頭像、昵稱、姓別、地址、手機(jī)號(hào)碼等,后者包括:地理位置、手機(jī)相冊、攝像頭等。根據(jù)小程序現(xiàn)有的規(guī)則,除“用戶標(biāo)識(shí)、頭像、昵稱、姓別”等信息之外,均需要用戶授權(quán)后才能使用。而且用戶的授權(quán)界面的喚醒又分為兩種方式,一是可以用代碼喚醒,另一種則必須使用指定類型的按鈕組件,用戶點(diǎn)擊該按鈕才能喚醒。
? ? ? ?本文主要介紹如何簡單有效地獲取用戶的唯一標(biāo)識(shí),獲取唯一標(biāo)識(shí)后,應(yīng)用程序就可以區(qū)別用戶。簡單來說,只要用戶打開小程序,則即可以確定用戶身份(無需登陸一說)。
? ? ? ?主要步驟如下:
? ? ? ?1、使用 wx.login({})?獲取臨時(shí)會(huì)話的 code
? ? ? ?2、使用 wx.request({}) 向開發(fā)者服務(wù)器(用戶自己服務(wù)器,非微信服務(wù)器)傳入第1步中獲得的code,在開發(fā)都服務(wù)器中向微信服務(wù)器指定的API地址發(fā)送請(qǐng)求,進(jìn)而返回所需信息。
>>開發(fā)者服務(wù)器向微信服務(wù)器發(fā)送帶code的請(qǐng)求代碼如下:
?public async System.Threading.Tasks.Task<XcxServer.MOpenIdInfo> GetOpenIdAsync(string p_code)
? ? ? ? {
? ? ? ? ? ? Dictionary<string, string> V_DirResult = new Dictionary<string, string>();
? ? ? ? ? ? string GetUrl = string.Format("https://api.weixin.qq.com/sns/jscode2session?appid={0}&secret={1}&js_code={2}&grant_type=authorization_code", _AppId, _AppSecret, p_code);
? ? ? ? ? ? //該地址為微信服務(wù)器指定獲得openid的地址。
? ? ? ? ? ? string GetResultStr = null;
? ? ? ? ? ? using (HttpClient V_Client = new HttpClient())
? ? ? ? ? ? {
? ? ? ? ? ? ? ? GetResultStr = await V_Client.GetStringAsync(GetUrl);
? ? ? ? ? ? }
? ? ? ? ? ? XcxServer.MOpenIdInfo OpenIdInfo = new XcxServer.MOpenIdInfo();
? ? ? ? ? ? if (!GetResultStr.Contains("openid"))
? ? ? ? ? ? {
? ? ? ? ? ? ? ? OpenIdInfo.errcode = "-2";
? ? ? ? ? ? ? ? OpenIdInfo.errmsg = "請(qǐng)求失敗" + GetResultStr;
? ? ? ? ? ? }
? ? ? ? ? ? else
? ? ? ? ? ? {
? ? ? ? ? ? ? ? OpenIdInfo = JsonConvert.DeserializeObject<XcxServer.MOpenIdInfo>(GetResultStr);
? ? ? ? ? ? }
? ? ? ? ? ? return OpenIdInfo;
? ? ? ? }
>>第1、2步的代碼可封裝如下:
const zmkGetOpenId = () => {
? let loginCodePromise =? new Promise((resolve, reject)=> {
? ? // 登錄
? ? wx.login({
? ? ? success: res => {
? ? ? ? if (res.code) {
? ? ? ? ? //console.log('登錄成功,Code=',res.code)
? ? ? ? ? resolve(res.code);
? ? ? ? } else {
? ? ? ? ? //console.log('登錄失敗!' + res.errMsg)
? ? ? ? ? reject();? }? }?})?});
? return loginCodePromise.then((tCode) => {
? let paramData = {
? ? ? tempCode: tCode
? ? }
? ? // 發(fā)送 res.code 到后臺(tái)換取 openId, sessionKey, unionId
? ? return?new?Promise((resolve,?reject)?=>?{
? ? wx.request({? url:?'http://localhost:5000/getuseropenid', //開發(fā)者服務(wù)器地址。
? ? ?method:?method,
? ? ? data:?updata,
? ? ? header:?{?'content-type':?'application/json',?},
? ? ? success(res)?{resolve(res)},
? ? ? fail(res)?{?reject(res)?}})
?})
})
}
>>調(diào)用封裝的代碼
Page({
? data:?{? userOpenId:null? },
? onLoad:?function?()?{
??? ? zmkGetOpenId().then((res)?=>?{
? ? ? userOpenId=res.data.openid;
? ? ? console.log(app.globalData.userOpenId)
? ? })
? },
})
? ? ? ?代碼中使用了Promise 語法,使邏輯變得清晰。后續(xù)將刊登如何最專業(yè)地獲取用戶信息或硬件設(shè)備的其他權(quán)限,歡迎大家關(guān)注。