c# 調用微信小程序


//微信也不給個c#調用的例子 只好自己造咯;ps:大佬勿噴
1
public string GetWx(string code, string iv, string encryptedData) 2 { 3 // context.Response.ContentType = "text/plain"; 4 string xx = ""; 5 try 6 { 7 //code = HttpContext.Current.Request.QueryString["code"].ToString(); 8 //iv = HttpContext.Current.Request.QueryString["iv"].ToString(); 9 //encryptedData = HttpContext.Current.Request.QueryString["encryptedData"].ToString(); 10 } 11 catch (Exception ex) 12 { 13 // context.Response.Write(ex.ToString()); 14 } 15 16 string Appid = "wx187bd36d7393af6b"; 17 string Secret = "8f14745e1dd01cedbdcac790aa397149"; 18 string grant_type = "authorization_code"; 19 20 //向微信服務端 使用登錄憑證 code 獲取 session_key 和 openid 21 string url = "https://api.weixin.qq.com/sns/jscode2session?appid=" + Appid + "&secret=" + Secret + "&js_code=" + code + "&grant_type=" + grant_type; 22 string type = "utf-8"; 23 24 GetUsersHelper GetUsersHelper = new GetUsersHelper(); 25 string j = GetUsersHelper.GetUrltoHtml(url, type);//獲取微信服務器返回字符串 26 27 //將字符串轉換為json格式 28 JObject jo = (JObject)JsonConvert.DeserializeObject(j); 29 30 result res = new result(); 31 try 32 { 33 //微信服務器驗證成功 34 res.openid = jo["openid"].ToString(); 35 res.session_key = jo["session_key"].ToString(); 36 } 37 catch (Exception) 38 { 39 //微信服務器驗證失敗 40 res.errcode = jo["errcode"].ToString(); 41 res.errmsg = jo["errmsg"].ToString(); 42 } 43 return res.openid; 44 } 45 46 public class GetUsersHelper 47 { 48 49 /// <summary> 50 /// 獲取鏈接返回數據 51 /// </summary> 52 /// <param name="Url">鏈接</param> 53 /// <param name="type">請求類型</param> 54 /// <returns></returns> 55 public string GetUrltoHtml(string Url, string type) 56 { 57 try 58 { 59 System.Net.WebRequest wReq = System.Net.WebRequest.Create(Url); 60 // Get the response instance. 61 System.Net.WebResponse wResp = wReq.GetResponse(); 62 System.IO.Stream respStream = wResp.GetResponseStream(); 63 // Dim reader As StreamReader = New StreamReader(respStream) 64 using (System.IO.StreamReader reader = new System.IO.StreamReader(respStream, Encoding.GetEncoding(type))) 65 { 66 return reader.ReadToEnd(); 67 } 68 } 69 catch (System.Exception ex) 70 { 71 return ex.Message; 72 } 73 }
 #region 微信小程序用戶數據解密

            public static string AesKey;
            public static string AesIV;

            /// <summary> 
            /// AES解密 
            /// </summary> 
            /// <param name="inputdata">輸入的數據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;

                }
            }

            /// <summary>  
            /// 根據微信小程序平台提供的解密算法解密數據  
            /// </summary>  
            /// <param name="encryptedData">加密數據</param>  
            /// <param name="iv">初始向量</param>  
            /// <param name="sessionKey">從服務端獲取的SessionKey</param>  
            /// <returns></returns>  
            public userInfo Decrypt(string encryptedData, string iv, string sessionKey)
            {
                userInfo userInfo;
                //創建解密器生成工具實例  
                AesCryptoServiceProvider aes = new AesCryptoServiceProvider();
                //設置解密器參數  
                aes.Mode = CipherMode.CBC;
                aes.BlockSize = 128;
                aes.Padding = PaddingMode.PKCS7;
                //格式化待處理字符串  
                byte[] byte_encryptedData = Convert.FromBase64String(encryptedData);
                byte[] byte_iv = Convert.FromBase64String(iv);
                byte[] byte_sessionKey = Convert.FromBase64String(sessionKey);

                aes.IV = byte_iv;
                aes.Key = byte_sessionKey;
                //根據設置好的數據生成解密器實例  
                ICryptoTransform transform = aes.CreateDecryptor();

                //解密  
                byte[] final = transform.TransformFinalBlock(byte_encryptedData, 0, byte_encryptedData.Length);

                //生成結果  
                string result = Encoding.UTF8.GetString(final);

                //反序列化結果,生成用戶信息實例  
                userInfo = JsonConvert.DeserializeObject<userInfo>(result);

                return userInfo;

            }


            #endregion
        }



        public class wechat
        {
        }
        #region 實體類
        /// <summary>  
        /// 微信用戶類  
        /// </summary>  
        public class userInfo
        {
            public string openId { get; set; }
            public string nickName { get; set; }
            public string gender { get; set; }
            public string city { get; set; }
            public string province { get; set; }
            public string country { get; set; }
            public string avatarUrl { get; set; }
            public string unionId { get; set; }
            public data watermark { get; set; }
        }
        /// <summary>  
        /// 微信用戶數據水印  
        /// </summary>  
        public class data
        {
            public string appid { get; set; }
            public string timestamp { get; set; }
        }
        /// <summary>  
        /// 微信小程序驗證返回結果  
        /// </summary>  
        public class result
        {
            public string openid { get; set; }
            public string session_key { get; set; }
            public string errcode { get; set; }
            public string errmsg { get; set; }
        }
        #endregion

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM