首页 > 代码库 > C#微信开发之旅(六):生成带参数的二维码

C#微信开发之旅(六):生成带参数的二维码

主要用来推广并统计数据,当用户扫描带参数二维码时,微信会推送消息到我们的服务器,此时可以根据参数了解到用户是从哪个渠道关注的。话不多少,先来代码:

  1 #region 生成二维码  2   3         /// <summary>  4         /// 获取Ticket  5         /// </summary>  6         /// <returns></returns>  7         private static string CreateTicket(string scene_id)  8         {  9             var token = AccessToken.Instance; 10  11             if (string.IsNullOrEmpty(token.Access_Token)) 12                 throw new ArgumentNullException("Access_Token"); 13  14             string url = string.Format(WeiXinConst.WeiXin_Ticket_CreateUrl, token.Access_Token); 15             string postData = http://www.mamicode.com/WeiXinConst.WeiXin_QrCodeTicket_Create_JsonString.Replace("{0}", scene_id); 16  17             string result = HttpClientHelper.PostResponse(url, postData); 18             Ticket ticket = JsonConvert.DeserializeObject<Ticket>(result); //HttpClientHelper.PostResponse<Ticket>(url, postData); 19  20             if (ticket == null || string.IsNullOrEmpty(ticket.ticket)) 21             { 22                 ErrorMessage msg = JsonConvert.DeserializeObject<ErrorMessage>(result); 23                 if (msg.TokenExpired) 24                     return CreateTicketByNewAccessToken(scene_id); 25             } 26             return ticket.ticket; 27         } 28  29         /// <summary> 30         /// 当AccessToken过期时 调用此方法 31         /// </summary> 32         /// <param name="scene_id"></param> 33         /// <returns></returns> 34         private static string CreateTicketByNewAccessToken(string scene_id) 35         { 36             var token = AccessToken.NewInstance; 37  38             if (string.IsNullOrEmpty(token.Access_Token)) 39                 throw new ArgumentNullException("Access_Token"); 40  41             string url = string.Format(WeiXinConst.WeiXin_Ticket_CreateUrl, token.Access_Token); 42             string postData = http://www.mamicode.com/WeiXinConst.WeiXin_QrCodeTicket_Create_JsonString.Replace("{0}", scene_id); 43  44             Ticket ticket = HttpClientHelper.PostResponse<Ticket>(url, postData); 45  46             if (ticket == null || string.IsNullOrEmpty(ticket.ticket)) 47                 throw new Exception("Ticket为Null,AccessToken:" + token.Access_Token); 48             return ticket.ticket; 49         } 50  51  52         /// <summary> 53         /// 根据Ticket获取二维码图片保存在本地 54         /// </summary> 55         /// <param name="scene_id">二维码场景id</param> 56         /// <param name="imgPath">图片存储路径</param> 57         public static void SaveQrCodeImage(string scene_id, string imgPath) 58         { 59             string Ticket = CreateTicket(scene_id); 60  61             if (Ticket == null) 62                 throw new ArgumentNullException("Ticket"); 63  64             //ticket需 urlEncode 65             string stUrl = string.Format(WeiXinConst.WeiXin_QrCode_GetUrl, HttpUtility.UrlEncode(Ticket)); 66  67             HttpWebRequest req = (HttpWebRequest)HttpWebRequest.Create(stUrl); 68  69             req.Method = "GET"; 70  71             using (WebResponse wr = req.GetResponse()) 72             { 73                 HttpWebResponse myResponse = (HttpWebResponse)req.GetResponse(); 74                 string strpath = myResponse.ResponseUri.ToString(); 75  76                 WebClient mywebclient = new WebClient(); 77  78                 try 79                 { 80                     mywebclient.DownloadFile(strpath, imgPath); 81                 } 82                 catch (Exception) 83                 { 84                     throw new Exception("获取二维码图片失败!"); 85                 } 86             } 87         } 88  89         /// <summary> 90         /// 根据SceneId 获取 二维码图片流 91         /// </summary> 92         /// <param name="scene_id"></param> 93         /// <returns></returns> 94         public static Stream GetQrCodeImageStream(string scene_id) 95         { 96             string Ticket = CreateTicket(scene_id); 97  98             if (Ticket == null) 99                 throw new ArgumentNullException("Ticket");100 101             //ticket需 urlEncode102             string strUrl = string.Format(WeiXinConst.WeiXin_QrCode_GetUrl, HttpUtility.UrlEncode(Ticket));103             try104             {105                 System.Net.Http.HttpClient client = new System.Net.Http.HttpClient();106                 Byte[] bytes = client.GetByteArrayAsync(strUrl).Result;107                 return new MemoryStream(bytes);108             }109             catch110             {111                 throw new Exception("获取二维码图片失败!");112             }113         }114 115         #endregion

生成带参数的二维码,需要先获取Ticket(内置 token过期处理),再根据Ticket获取二维码(两个方法:保存到本地 以及 返回Stream)。

下面是调用代码:

1             string scene_id = "1";//场景Id,扫描生产的二维码 会带这个id,可以做推广、统计用2 3             //获取二维码流4             System.IO.Stream stream = WeiXinHelper.GetQrCodeImageStream(scene_id);5 6             //二维码图片存储路径7             string path = Server.MapPath("~/Document/QrCode/" + scene_id + ".jpg"); 8             //直接保存二维码到本地9             WeiXinHelper.SaveQrCodeImage("1", path);

C#微信开发之旅(六):生成带参数的二维码