• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

生成微信小程序二维码

原作者: [db:作者] 来自: [db:来源] 收藏 邀请
        /// <summary>
        /// 获取小程序二维码
        /// </summary>
        /// <param name="req">订单id</param>
        /// <returns></returns>
        [HttpGet("GetAppletsQRCode")]
        public async Task<GetUnlimitedResponse> GetAppletsQRCode([FromQuery]PreShareReq req)
        {

            _logger.Info(new LogInfo()
            {
                Method = nameof(GetAppletsQRCode),
                Argument = new
                {
                    req
                },
                Description = "GetAppletsQRCode:获取小程序二维码参数"
            });

            GetUnlimitedResponse response = new GetUnlimitedResponse();
            if (req == null || string.IsNullOrWhiteSpace(req.OrderID))
            {
                response.errcode = 100001;
                response.errmsg = "请提供订单id";
                return response;
            }
            //var user = await IUserService.FindByUserIdAsync(SID.Value);
            OrderShares model = new OrderShares();
            model.FromShareUID = SID.Value;
            model.OrderId = req.OrderID;
            model.CreationTime = DateTime.Now;
            model.ShareBody = (int)EShareBody.PreShare;
            var id = await OrderSharesService.PreShare(model);

            string data = $"{id},{(int)EShareType.FriendCircle}";
            //page 不能带参数,参数只能放在scene中,并且不能超过32个字符(还不清楚是否包含中文等字符)
            var input = new AppletsQRCodeInput()
            {
                scene = data,
                page = $"pages/grabs/grabs-detail/main",
                width = 280,
                is_hyaline = true
            };
            var result = await WXMiniProgramAipClient.GetAppletsQRCode(input);
            response.DataType = result.contentType;
            response.errmsg = result.errmsg;
            response.errcode = result.errcode;
            if (result.errcode == 0)
            {
                using (MemoryStream ms = new MemoryStream(result.buffer))
                {
                    var r = await BlobFileStorageProvider.SaveAsync(ms, $"wxappletsqrcodes/{DateTime.Now.ToString("yyyyMMddHHmmssfff")}.jpg");
                    string path = await BlobFileStorageProvider.GetPath(r);
                    response.QRCode = path;
                }
            }
            else
            {
                throw new SinoException("获取小程序二维码失败!", ErrorCode.E100001);
            }
            _logger.Info(new LogInfo() { Method = nameof(GetAppletsQRCode), Argument = new { QRCode = result.buffer }, Description = "GetAppletsQRCode:获取小程序二维码返回结果" });
            return response;
        } 
        /// <summary>
        /// 获取小程序二维码
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public async Task<UnlimitedRes> GetAppletsQRCode(AppletsQRCodeInput input)
        {
            var UnlimitedResponse = new UnlimitedRes();
            string accessToken = "";
            var token = await RedisService.FindAsync("ccpMiniProgram_accessToken_");
            if (token != null)
            {
                var TokenRedis = JsonConvert.DeserializeObject<AccessTokenRedis>(token);
                if (DateTime.Now - TokenRedis.createTime <= TimeSpan.FromMinutes(100))
                {
                    accessToken = TokenRedis.accessToken;
                }
            }
            if (string.IsNullOrWhiteSpace(accessToken))
            {
                var response = await GetAccessToken();
                accessToken = response.access_token;
            }
            var url = string.Format("https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token={0}", accessToken);
            var postData = input.ToJson();
            try
            {
                UnlimitedResponse = await Postbyte(url, postData);
            }
            catch (Exception ex)
            {
                _logger.Error(ex, "获取小程序二维码失败");
                UnlimitedResponse.errcode = -1;
                UnlimitedResponse.errmsg = "获取小程序二维码失败";

                //return JsonConvert.DeserializeObject<UnlimitedRes>(result);
            }
            return UnlimitedResponse;
        }
   public class AppletsQRCodeInput
    {
        /// <summary>
        /// 参数
        /// </summary>
        public string scene { get; set; }

        /// <summary>
        /// 跳转小程序页面
        /// </summary>
        public string page { get; set; }

        /// <summary>
        /// 二维码的宽度,单位 px,最小 280px,最大 1280px
        /// </summary>
        public int width { get; set; } = 430;

        /// <summary>
        /// 自动配置线条颜色,如果颜色依然是黑色,则说明不建议配置主色调,默认 false
        /// </summary>
        public bool auto_color { get; set; } = false;

        /// <summary>
        /// auto_color 为 false 时生效,使用 rgb 设置颜色 例如 {"r":"xxx","g":"xxx","b":"xxx"} 十进制表示
        /// </summary>
        private LineColor _lineColor;
        public LineColor line_color
        {
            get
            {
                if (_lineColor == null)
                {
                    _lineColor = new LineColor();
                }
                return _lineColor;
            }
            set
            {
                _lineColor = value;
            }
        }

        /// <summary>
        /// 是否需要透明底色,为 true 时,生成透明底色的小程序
        /// </summary>
        public bool is_hyaline { get; set; } = false;
    }

    public class LineColor
    {
        public string r { get; set; } = "0";
        public string g { get; set; } = "0";
        public string b { get; set; } = "0";
    }

 

     /// <summary>
        /// 获取接口调用凭证
        /// </summary>
        /// <returns></returns>
        public async Task<AccessTokenRes> GetAccessToken()
        {
            var AccessTokenRes = new AccessTokenRes();

            var Geturl = string.Format(@"https://api.weixin.qq.com/cgi-bin/token?grant_type={0}&appid={1}&secret={2}", grant_type, appid, secret);
            try
            {
                var Response = await client.GetAsync(Geturl);
                var result = await Response.Content.ReadAsStringAsync();
                AccessTokenRes = JsonConvert.DeserializeObject<AccessTokenRes>(result);
            }
            catch (Exception ex)
            {
                _logger.Error(ex, "获取微信小程序接口调用凭证失败");
            }
            await RedisService.CreateAsync("ccpMiniProgram_accessToken_", new AccessTokenRedis() { accessToken = AccessTokenRes.access_token, createTime = DateTime.Now }.ToJson(), null);
            _logger.Info(new LogInfo() { Method = "GetAccessToken", Argument = new { errmsg = AccessTokenRes.errmsg }, Description = "获取接口调用凭证" });
            return AccessTokenRes;
        }
        private async Task<UnlimitedRes> Postbyte(string url, string param)
        {
            UnlimitedRes res = new UnlimitedRes()
            {
                errcode = 0,
                errmsg = "ok",
                contentType = "image/jpeg"
            };
            StringContent c = new StringContent(param, Encoding.UTF8);
            c.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/json");
            try
            {
                var response = await client.PostAsync(url, c);
                if (response.Content.Headers.ContentType.MediaType == "image/jpeg")
                {
                    res.buffer = await response.Content.ReadAsByteArrayAsync();
                }
                else
                {
                    var s = await response.Content.ReadAsStringAsync();
                    res = JsonConvert.DeserializeObject<UnlimitedRes>(s);
                }
            }
            catch (Exception ex)
            {
                _logger.Error(ex, "HttpPost接口请求失败");
                throw ex;
            }
            return res;
        }

 


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
微信小程序 - 二维码生成工具 weapp-qrcode发布时间:2022-07-18
下一篇:
「4.0」一个人开发一个App,小程序从0到1,布局发布时间:2022-07-18
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap