1. 程式人生 > >c# 生成微信公眾帳號帶引數二維碼類

c# 生成微信公眾帳號帶引數二維碼類

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Web;
using LitJson;
using Newtonsoft.Json.Linq;
using Newtonsoft.Json;

/// <summary>
/// Ticket 的摘要說明
/// </summary>
public class Ticket
{
	public Ticket()
	{
		//
		// TODO: 在此處新增建構函式邏輯
		//
	}



    public static  string GetewmPic( string scene_id)
    {
        string tocket = "";
        string pic="";
        if (Config.GetInstance().SystemSetting.Appid!=""&&Config.GetInstance().SystemSetting.seconid!="")
        {

            string appid = Config.GetInstance().SystemSetting.Appid;// "wx5955bd71e310a7b5";
            string secret = Config.GetInstance().SystemSetting.seconid;// "2d6b6ec95cde8bc2908713bde4c92434";
            string parm = "grant_type=client_credential&appid=" + appid + "&secret=" + secret + "";//2d6b6ec95cde8bc2908713bde4c92434
            string url = "https://api.weixin.qq.com/cgi-bin/token";
            string b = webRequestGet(url, parm);
            b = SubString1(b, "{\"access_token\":\"", "\",\"expires_in\":7200}");//acc_tonke

          
            string poster = "{\"action_name\": \"QR_LIMIT_SCENE\",\"action_info\": {\"scene\": { \"scene_id\": "+scene_id+" } }";//二維碼永久請求格式

            string tockes = GetPage("https://api.weixin.qq.com/cgi-bin/qrcode/create?access_token=" +b+ "", poster + "");
            if(tockes.IndexOf("ticket")>-1)
            {
                JsonData bejson = JsonMapper.ToObject(tockes);
                tocket =(String)bejson["ticket"];
                tocket = Uri.EscapeDataString(tocket);//TICKET必需UrlEncode
            }
           
           
            string Picurl = "https://mp.weixin.qq.com/cgi-bin/showqrcode?ticket="+tocket+"";
           
            HttpWebRequest req = (HttpWebRequest)WebRequest.Create(Picurl);
            req.Proxy = null;
            req.UserAgent = "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:11.0) Gecko/20100101 Firefox/11.0";
            req.Headers.Add("Accept-Language", "zh-cn,en-us;q=0.8,zh-hk;q=0.6,ja;q=0.4,zh;q=0.2");
            req.Accept = "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8";
            ServicePointManager.ServerCertificateValidationCallback = delegate { return true; };
            ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3;
            //HttpWebResponse myResponse = (HttpWebResponse)req.GetResponse();
           
            System.Drawing.Image img = System.Drawing.Image.FromStream(req.GetResponse().GetResponseStream());
            string newfilename = "ewm_" + scene_id + ".jpg";//二維碼圖片路徑
           // string filepath = @"D:\專案\wsl\ewmPic\" + newfilename;
            string address = HttpContext.Current.Server.MapPath(SysConfig.ApplicationPath+"/ewmPic/"+newfilename);
            img.Save(address);

            pic = "ewmPic/" + newfilename;
        }
        return pic;
        
        
    }


    /// <summary>
    /// Post 提交呼叫抓取
    /// </summary>
    /// <param name="url">提交地址</param>
    /// <param name="param">引數</param>
    /// <returns>string</returns>
    public static string webRequestPostOAuth(string url)
    {
        //  byte[] bs = System.Text.Encoding.UTF8.GetBytes(param);

        HttpWebRequest req = (HttpWebRequest)HttpWebRequest.Create(url);
        req.Method = "GET";
        using (WebResponse wr = req.GetResponse())
        {
            //在這裡對接收到的頁面內容進行處理 

            Stream strm = wr.GetResponseStream();

            StreamReader sr = new StreamReader(strm, System.Text.Encoding.UTF8);

            string line;

            System.Text.StringBuilder sb = new System.Text.StringBuilder();

            while ((line = sr.ReadLine()) != null)
            {
                sb.Append(line);
            }
            sr.Close();
            strm.Close();
            return sb.ToString();
        }
    }



    public static string SubString1(string sourceStr, string beginStr, string endStr)
    {
        int begin = sourceStr.IndexOf(beginStr);
        if (begin == -1) return "";
        int end = sourceStr.IndexOf(endStr, begin + beginStr.Length);
        if (end == -1 && end == begin + beginStr.Length) return "";

        return sourceStr.Substring(begin + beginStr.Length, end - begin - beginStr.Length);

    }
    /// <summary>
    /// GET 提交呼叫抓取
    /// </summary>
    /// <param name="url">提交地址</param>
    /// <param name="param">引數</param>
    /// <returns>string</returns>
    public static string webRequestGet(string url, string param)
    {
        byte[] bs = System.Text.Encoding.UTF8.GetBytes(param);

        HttpWebRequest req = (HttpWebRequest)HttpWebRequest.Create(url + "?" + param);
        req.Method = "GET";
        using (WebResponse wr = req.GetResponse())
        {
            //在這裡對接收到的頁面內容進行處理 

            Stream strm = wr.GetResponseStream();

            StreamReader sr = new StreamReader(strm, System.Text.Encoding.UTF8);

            string line;

            System.Text.StringBuilder sb = new System.Text.StringBuilder();

            while ((line = sr.ReadLine()) != null)
            {
                sb.Append(line);
            }
            sr.Close();
            strm.Close();
            return sb.ToString();
        }
    }
    public static string GetPage(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)
        {
            string err = ex.Message;
            return string.Empty;
        }
    }

}