隐藏

生成小程序二维码

发布:2022/3/26 17:17:05作者:管理员 来源:本站 浏览次数:1311

一、获取accessToken
定义一个方法,请求官方api文档,获取token,参数是小程序的appid跟secret,可以在微信公众平台上直接复制下来

        /// <summary>
        /// 获取accessToken
        /// </summary>
        /// <param name="appid"></param>
        /// <param name="secret"></param>
        /// <returns></returns>
        public static string GetAccessToken(string appid,string secret)
        {
            string token =  HttpHelper.HttpGet("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" + appid + "&secret=" + secret);
            Newtonsoft.Json.Linq.JObject _jObject = Newtonsoft.Json.Linq.JObject.Parse(token);
            var _value = _jObject["access_token"].ToString();    //取值
            return _value;
        }

        这个是上面定义的HttpGet 的方法,已经封装好了的,如果自己有定义好了的,就不用复制过去
        /// <summary>
        /// HTTP GET方式请求数据.
        /// </summary>
        /// <param name="url">URL.</param>
        /// <returns></returns>
        public static string HttpGet(string url)
        {
            HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(url);
            request.Method = "GET";
            //request.ContentType = "application/x-www-form-urlencoded";
            request.Accept = "*/*";
            request.Timeout = 15000;
            request.AllowAutoRedirect = false;

            WebResponse response = null;
            string responseStr = null;
            try
            {
                response = request.GetResponse();

                if (response != null)
                {
                    StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.UTF8);
                    responseStr = reader.ReadToEnd();
                    reader.Close();
                }
            }
            catch (Exception)
            {
                throw;
            }
            finally
            {
                request = null;
                response = null;
            }
            return responseStr;
        }

上面的是获取token的方法,下面的是生成小程序二维码的方法
        /// <summary>
        /// 生成小程序二维码
        /// </summary>
        /// <param name="path">生成的小程序二维码存放的路径</param>
        /// <param name="scene">参数 最多32位</param>
        /// <param name="page">小程序页面路径 必须是已经发布了的</param>
        /// <param name="width">二维码大小</param>
        /// <param name="appid">小程序appid</param>
        /// <param name="secret">小程序密钥</param>
        /// <returns></returns>
        public static bool CreateXcxQrCode(string path,string scene,string page,string width,string appid,string secret)
        {
            try
            {
                string token = GetAccessToken(appid, secret);
                string _url = "https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token=" + token;
                string strURL = _url;
                System.Net.HttpWebRequest request;
                request = (System.Net.HttpWebRequest)System.Net.WebRequest.Create(strURL);
                request.Method = "POST";
                request.ContentType = "application/json;charset=UTF-8";
                string options = "{\"scene\":\"" + scene + "\",\"page\":\"" + page + "\",\"width\":\"" + width + "\"}";
                byte[] payload;
                payload = System.Text.Encoding.UTF8.GetBytes(options);
                request.ContentLength = payload.Length;
                System.IO.Stream writer = request.GetRequestStream();
                writer.Write(payload, 0, payload.Length);
                writer.Close();
                System.Net.HttpWebResponse response;
                response = (System.Net.HttpWebResponse)request.GetResponse();

                System.IO.Stream s;
                s = response.GetResponseStream();
                byte[] val = StreamToBytes(s);

                System.IO.File.WriteAllBytes(path, val);
                s.Dispose();
                writer.Dispose();
            }
            catch(Exception e)
            {
                log4net.LogManager.GetLogger("生成小程序二维码异常").Info(e);
                return false;
            }
            return true;
        }
        public static byte[] StreamToBytes(System.IO.Stream stream)
        {
            List<byte> bytes = new List<byte>();
            int temp = stream.ReadByte();
            while (temp != -1)
            {
                bytes.Add((byte)temp);
                temp = stream.ReadByte();
            }
            return bytes.ToArray();
        }
中间如果报错的话,是没有添加引用,鼠标悬浮在报错的代码上,右击选择添加引用即可。