zoukankan      html  css  js  c++  java
  • asp.net 微信JsSDK

    有时间再整理吧

      1 using System;
      2 using System.Collections.Generic;
      3 using System.Linq;
      4 using System.Web;
      5 using System.IO;
      6 using Newtonsoft.Json;
      7 using System.Net;
      8 using System.Runtime.Serialization.Formatters.Binary;
      9 using System.Text;
     10 using System.Security.Cryptography;
     11 using System.Data;
     12 using Common;
     13 
     14 namespace LingDing.test
     15 {
     16     /// <summary>
     17     /// WXJSSDK 的摘要说明
     18     /// </summary>
     19     public class WXJSSDK
     20     {
     21         private string appId;
     22         private string appSecret;
     23         private DataTable DT;
     24 
     25         public WXJSSDK(string appId, string appSecret)
     26         {
     27             this.appId = appId;
     28             this.appSecret = appSecret;
     29         }
     30 
     31         //得到数据包,返回使用页面  
     32         public System.Collections.Hashtable getSignPackage()
     33         {
     34             string jsapiTicket = getJsApiTicket();
     35             string url = HttpContext.Current.Request.Url.ToString();
     36             string timestamp = Convert.ToString(ConvertDateTimeInt(DateTime.Now));
     37             string nonceStr = createNonceStr();
     38 
     39             // 这里参数的顺序要按照 key 值 ASCII 码升序排序  
     40             string rawstring = "jsapi_ticket=" + jsapiTicket + "&noncestr=" + nonceStr + "&timestamp=" + timestamp + "&url=" + url + "";
     41 
     42             string signature = SHA1_Hash(rawstring);
     43 
     44             System.Collections.Hashtable signPackage = new System.Collections.Hashtable();
     45             signPackage.Add("appId", appId);
     46             signPackage.Add("nonceStr", nonceStr);
     47             signPackage.Add("timestamp", timestamp);
     48             signPackage.Add("url", url);
     49             signPackage.Add("signature", signature);
     50             signPackage.Add("rawString", rawstring);
     51 
     52 
     53             return signPackage;
     54         }
     55 
     56 
     57         //创建随机字符串  
     58         private string createNonceStr()
     59         {
     60             int length = 16;
     61             string chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
     62             string str = "";
     63             Random rad = new Random();
     64             for (int i = 0; i < length; i++)
     65             {
     66                 str += chars.Substring(rad.Next(0, chars.Length - 1), 1);
     67             }
     68             return str;
     69         }
     70 
     71 
     72         //得到ticket 如果文件里时间 超时则重新获取  
     73         private string getJsApiTicket()
     74         {
     75             //这里我从数据库读取
     76             DT = new DAL.FreeBase().TranSQLGetTable("select jsapi_ticket,ticket_expires from tokens where ID=1");
     77             int expire_time = (int)DT.Rows[0]["ticket_expires"];
     78             string ticket = DT.Rows[0]["jsapi_ticket"].ToString();
     79             string accessToken = GetTokenName(); //getAccessToken();//获取系统的全局token 
     80             if (expire_time < ConvertDateTimeInt(DateTime.Now))
     81             {
     82                 string url = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?type=jsapi&access_token=" + accessToken + "";
     83                 Jsapi api = JsonConvert.DeserializeObject<Jsapi>(httpGet(url));
     84                 ticket = api.ticket;
     85                 if (ticket != "")
     86                 {
     87                     expire_time = ConvertDateTimeInt(DateTime.Now) + 7000;
     88                     //存入数据库操作
     89                     new DAL.FreeBase().TranSQL("update tokens set jsapi_ticket='" + ticket + "',ticket_expires='" + expire_time + "' where ID=1");
     90                 }
     91             }
     92             return ticket;
     93         }
     94 
     95         string GetTokenName()//得到tokenname
     96         {
     97             //string projectname = "类名:" + System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.FullName;
     98             string projectname = System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.FullName;
     99             string classname = projectname.Substring(projectname.IndexOf('.') + 1);
    100             string tokenname = GetConfig.gettoken(classname);
    101             return tokenname;
    102         }
    103         ////得到accesstoken 如果文件里时间 超时则重新获取  
    104         //private string getAccessToken()
    105         //{
    106         //    // access_token 应该全局存储与更新,以下代码以写入到文件中做示例
    107         //    string access_token = "";
    108         //    string path = HttpContext.Current.Server.MapPath(@"/weixin/access_token.json");
    109         //    FileStream file = new FileStream(path, FileMode.Open);
    110         //    var serializer = new DataContractJsonSerializer(typeof(AccToken));
    111         //    AccToken readJSTicket = (AccToken)serializer.ReadObject(file);
    112         //    file.Close();
    113         //    if (readJSTicket.expires_in < ConvertDateTimeInt(DateTime.Now))
    114         //    {
    115         //        string url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" + appId + "&secret=" + appSecret + "";
    116 
    117         //        AccToken iden = Desrialize<AccToken>(new AccToken(), httpGet(url));
    118 
    119         //        access_token = iden.access_token;
    120         //        if (access_token != "")
    121         //        {
    122         //            iden.expires_in = ConvertDateTimeInt(DateTime.Now) + 7000;
    123         //            iden.access_token = access_token;
    124 
    125         //            string json = Serialize<AccToken>(iden);
    126         //            StreamWriterMetod(json, path);
    127         //        }
    128         //    }
    129         //    else
    130         //    {
    131         //        access_token = readJSTicket.access_token;
    132         //    }
    133         //    return access_token;
    134         //}
    135 
    136 
    137         //发起一个http请球,返回值  
    138         private string httpGet(string url)
    139         {
    140             try
    141             {
    142                 WebClient MyWebClient = new WebClient();
    143                 MyWebClient.Credentials = CredentialCache.DefaultCredentials;//获取或设置用于向Internet资源的请求进行身份验证的网络凭据  
    144                 Byte[] pageData = MyWebClient.DownloadData(url); //从指定网站下载数据  
    145                 string pageHtml = System.Text.Encoding.Default.GetString(pageData);  //如果获取网站页面采用的是GB2312,则使用这句              
    146 
    147                 return pageHtml;
    148             }
    149             catch (WebException webEx)
    150             {
    151                 Console.WriteLine(webEx.Message.ToString());
    152                 return null;
    153             }
    154         }
    155 
    156 
    157         //SHA1哈希加密算法  
    158         public string SHA1_Hash(string str_sha1_in)
    159         {
    160             SHA1 sha1 = new SHA1CryptoServiceProvider();
    161             byte[] bytes_sha1_in = System.Text.UTF8Encoding.Default.GetBytes(str_sha1_in);
    162             byte[] bytes_sha1_out = sha1.ComputeHash(bytes_sha1_in);
    163             string str_sha1_out = BitConverter.ToString(bytes_sha1_out);
    164             str_sha1_out = str_sha1_out.Replace("-", "").ToLower();
    165             return str_sha1_out;
    166         }
    167 
    168 
    169         /// <summary>  
    170         /// StreamWriter写入文件方法  
    171         /// </summary>  
    172         private void StreamWriterMetod(string str, string patch)
    173         {
    174             try
    175             {
    176                 FileStream fsFile = new FileStream(patch, FileMode.OpenOrCreate);
    177                 StreamWriter swWriter = new StreamWriter(fsFile);
    178                 swWriter.WriteLine(str);
    179                 swWriter.Close();
    180             }
    181             catch (Exception e)
    182             {
    183                 throw e;
    184             }
    185         }
    186 
    187         /// <summary>  
    188         /// 将c# DateTime时间格式转换为Unix时间戳格式  
    189         /// </summary>  
    190         /// <param name="time">时间</param>  
    191         /// <returns>double</returns>  
    192         public int ConvertDateTimeInt(System.DateTime time)
    193         {
    194             int intResult = 0;
    195             System.DateTime startTime = TimeZone.CurrentTimeZone.ToLocalTime(new System.DateTime(1970, 1, 1));
    196             intResult = Convert.ToInt32((time - startTime).TotalSeconds);
    197             return intResult;
    198         }
    199     }
    200     //创建Json序列化 及反序列化类目  
    201     #region
    202     //创建JSon类 保存文件 jsapi_ticket.json  
    203     public class JSTicket
    204     {
    205 
    206         public string jsapi_ticket { get; set; }
    207 
    208         public double expire_time { get; set; }
    209     }
    210     //创建 JSon类 保存文件 access_token.json  
    211 
    212     public class AccToken
    213     {
    214 
    215         public string access_token { get; set; }
    216 
    217         public double expires_in { get; set; }
    218     }
    219 
    220 
    221     //创建从微信返回结果的一个类 用于获取ticket  
    222 
    223     public class Jsapi
    224     {
    225 
    226         public int errcode { get; set; }
    227 
    228         public string errmsg { get; set; }
    229 
    230         public string ticket { get; set; }
    231 
    232         public string expires_in { get; set; }
    233     }
    234     #endregion
    235 }
    View Code
  • 相关阅读:
    Stm32CubeMX5 配置 STM32的串口DMA接受方式 --- 基于 stm32f051k8u6
    Stm32 控制1.44寸液晶显示图片 基于stm32f051k8u6
    makefile自动编译
    Stm32CubeMX5 创建LED控制工程
    ARM 汇编与C之间 的调用
    shell 脚本文件类型.sh ,变量
    bzoj3589 动态树 求链并 容斥
    bzoj2287【POJ Challenge】消失之物 缺一01背包
    bzoj2916: [Poi1997]Monochromatic Triangles 思路
    [NOI2010]超级钢琴 主席树
  • 原文地址:https://www.cnblogs.com/itslives-com/p/wxJsSDK.html
Copyright © 2011-2022 走看看