十年河东,十年河西,莫欺少年穷
学无止境,精益求精
Vant 插件请参考:https://youzan.github.io/vant-weapp/#/dialog
1、早index.json中引入Vant的dialog组件{ "usingComponents": { "van-dialog": "@vant/weapp/dialog/index" }}
2、index.wxml 如下<!--Callbackuserinfo 获取用户信息回调函数 Callbackphonenumber 获取手机号回调函数--><van-dialog id="van-dialog" bind:confirm="confirm" bind:getuserinfo="Callbackuserinfo" bind:getphonenumber="Callbackphonenumber"/>
3、C#代码如下【C#代码有详细备注,无需多说】
using Iot.Common;using Newtonsoft.Json;using System;using System.Collections.Generic;using System.Linq;using System.Net;using System.Net.Http;using System.Security.Cryptography;using System.Text;using System.Web.Http;namespace Iot.WebSite.Controllers.Apis{ public class WeChatController : ApiController { /// <summary> /// 获取用户基本信息 /// </summary> /// <param name="wxUser"></param> /// <returns></returns> [HttpPost] public IHttpActionResult GetUserInfo([FromBody] wxUserInfo wxUser) { return Ok(CommonBaseResponse.SetResponse<wxUserInfo>(wxUser, true)); } /// <summary> /// 获取用户OpenId /// </summary> /// <param name="code"></param> /// <returns></returns> [HttpGet] public IHttpActionResult GetUserOpenId([FromUri]string code) { return Ok(CommonBaseResponse.SetResponse<SessionResult>(WechatCommon.GetOpenId(code),true)); } /// <summary> /// 获取用户手机号 /// </summary> /// <param name="wxPhoneParm"></param> /// <returns></returns> [HttpPost] public IHttpActionResult GetPhoneNubmber([FromBody]WxPhoneParm wxPhoneParm) { var result = WechatCommon.GetPhoneNubmber(wxPhoneParm.encryptedData, wxPhoneParm.session_key, wxPhoneParm.iv); return Ok(CommonBaseResponse.SetResponse<GetWeChatCustomerPhoneResult>(result, true)); } } /// <summary> /// 公共类 /// </summary> public class WechatCommon { /// <summary> /// 获取用户OPenId /// </summary> /// <param name="code"></param> /// <returns></returns> public static SessionResult GetOpenId(string code) { string url = "https://api.weixin.qq.com/sns/jscode2session?appid=" + WechatAppInfo.Appid + "&secret=" + WechatAppInfo.AppSerct + "&js_code=" + code + "&grant_type=authorization_code"; var jspon = RestServiceProxy.GetPage(url, ""); if (jspon.Contains("errcode")) { //获取OpenId失败 return null; } //获取OpenID var Result = JsonConvert.DeserializeObject<SessionResult>(jspon); return Result; } /// <summary> /// 获取用户手机号 /// </summary> /// <param name="encryptedData"></param> /// <param name="session_key">获取用户OpenId方法的返回对象session_key属性</param> /// <param name="iv"></param> /// <returns></returns> public static GetWeChatCustomerPhoneResult GetPhoneNubmber(string encryptedData, string session_key, string iv) { try { byte[] encryptedDataBys = Convert.FromBase64String(encryptedData); RijndaelManaged rijndaelCipher = new RijndaelManaged(); rijndaelCipher.Key = Convert.FromBase64String(session_key); rijndaelCipher.IV = Convert.FromBase64String(iv); rijndaelCipher.Mode = CipherMode.CBC; rijndaelCipher.Padding = PaddingMode.PKCS7; ICryptoTransform transform = rijndaelCipher.CreateDecryptor(); byte[] plainText = transform.TransformFinalBlock(encryptedDataBys, 0, encryptedDataBys.Length); string result = Encoding.Default.GetString(plainText); GetWeChatCustomerPhoneResult userInfo = JsonConvert.DeserializeObject<GetWeChatCustomerPhoneResult>(result); return userInfo; } catch(Exception ex) { return null; } } } public class GetWeChatCustomerPhoneResult { public string phoneNumber { get; set; } } /// <summary> /// 获取OpenId 的返回值 session_key 可用于获取用户手机号 /// </summary> public class SessionResult { public string openid { get; set; } public string session_key { get; set; } public string unionid { get; set; } } /// <summary> /// 微信小程序基本信息 /// </summary> public class WechatAppInfo { public static string Appid = "AppID"; public static string AppSerct = "AppSerct"; } /// <summary> /// 获取用户手机号参数 /// </summary> public class WxPhoneParm { /// <summary> /// 小程序获取手机号api返回 /// </summary> public string encryptedData { get; set; } /// <summary> /// 小程序获取手机号api返回 /// </summary> public string iv { get; set; } /// <summary> /// wx.login 获取 /// </summary> public string session_key { get; set; } } /// <summary> /// 用户基本信息 /// </summary> public class wxUserInfo { /// <summary> /// 用户昵称 /// </summary> public string nickName { get; set; } /// <summary> /// 头像 /// </summary> public string avatarUrl { get; set; } /// <summary> /// 语言 /// </summary> public string language { get; set; } /// <summary> /// 国家 微信API更新后,不再返回,统一返回空字符串 微信牛逼,Api想怎么改就怎么改 奶奶个腿 /// </summary> public string country { get; set; } /// <summary> /// 省 微信API更新后,不再返回,统一返回空字符串 微信牛逼,Api想怎么改就怎么改 奶奶个腿 /// </summary> public string province { get; set; } /// <summary> /// 市 微信API更新后,不再返回,统一返回空字符串 微信牛逼,Api想怎么改就怎么改 奶奶个腿 /// </summary> public string city { get; set; } /// <summary> /// 性别 微信API更新后,不再返回,统一返回空字符串 微信牛逼,Api想怎么改就怎么改 奶奶个腿 /// </summary> public int gender { get; set; } }}
View Code
4、index.js如下
4.1、微信获取用户基本信息 GetUserInfo() { let that = this; Dialog.alert({ title: '登录', message: '是否公开您的信息', confirmButtonOpenType: "getUserInfo", // 按钮的微信开放能力 showCancelButton: true, confirmButtonText: "授权登录" }).then((e) => { // on close console.log("GetUser has Closed") }).catch(() => { }); }, confirm(e) { console.log(e) }, /**授权-新接口 用户点击允许,回调函数 */ Callbackuserinfo(e) { //用户点击允许,回调函数 console.log(e) },
只需要OnLoad中调用上述方法即可即可onLoad() { this.GetUserInfo(); //this.GetOpenId(); // this.GetUserPhone(); },
效果图如下:
代码输出顺序如下:
执行顺序:用户点击授权登录,执行 confirm(e) 方法,点击授权登录后,弹出框关闭,执行 then 方法,打印: console.log("GetUser has Closed") ,然后弹出获取您的昵称头像,用户点击【允许】,执行回调函数:Callbackuserinfo(e)
下面,我们看看 Callbackuserinfo(e) 回调函数的参数 e 的输出,是否能得到用户信息呢?
以上便是获取用户基本信息的代码。
4.2、获取用户OpenID GetOpenId() { wx.login({ success(res) { request.request({ url: "/api/WeChat/GetUserOpenId?code=" + res.code, method: "GET" }).then(result => { console.log(result.Data); wx.setStorageSync('session_key', result.Data.session_key) }); } }) },
只需在OnLoad中调用上述方法即可onLoad() { //this.GetUserInfo(); this.GetOpenId(); // this.GetUserPhone(); },
执行结果:
返回结果有三个值,分别为openid seesion_key untionId,其中openId 是我们想要的结果,session_key 可用于获取用户手机号,untionId 的作用,我记不起来了。
4.3、获取用户手机号 GetUserPhone() { let that = this; Dialog.alert({ title: '登录', message: '是否允许获取您的手机号', confirmButtonOpenType: "getPhoneNumber", // 按钮的微信开放能力 showCancelButton: true, confirmButtonText: "授权" }).then(() => { // on close console.log("GetUserPhone has Closed") }).catch(() => { }); }, confirm(e) { console.log(e) }, Callbackphonenumber(e) { wx.login({ success(res) { request.request({ url: "/api/WeChat/GetUserOpenId?code=" + res.code, method: "GET" }).then(result => { //console.log(result.Data.session_key); let session_key = result.Data.session_key; let encryptedData = e.detail.encryptedData; let iv = e.detail.iv; request.request({ url: "/api/WeChat/GetPhoneNubmber", data: { encryptedData: encryptedData, session_key: session_key, iv: iv }, method: "POST" }).then(result => { console.log(result); }); }); } }) }
只需在OnLoad 中调用以上代码即可
效果如下:
结果如下:
执行顺序和获取用户基本信息一致,不再累述。
需要注意的是,获取用户OpenId 中会使用到code,而这个code的有效期为五分钟,因此,我们使用code 获取到的session_key的有效期可能也是五分钟,这里我没有详细去查 。
一次性获取所有的信息, 如下:
获取到用户基本信息后,立马弹出获取手机号的授权框,并获取手机号,获取手机号的方法,写在了用户信息回调方法内
index.js 代码如下:
// index.jsvar dayjs = require('dayjs')const app = getApp()import * as request from "../../utils/request/request.js"import Dialog from '../../miniprogram_npm/@vant/weapp/dialog/dialog';Page({ data: { }, onLoad() { this.GetUserInfo(); this.GetOpenId(); }, GetOpenId() { wx.login({ success(res) { request.request({ url: "/api/WeChat/GetUserOpenId?code=" + res.code, method: "GET" }).then(result => { console.log(result.Data); wx.setStorageSync('session_key', result.Data.session_key) }); } }) }, GetUserInfo() { let that = this; Dialog.alert({ title: '登录', message: '是否公开您的信息', confirmButtonOpenType: "getUserInfo", // 按钮的微信开放能力 showCancelButton: true, confirmButtonText: "授权登录" }).then((e) => { // on close console.log("GetUser has Closed") }).catch(() => { }); }, /**授权-新接口 用户点击允许,回调函数 */ Callbackuserinfo(e) { //用户点击允许,回调函数 console.log(e); this.GetUserPhone(); }, GetUserPhone() { let that = this; Dialog.alert({ title: '登录', message: '是否允许获取您的手机号', confirmButtonOpenType: "getPhoneNumber", // 按钮的微信开放能力 showCancelButton: true, confirmButtonText: "授权" }).then(() => { // on close console.log("GetUserPhone has Closed") }).catch(() => { }); }, confirm(e) { console.log(e) }, Callbackphonenumber(e) { wx.login({ success(res) { request.request({ url: "/api/WeChat/GetUserOpenId?code=" + res.code, method: "GET" }).then(result => { //console.log(result.Data.session_key); let session_key = result.Data.session_key; let encryptedData = e.detail.encryptedData; let iv = e.detail.iv; request.request({ url: "/api/WeChat/GetPhoneNubmber", data: { encryptedData: encryptedData, session_key: session_key, iv: iv }, method: "POST" }).then(result => { console.log(result); }); }); } }) }})
View Code
执行结果:
以上便是Vant 结合 C# 结合 微信小程序 获取用户信息的全部。