微信小程序获取用户openid

微信小程序获取用户openid,第1张

微信小程序获取用户openid

首先调用wx.login() 获取登录凭证(code),再通过登录凭证(code)获取用户登录信息,包括用户的唯一标识(openid) 及本次登录的会话密钥(session_key)。

app.js代码
//app.js
globalData: {
	userInfo:null,
	openid:null,
	session_key:null,
	apiUrl:'http://localhost:1234/api/index.aspx',//请求接口地址
},
getUserProfile(e) {
	var that = this
	wx.getUserProfile({
		desc: '获取用户信息',
		success: (res) => {
			wx.showToast({
				title: '获取中...',
				duration: 2000,
				icon: 'loading',
				mask:true,
			})
			that.globalData.userInfo = res.userInfo
			//登录
			wx.login({
				success: res => {
				//根据code获取openid,session_key
					if (res.code) {
						//发起网络请求
						wx.request({
						url: that.globalData.apiUrl,
						data: {
							code: res.code,
							parameter: 'onLogin'
						},
						header: {
							'content-type': 'application/json'
						},
						success: function(res) {
							console.log(res.data.openid);//openid
							console.log(res.data.session_key);//session_key
							that.globalData.openid= res.data.openid;
							that.globalData.session_key= res.data.session_key;
							wx.showToast({
								title: '获取成功',
								duration: 1500,
								icon: 'success'
							})
						},
						fail: function() {
							wx.showToast({
								title: '获取失败',
								duration: 2000,
								icon: 'error'
							})
						}
					}
				}else {
            		console.log('登录失败:' + res.errMsg)
          		}
			})
		}
	})
},
后端api代码
protected void Page_Load(object sender, EventArgs e)
{
	string parameter = Request["parameter"];
	switch (parameter)
	{
		case "onLogin": onLogin(); break;//获取用户的openid、session_key
	}
}
#region 通过code获取用户的openid、session_key
public void onLogin()
{
	string code = Request["code"];
	string Str = GetJson("https://api.weixin.qq.com/sns/jscode2session?appid=appid&secret=secret&js_code=" + code + "&grant_type=authorization_code");//参数appid的值为小程序的appid,参数secret的值为小程序的密钥
	if (Str != null)
	{
		Response.Write(Str);
		Response.End();
	}
	else
	{
		Response.Write("");
		Response.End();
	}
}
/// 
/// 接受信息
/// 
/// 请求地址
/// 
public static string GetJson(string url)
{
	WebClient wc = new WebClient();
	wc.Credentials = CredentialCache.DefaultCredentials;
	wc.Encoding = Encoding.UTF8;
	string returnText = wc.DownloadString(url);
	if (returnText.Contains("errcode"))
	{
		//错误
	}
	return returnText;
}
#endregion

欢迎分享,转载请注明来源:内存溢出

原文地址:https://54852.com/web/1322930.html

(0)
打赏 微信扫一扫微信扫一扫 支付宝扫一扫支付宝扫一扫
上一篇 2022-06-12
下一篇2022-06-12

发表评论

登录后才能评论

评论列表(0条)

    保存