后端接口生成微信小程序二维码Api

后端接口生成微信小程序二维码Api

官方文档请参考:
https://developers.weixin.qq.com/miniprogram/dev/api-backend/open-api/qr-code/wxacode.getUnlimited.html

        public ActionResult Index()
        {
            string DataJson = string.Empty;
            string appId = "******";//小程序唯一凭证,即 AppID
            string appSecret = "******";小程序唯一凭证密钥,即 AppSecret
           
            #region 使用senparc获取accessToken
            var isGLobalDebug = false;//设置全局 Debug 状态
            var senparcSetting = SenparcSetting.BuildFromWebConfig(isGLobalDebug);
            var register = RegisterService.Start(senparcSetting).UseSenparcGlobal();//CO2NET全局注册,必须!

            var isWeixinDebug = false;//设置微信 Debug 状态
            var senparcWeixinSetting = SenparcWeixinSetting.BuildFromWebConfig(isWeixinDebug);
            register.UseSenparcWeixin(senparcWeixinSetting, senparcSetting);////微信全局注册,必须!

            //自动管理accessToken如果过期自动注册
            string accessToken = AccessTokenContainer.TryGetAccessToken(appId, appSecret); 
            #endregion

            if (string.IsNullOrWhiteSpace(accessToken))
            {
                 //提示获取accessToken失败
            }
            string url = "https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token=" + accessToken;

            DataJson = "{";
            DataJson += string.Format("\"scene\":\"{0}\",", "123");//单参数
            //DataJson += string.Format("\"scene\":\"{0}\",", "phone=15724521547&name=张三&sex=男"); 多参数表达方式1
             //DataJson += string.Format("\"scene\":\"{0}\",", "15724521547,张三,男"); 多参数表达方式2
            DataJson += string.Format("\"width\":\"{0}\",", 124);
            DataJson += string.Format("\"page\":\"{0}\",", "pages/index/index");
            DataJson += "\"line_color\":{";
            DataJson += string.Format("\"r\":\"{0}\",", "0");
            DataJson += string.Format("\"g\":\"{0}\",", "0");
            DataJson += string.Format("\"b\":\"{0}\"", "0");
            DataJson += "}";
            DataJson += "}";

            string ret = PostMoths(url, DataJson); 
            ViewBag.Url = ret;//返回的信息
            return View();
        }

           private static string PostMoths(string url, string param)
            {
            try
            {
                string imgsrc = "";
                string strURL = url;
                System.Net.HttpWebRequest request;
                request = (System.Net.HttpWebRequest)WebRequest.Create(strURL);
                request.Method = "POST";
                request.ContentType = "application/json;charset=UTF-8";
                string paraUrlCoded = param;
                byte[] payload;
                payload = System.Text.Encoding.UTF8.GetBytes(paraUrlCoded);
                request.ContentLength = payload.Length;
                Stream writer = request.GetRequestStream();
                writer.Write(payload, 0, payload.Length);
                writer.Close();
                System.Net.HttpWebResponse response;
                response = (System.Net.HttpWebResponse)request.GetResponse();
                if (response.ContentType.Equals("image/jpeg")) 
                {
                    System.IO.Stream s=response.GetResponseStream();//返回图片数据流
                    byte[] tt = StreamToBytes(s);//将数据流转为byte[]
                    if (tt.Length > 0)
                    {
                        string imgName = DateTime.Now.ToString("yyyyMMddhhmmss") + ".jpg";
                        string path = "/image/";
                        //创建目录
                        string imgPath = System.AppDomain.CurrentDomain.BaseDirectory + path;
                        if (!Directory.Exists(imgPath))//如果不存在就创建 dir 文件夹  
                            Directory.CreateDirectory(imgPath);
                        //将byte[]存储为图片
                        System.IO.File.WriteAllBytes(HttpContext.Current.Server.MapPath(path + imgName), tt);
                        imgsrc= "/image/" + imgName;
                    }

                }
                else
                {
                    //45009 调用分钟频率受限(目前5000次/分钟,会调整),如需大量小程序码,建议预生成。
                    //41030 所传page页面不存在,或者小程序没有发布 	
                    //data format error(很有可能是参数json格式错误)
                    StreamReader reader = new StreamReader(response.GetResponseStream(), System.Text.Encoding.Default);
                    var returnResult = reader.ReadToEnd();
                    dynamic obj = Newtonsoft.Json.JsonConvert.DeserializeObject<dynamic>(returnResult);
                    imgsrc= "errcode:" + obj.errcode + " errmsg:" + obj.errmsg;//返回的错误信息
                }
                return imgsrc;
            }
            catch (Exception exce)
            {
                return "";
            }

        }

         //将数据流转为byte[]
         private static byte[] StreamToBytes(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();
        }

你可能感兴趣的