C#微信小程序服務(wù)端獲取用戶解密信息實(shí)例代碼
更新時(shí)間:2017年03月10日 11:42:32 作者:一九九二
這篇文章主要介紹了 C#微信小程序服務(wù)端獲取用戶解密信息實(shí)例代碼的相關(guān)資料,需要的朋友可以參考下
C#微信小程序服務(wù)端獲取用戶解密信息實(shí)例代碼
實(shí)現(xiàn)代碼:
using AIOWeb.Models;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Web;
namespace AIOWeb
{
/// <summary>
/// wxapi 的摘要說明
/// </summary>
public class wxapi : IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
context.Response.ContentType = "text/plain";
string code = "";
string iv = "";
string encryptedData = "";
try
{
code = HttpContext.Current.Request.QueryString["code"].ToString();
iv = HttpContext.Current.Request.QueryString["iv"].ToString();
encryptedData = HttpContext.Current.Request.QueryString["encryptedData"].ToString();
}
catch (Exception ex)
{
context.Response.Write(ex.ToString());
}
string Appid = "wxdb2641f85b04f1b3";
string Secret = "8591d8cd7197b9197e17b3275329a1e7";
string grant_type = "authorization_code";
//向微信服務(wù)端 使用登錄憑證 code 獲取 session_key 和 openid
string url = "https://api.weixin.qq.com/sns/jscode2session?appid=" + Appid + "&secret=" + Secret + "&js_code=" + code + "&grant_type=" + grant_type;
string type = "utf-8";
AIOWeb.Models.GetUsersHelper GetUsersHelper = new AIOWeb.Models.GetUsersHelper();
string j = GetUsersHelper.GetUrltoHtml(url, type);//獲取微信服務(wù)器返回字符串
//將字符串轉(zhuǎn)換為json格式
JObject jo = (JObject)JsonConvert.DeserializeObject(j);
result res = new result();
try
{
//微信服務(wù)器驗(yàn)證成功
res.openid = jo["openid"].ToString();
res.session_key = jo["session_key"].ToString();
}
catch (Exception)
{
//微信服務(wù)器驗(yàn)證失敗
res.errcode = jo["errcode"].ToString();
res.errmsg = jo["errmsg"].ToString();
}
if (!string.IsNullOrEmpty(res.openid))
{
//用戶數(shù)據(jù)解密
GetUsersHelper.AesIV = iv;
GetUsersHelper.AesKey = res.session_key;
string result = GetUsersHelper.AESDecrypt(encryptedData);
//存儲(chǔ)用戶數(shù)據(jù)
JObject _usrInfo = (JObject)JsonConvert.DeserializeObject(result);
userInfo userInfo = new userInfo();
userInfo.openId = _usrInfo["openId"].ToString();
try //部分驗(yàn)證返回值中沒有unionId
{
userInfo.unionId = _usrInfo["unionId"].ToString();
}
catch (Exception)
{
userInfo.unionId = "unionId";
}
userInfo.nickName = _usrInfo["nickName"].ToString();
userInfo.gender = _usrInfo["gender"].ToString();
userInfo.city = _usrInfo["city"].ToString();
userInfo.province = _usrInfo["province"].ToString();
userInfo.country = _usrInfo["country"].ToString();
userInfo.avatarUrl = _usrInfo["avatarUrl"].ToString();
object watermark = _usrInfo["watermark"].ToString();
object appid = _usrInfo["watermark"]["appid"].ToString();
object timestamp = _usrInfo["watermark"]["timestamp"].ToString();
#region
//創(chuàng)建連接池對(duì)象(與數(shù)據(jù)庫服務(wù)器進(jìn)行連接)
SqlConnection conn = new SqlConnection("server=127.0.0.1;database=Test;uid=sa;pwd=1");
//打開連接池
conn.Open();
//創(chuàng)建命令對(duì)象
string Qrystr = "SELECT * FROM WeChatUsers WHERE openId='" + userInfo.openId + "'";
SqlCommand cmdQry = new SqlCommand(Qrystr, conn);
object obj = cmdQry.ExecuteScalar();
if ((Object.Equals(obj, null)) || (Object.Equals(obj, System.DBNull.Value)))
{
string str = "INSERT INTO WeChatUsers ([UnionId] ,[OpenId],[NickName],[Gender],[City],[Province],[Country],[AvatarUrl],[Appid],[Timestamp],[Memo],[counts])VALUES('" + userInfo.unionId + "','" + userInfo.openId + "','" + userInfo.nickName + "','" + userInfo.gender + "','" + userInfo.city + "','" + userInfo.province + "','" + userInfo.country + "','" + userInfo.avatarUrl + "','" + appid.ToString() + "','" + timestamp.ToString() + "','來自微信小程序','1')";
SqlCommand cmdUp = new SqlCommand(str, conn);
// 執(zhí)行操作
try
{
int row = cmdUp.ExecuteNonQuery();
}
catch (Exception ex)
{
context.Response.Write(ex.ToString());
}
}
else
{
//多次訪問,記錄訪問次數(shù)counts 更新unionId是預(yù)防最初沒有,后期關(guān)聯(lián)后卻仍未記錄
string str = "UPDATE dbo.WeChatUsers SET counts = counts+1,UnionId = '" + userInfo.unionId + "' WHERE OpenId='" + userInfo.openId + "'";
SqlCommand cmdUp = new SqlCommand(str, conn);
int row = cmdUp.ExecuteNonQuery();
}
//關(guān)閉連接池
conn.Close();
#endregion
//返回解密后的用戶數(shù)據(jù)
context.Response.Write(result);
}
else
{
context.Response.Write(j);
}
}
public bool IsReusable
{
get
{
return false;
}
}
}
}
GetUsersHelper 幫助類
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;
namespace AIOWeb.Models
{
public class GetUsersHelper
{
/// <summary>
/// 獲取鏈接返回?cái)?shù)據(jù)
/// </summary>
/// <param name="Url">鏈接</param>
/// <param name="type">請(qǐng)求類型</param>
/// <returns></returns>
public string GetUrltoHtml(string Url, string type)
{
try
{
System.Net.WebRequest wReq = System.Net.WebRequest.Create(Url);
// Get the response instance.
System.Net.WebResponse wResp = wReq.GetResponse();
System.IO.Stream respStream = wResp.GetResponseStream();
// Dim reader As StreamReader = New StreamReader(respStream)
using (System.IO.StreamReader reader = new System.IO.StreamReader(respStream, Encoding.GetEncoding(type)))
{
return reader.ReadToEnd();
}
}
catch (System.Exception ex)
{
return ex.Message;
}
}
#region 微信小程序用戶數(shù)據(jù)解密
public static string AesKey;
public static string AesIV;
/// <summary>
/// AES解密
/// </summary>
/// <param name="inputdata">輸入的數(shù)據(jù)encryptedData</param>
/// <param name="AesKey">key</param>
/// <param name="AesIV">向量128</param>
/// <returns name="result">解密后的字符串</returns>
public string AESDecrypt(string inputdata)
{
try
{
AesIV = AesIV.Replace(" ", "+");
AesKey = AesKey.Replace(" ", "+");
inputdata = inputdata.Replace(" ", "+");
byte[] encryptedData = Convert.FromBase64String(inputdata);
RijndaelManaged rijndaelCipher = new RijndaelManaged();
rijndaelCipher.Key = Convert.FromBase64String(AesKey); // 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(encryptedData, 0, encryptedData.Length);
string result = Encoding.UTF8.GetString(plainText);
return result;
}
catch (Exception)
{
return null;
}
}
#endregion
}
}
感謝閱讀,希望能幫助到大家,謝謝大家對(duì)本站的支持!
您可能感興趣的文章:
- c#使用微信接口開發(fā)微信門戶應(yīng)用
- C#實(shí)現(xiàn)微信公眾號(hào)群發(fā)消息(解決一天只能發(fā)一次的限制)實(shí)例分享
- C#微信公眾號(hào)開發(fā)之接收事件推送與消息排重的方法
- C#微信公眾平臺(tái)開發(fā)之a(chǎn)ccess_token的獲取存儲(chǔ)與更新
- C#微信開發(fā)之發(fā)送模板消息
- C#開發(fā)之微信小程序發(fā)送模板消息功能
- .NET C#使用微信公眾號(hào)登錄網(wǎng)站
- c#版在pc端發(fā)起微信掃碼支付的實(shí)例
- C#開發(fā)微信公眾號(hào)接口開發(fā)
- C#實(shí)現(xiàn)微信分賬功能的完整步驟
相關(guān)文章
JS輕量級(jí)函數(shù)式編程實(shí)現(xiàn)XDM二
這篇文章主要為大家介紹了JS函數(shù)式編程實(shí)現(xiàn)XDM示例詳解第2/3篇,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2022-06-06
JavaScript實(shí)際應(yīng)用:innerHTMl和確認(rèn)提示的使用
JavaScript實(shí)際應(yīng)用:innerHTMl和確認(rèn)提示的使用...2006-06-06
利用前端HTML+CSS+JS開發(fā)簡(jiǎn)單的TODOLIST功能(記事本)
這篇文章主要介紹了用HTML+CSS+JS做出簡(jiǎn)單的TODOLIST(記事本)項(xiàng)目,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下2021-04-04
TypeScript順時(shí)針打印矩陣實(shí)現(xiàn)實(shí)例詳解
這篇文章主要為大家介紹了TypeScript順時(shí)針打印矩陣實(shí)現(xiàn)實(shí)例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2022-09-09
微信小程序 支付功能實(shí)現(xiàn)PHP實(shí)例詳解
這篇文章主要介紹了微信小程序 支付功能實(shí)現(xiàn)PHP實(shí)例詳解的相關(guān)資料,需要的朋友可以參考下2017-05-05
微信小程序 數(shù)據(jù)交互與渲染實(shí)例詳解
這篇文章主要介紹了微信小程序 數(shù)據(jù)交互與渲染實(shí)例詳解的相關(guān)資料,需要的朋友可以參考下2017-01-01

