唯一标识 微信小程序_微信小程序获取用户唯一标识(不用授权)

在做微信小程序开发时,根据应用的需要,可能会要求获得用户不同的信息和硬件设备不同的使用权限。前者比如:用户标识、头像、昵称、姓别、地址、手机号码等,后者包括:地理位置、手机相册、摄像头等。根据小程序现有的规则,除“用户标识、头像、昵称、姓别”等信息之外,均需要用户授权后才能使用。而且用户的授权界面的唤醒又分为两种方式,一是可以用代码唤醒,另一种则必须使用指定类型的按钮组件,用户点击该按钮才能唤醒。

本文主要介绍如何简单有效地获取用户的唯一标识,获取唯一标识后,应用程序就可以区别用户。简单来说,只要用户打开小程序,则即可以确定用户身份(无需登陆一说)。

主要步骤如下:

1、使用 wx.login({}) 获取临时会话的 code

2、使用 wx.request({}) 向开发者服务器(用户自己服务器,非微信服务器)传入第1步中获得的code,在开发都服务器中向微信服务器指定的API地址发送请求,进而返回所需信息。

>>开发者服务器向微信服务器发送带code的请求代码如下:

public async System.Threading.Tasks.Task GetOpenIdAsync(string p_code)        {

Dictionary V_DirResult = new Dictionary();

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);

//该地址为微信服务器指定获得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 = "请求失败" + GetResultStr;

}

else

{

OpenIdInfo = JsonConvert.DeserializeObject(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

}

// 发送 res.code 到后台换取 openId, sessionKey, unionId

return new Promise((resolve, reject) => {

wx.request({  url: 'http://localhost:5000/getuseropenid', //开发者服务器地址。

method: method,

data: updata,

header: { 'content-type': 'application/json', },

success(res) {resolve(res)},

fail(res) { reject(res) }})

})

})

}

>>调用封装的代码

Page({

data: {  userOpenId:null  },

onLoad: function () {

zmkGetOpenId().then((res) => {

userOpenId=res.data.openid;

console.log(app.globalData.userOpenId)

})

},

})

代码中使用了Promise 语法,使逻辑变得清晰。后续将刊登如何最专业地获取用户信息或硬件设备的其他权限,欢迎大家关注。


本文来自互联网用户投稿,文章观点仅代表作者本人,不代表本站立场,不承担相关法律责任。如若转载,请注明出处。 如若内容造成侵权/违法违规/事实不符,请点击【内容举报】进行投诉反馈!

相关文章

立即
投稿

微信公众账号

微信扫一扫加关注

返回
顶部