public class WxHelper { //微信小程序 private static string _appid = ConfigurationManager.AppSettings["wxAPPID"]; private static string _appSecret = ConfigurationManager.AppSettings["wxAppSecret"]; //APP微信ID private static string id = ConfigurationManager.AppSettings["appWxAPPID"]; // APP 微信 private static string secret = ConfigurationManager.AppSettings["appWxAppSecret"]; //微信公众号 private static string _gzhappid = ConfigurationManager.AppSettings["wxgzhAPPID"]; private static string _gzhappSecret = ConfigurationManager.AppSettings["wxgzhAppSecret"]; public static WxSession Code2Session(string code) { var url = $"https://api.weixin.qq.com/sns/jscode2session?appid={_appid}&secret={_appSecret}&js_code={code}&grant_type=authorization_code"; try { var request = WebRequest.Create(url); using (var response = request.GetResponse()) { using (var rs = response.GetResponseStream()) { using (var s = new System.IO.StreamReader(rs)) { return s.ReadToEnd().JsonTo<WxSession>(); } } } } catch (Exception) { return null; } } #region 获取微信手机号 /// <summary> /// 获取微信手机号 /// </summary> /// <param name="aesIv">向量</param> /// <param name="encryptedData">encryptedData</param> /// <param name="code">加密数据</param> /// <returns></returns> ///框架引用,用于返回Json串 public static string GetPhoneNumber(string aesIv, string encryptedData, string code) { try { #region 获取Session_Key var AppId = _appid; //微信小程序AppID var Secret = _appSecret; //微信小程序Secret string serviceAddress = "https://api.weixin.qq.com/sns/jscode2session?appid=" + AppId + "&secret=" + Secret + "&js_code=" + code + "&grant_type=authorization_code"; HttpWebRequest request = (HttpWebRequest)WebRequest.Create(serviceAddress); request.Method = "GET"; request.ContentType = "text/html;charset=utf-8"; HttpWebResponse response = (HttpWebResponse)request.GetResponse(); Stream myResponseStream = response.GetResponseStream(); StreamReader myStreamReader = new StreamReader(myResponseStream, System.Text.Encoding.UTF8); string retString = myStreamReader.ReadToEnd(); myStreamReader.Close(); myResponseStream.Close(); var obj = new { data = retString, Success = true }; Formatting microsoftDataFormatSettings = default(Formatting); string result = JsonConvert.SerializeObject(obj, microsoftDataFormatSettings); //序列化获取session_key v_petminiuserdetails item = JsonConvert.DeserializeObject<v_petminiuserdetails>(retString); #endregion #region 获取微信绑定手机号 //判断是否是16位 如果不够补0 //text = tests(text); //16进制数据转换成byte byte[] encryptedDatas = Convert.FromBase64String(encryptedData); // strToToHexByte(text); RijndaelManaged rijndaelCipher = new RijndaelManaged(); rijndaelCipher.Key = Convert.FromBase64String(item.session_key); // Encoding.UTF8.GetBytes(AesKey); rijndaelCipher.IV = Convert.FromBase64String(aesIv);// Encoding.UTF8.GetBytes(AesIV); rijndaelCipher.Mode = CipherMode.CBC; rijndaelCipher.Padding = PaddingMode.PKCS7; ICryptoTransform transform = rijndaelCipher.CreateDecryptor(); byte[] plainText = transform.TransformFinalBlock(encryptedDatas, 0, encryptedDatas.Length); string results = Encoding.Default.GetString(plainText); //序列化获取手机号码 wechardetails<watermark> getPhone = JsonConvert.DeserializeObject<wechardetails<watermark>>(results); //getPhone.watermark.openid = item.openid; //获取用户OpenID return getPhone.phoneNumber; #endregion } catch (Exception ex) { return null; } } #endregion private static string DecodeData(string sessionKey, string iv, string encryptedData) { var dataBuffer = Convert.FromBase64String(encryptedData); RijndaelManaged rijndaelCipher = new RijndaelManaged(); rijndaelCipher.Key = Convert.FromBase64String(sessionKey); rijndaelCipher.IV = Convert.FromBase64String(iv); rijndaelCipher.Mode = CipherMode.CBC; rijndaelCipher.Padding = PaddingMode.PKCS7; ICryptoTransform transform = rijndaelCipher.CreateDecryptor(rijndaelCipher.Key, rijndaelCipher.IV); byte[] plainText = transform.TransformFinalBlock(dataBuffer, 0, dataBuffer.Length); string result = Encoding.UTF8.GetString(plainText); return result; } /// <summary> /// 获取微信手机号 /// </summary> /// <param name="sessionKey"></param> /// <param name="iv"></param> /// <param name="encryptedData"></param> /// <returns></returns> public static string GetUnionId(string sessionKey, string iv, string encryptedData) { string result = DecodeData(sessionKey, iv, encryptedData); Newtonsoft.Json.Linq.JObject jobject = (Newtonsoft.Json.Linq.JObject)Newtonsoft.Json.JsonConvert.DeserializeObject(result); var wxUnion = Convert.ToString(jobject["phoneNumber"]); return wxUnion; } /// <summary> /// 获取微信UnionId /// </summary> /// <param name="sessionKey"></param> /// <param name="iv"></param> /// <param name="encryptedData"></param> /// <returns></returns> public static string GetUnionIdYjsq(string sessionKey, string iv, string encryptedData) { string result = DecodeData(sessionKey, iv, encryptedData); Newtonsoft.Json.Linq.JObject jobject = (Newtonsoft.Json.Linq.JObject)Newtonsoft.Json.JsonConvert.DeserializeObject(result); var wxUnion = Convert.ToString(jobject["unionId"]); return wxUnion; } /// <summary> /// 获取微信信息 /// </summary> /// <param name="sessionKey"></param> /// <param name="iv"></param> /// <param name="encryptedData"></param> /// <returns></returns> public static Newtonsoft.Json.Linq.JObject wxUserInfo(string sessionKey, string iv, string encryptedData) { string result = DecodeData(sessionKey, iv, encryptedData); Newtonsoft.Json.Linq.JObject jobject = (Newtonsoft.Json.Linq.JObject)Newtonsoft.Json.JsonConvert.DeserializeObject(result); return jobject; } /// <summary> /// 获取微信access_token /// </summary> /// <param name="code"></param> /// <returns></returns> public static WxTokenSession GetAccessToken(string code) { var url = $"https://api.weixin.qq.com/sns/oauth2/access_token?appid={_appid}&secret={_appSecret}&code={code}&grant_type=authorization_code"; try { var request = WebRequest.Create(url); using (var response = request.GetResponse()) { using (var rs = response.GetResponseStream()) { using (var s = new System.IO.StreamReader(rs)) { return s.ReadToEnd().JsonTo<WxTokenSession>(); } } } } catch (Exception) { return null; } } public class WxSession { public string openid { get; set; } public string session_key { get; set; } public string errcode { get; set; } public string errMsg { get; set; } public string unionid { get; set; } } public class WxTokenSession { public string access_token { get; set; } public string expires_in { get; set; } public string refresh_token { get; set; } public string openid { get; set; } public string scope { get; set; } public string unionid { get; set; } public string errcode { get; set; } public string errMsg { get; set; } } //实体Model //获取用户openid、session_key public class v_petminiuserdetails { /// <summary> /// 微信用户openId /// </summary> public string openid { get; set; } /// <summary> /// session_key /// </summary> public string session_key { get; set; } } //获取用户手机号 public class wechardetails<T> { /// <summary> /// 手机号 /// </summary> public string phoneNumber { get; set; } /// <summary> /// 区域手机号 /// </summary> public string purePhoneNumber { get; set; } /// <summary> /// 区码 /// </summary> public string countryCode { get; set; } public T watermark { get; set; } } public class watermark { /// <summary> /// 时间戳 /// </summary> public string timestamp { get; set; } /// <summary> /// 用户appid /// </summary> public string appid { get; set; } /// <summary> /// 用户openid /// </summary> public string openid { get; set; } } }
请发表评论