c# 微信開發 《生成帶參數的關注二維碼》

/// <summary>
        /// 生成二維碼
        /// </summary>
        /// <returns></returns>
        /// 申請生成二維碼的用戶 CreatQrCodeUser
        public string CreateQrCodeImage(string CreatQrCodeUser)
        {
            string WeixinQrCodePath = ConfigurationManager.AppSettings["WeixinQrCodePath"].TryToString(); //配置的文件地址
            string rootpath = System.AppDomain.CurrentDomain.BaseDirectory;//程序運行地址
            string path = rootpath + WeixinQrCodePath; //文件夾絕對路徑
            string filename = Guid.NewGuid().TryString() + ".jpg";
            string absolutelyPath = path + "/" +filename; //生成的二維碼絕對路徑
            string returnPath = "";//文件返回的路徑
            if (!Directory.Exists(path))
            {
                Directory.CreateDirectory(path);
            }
            int Sceneid = WeixinDA.GetQrcodeImgMaxSceneid(CreatQrCodeUser);
            //保存二維碼生成的圖片
            WeixinQrCode.SaveQrCodeImage(Sceneid.TryString(), absolutelyPath);

            //最終生成二維碼
            string ResultCodeImg = path + "/" + filename; //最終合成圖片的絕對路徑
            returnPath = WeixinQrCodePath + "/" + filename;//最終合成圖片的相對路徑
            WeixinDA.SaveUserQrcodeImg(CreatQrCodeUser, Sceneid, returnPath);
            return returnPath;
        }

/// <summary>
/// 獲取二維碼圖片Url,須要Format 0.ticket
/// </summary>
public const string WeiXin_QrCode_GetUrl = "https://mp.weixin.qq.com/cgi-bin/showqrcode?ticket={0}";css

 /// <summary>
        /// 根據Ticket獲取二維碼圖片保存在本地
        /// </summary>
        /// <param name="scene_id">二維碼場景id</param>
        /// <param name="imgPath">圖片存儲路徑</param>
        public static void SaveQrCodeImage(string scene_id, string imgPath)
        {
            try
            {
                string Ticket = WeiXinCommom.CreateTicket(scene_id);

                if (Ticket == null)
                    throw new ArgumentNullException("Ticket");

                //ticket需 urlEncode
                string stUrl = string.Format(WeiXinCommom.WeiXin_QrCode_GetUrl, HttpUtility.UrlEncode(Ticket));
                WeiXinCommom.SaveUrlImage(stUrl, imgPath);
            }
            catch (Exception ex)
            {
                LogHelper.WriteFileLog("qrcodeError", ex.Message);
            }
        }

public const string WeiXin_Ticket_CreateUrl = "https://api.weixin.qq.com/cgi-bin/qrcode/create?access_token={0}";

public const string QrCodeTicket_Create_TempJsonStrin = "{\"expire_seconds\": 604800, \"action_name\": \"QR_SCENE\", \"action_info\": {\"scene\": {\"scene_id\": {0}}}}";

 /// <summary>
        /// 獲取Ticket
        /// </summary>
        /// <returns></returns>
        public static string CreateTicket(string scene_id)
        {
            string access_token = WeiXinCommom.GetAccsss_token(); ;

            if (string.IsNullOrEmpty(access_token))
                throw new ArgumentNullException("Access_Token");

            string url = string.Format(WeiXin_Ticket_CreateUrl, access_token);
            string postData = QrCodeTicket_Create_TempJsonStrin.Replace("{0}", scene_id);
            string result = PostData(url, postData);
            WeixinQrCode.Ticket ticket = JsonConvert.DeserializeObject<WeixinQrCode.Ticket>(result);

            if (ticket == null || string.IsNullOrEmpty(ticket.ticket))
            {
                FileLog.AddLog("ticket", "獲取二維碼ticket失敗");
                return "";
            }
            return ticket.ticket;
        }

 /// <summary>
        /// Post數據
        /// </summary>
        /// <param name="posturl"></param>
        /// <param name="postData"></param>
        /// <returns></returns>
        public static string PostData(string posturl, string postData)
        {
            Stream outstream = null;
            Stream instream = null;
            StreamReader sr = null;
            HttpWebResponse response = null;
            HttpWebRequest request = null;
            Encoding encoding = Encoding.UTF8;
            byte[] data = encoding.GetBytes(postData);
            // 準備請求...
            try
            {
                // 設置參數
                request = WebRequest.Create(posturl) as HttpWebRequest;
                CookieContainer cookieContainer = new CookieContainer();
                request.CookieContainer = cookieContainer;
                request.AllowAutoRedirect = true;
                request.Method = "POST";
                request.ContentType = "application/x-www-form-urlencoded";
                request.ContentLength = data.Length;
                outstream = request.GetRequestStream();
                outstream.Write(data, 0, data.Length);
                outstream.Close();
                //發送請求並獲取相應迴應數據
                response = request.GetResponse() as HttpWebResponse;
                //直到request.GetResponse()程序纔開始向目標網頁發送Post請求
                instream = response.GetResponseStream();
                sr = new StreamReader(instream, encoding);
                //返回結果網頁(html)代碼
                string content = sr.ReadToEnd();
                string err = string.Empty;
                return content;
            }
            catch (Exception ex)
            {
                LogHelper.WriteFileLog("PostDataerror", string.Format("{0}", ex.Message));
                return string.Empty;
            }
        }
相關文章
相關標籤/搜索