/// <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;
        }

 

posted on 2021-04-16 12:59  不知勿言  阅读(225)  评论(0编辑  收藏  举报