• 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
  • 相关阅读:
    excel读取表,并将结果保存为键值对的字典列表;
    [置顶] MQ选型对比RabbitMQ RocketMQ ActiveMQ Kafka
    ActiveMQ持久化消息的三种方式
    getConstructor、getDeclaredConstructor区别
    JavaEE 保存文件获取绝对路径getResource("")和servletContext.getRealPath("/")
    Java中getResourceAsStream的用法
    Java 输出流中的flush方法
    Java之关闭流
    Java中的字节流、缓冲流
    java原生序列化和Kryo序列化性能比较
  • 原文地址:https://www.cnblogs.com/provedl/p/9336480.html
Copyright © 2020-2023  润新知