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 /// 50 /// 获取链接返回数据 51 /// 52 /// 链接 53 /// 请求类型 54 /// 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;

            ///  
            /// AES解密 
            ///  
            /// 输入的数据encryptedData 
            /// key 
            /// 向量128 
            /// 解密后的字符串 
            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;

                }
            }

            ///   
            /// 根据微信小程序平台提供的解密算法解密数据  
            ///   
            /// 加密数据  
            /// 初始向量  
            /// 从服务端获取的SessionKey  
            ///   
            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(result);

                return userInfo;

            }


            #endregion
        }



        public class wechat
        {
        }
        #region 实体类
        ///   
        /// 微信用户类  
        ///   
        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; }
        }
        ///   
        /// 微信用户数据水印  
        ///   
        public class data
        {
            public string appid { get; set; }
            public string timestamp { get; set; }
        }
        ///   
        /// 微信小程序验证返回结果  
        ///   
        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

 

 

转载于:https://www.cnblogs.com/provedl/p/9336480.html

你可能感兴趣的:(c# 调用微信小程序)