Beispiel #1
0
        /// <summary>
        /// 申请退款订单
        /// </summary>
        /// <param name="out_trade_no">商户订单号</param>
        /// <param name="out_refund_no">商户退款单号</param>
        /// <param name="total_fee">订单金额,单位/分</param>
        /// <param name="refund_fee">申请退款金额,单位/分</param>
        /// <param name="notify_url">退款异步通知回调地址</param>
        /// <param name="refund_desc">退款原因</param>
        /// <returns>callback xml</returns>
        public string Refund(string out_trade_no, string out_refund_no, string total_fee, string refund_fee, string notify_url = null, string refund_desc = null)
        {
            #region 查询map
            SortedDictionary <string, string> sortedDictionary = new SortedDictionary <string, string>()
            {
                { "appid", WxConfig.AppId },            //微信分配的公众账号ID(企业号corpid即为此appId)
                { "mch_id", WxConfig.MCH_ID },          //商户号
                { "nonce_str", WxUtils.RandomStr(16) }, //随机16位字符串
                { "out_refund_no", out_refund_no },     //商户内部退款单号,同一单号退款多次申请只退一次
                { "out_trade_no", out_trade_no },       //商户订单号
                { "total_fee", total_fee },             //订单总金额
                { "refund_fee", refund_fee },           //申请退款金额,不能大于订单总金额
            };
            if (string.IsNullOrEmpty(notify_url))
            {
                sortedDictionary.Add("notify_url", notify_url);
            }
            if (string.IsNullOrEmpty(notify_url))
            {
                sortedDictionary.Add("refund_desc", refund_desc);
            }
            #endregion

            #region 生成sign
            string md5key = $@"{ sortedDictionary.SortedDictionaryToWxUrl()}&key={WxConfig.PARTNER_ID}";
            string sign   = WxUtils.GetSign(md5key, "utf-8");
            string xml    = sortedDictionary.SortedDictionaryToWxXml().Replace("</xml>", $@"<sign><![CDATA[{ sign }]]></sign></xml>");
            #endregion

            return(WxUtils.PostToWxOpenApi(refundUrl, xml));
        }
 public void MobliePay()
 {
     using (MemoryStream ms = new MemoryStream())
     {
         Request.Body.CopyTo(ms);
         byte[] bytes         = ms.ToArray();
         string requestxml    = Encoding.UTF8.GetString(bytes);
         string return_string = string.Empty;
         SortedDictionary <string, string> map = new SortedDictionary <string, string>();
         object obj = WxUtils.XmlDeserialize(typeof(MobilePayCallbackDto), requestxml);
         if (obj is MobilePayCallbackDto && ((MobilePayCallbackDto)obj).result_code == "SUCCESS")
         {
             //成功则在此对订单执行操作
             map.Add("return_code", "SUCCESS");
             map.Add("return_msg", "");
         }
         else
         {
             map.Add("return_code", "FAIL");
             map.Add("return_msg", "统一下单失败");
         }
         string xml      = map.SortedDictionaryToWxXml();
         Stream stream   = ms;
         var    respbyte = Encoding.UTF8.GetBytes(xml);
         //contextAccessor.HttpContext.Response.Body.EndWrite(stream.WriteAsync(respbyte, 0, respbyte.Length));
         Response.Body.Write(respbyte, 0, respbyte.Length);
     }
 }
Beispiel #3
0
        public async Task <IActionResult> WxLoginAsync(WxLoginParam loginParam)
        {
            // 使用IHttpClientFactory创建的HttpClient
            OpenIdParam openIdParam = await WxUtils.GetOpenIdAsync(loginParam, clientFactory.CreateClient());

            if (openIdParam == null || string.IsNullOrEmpty(openIdParam.session_key))
            {
                return(ValidationProblem("验证错误,Secret可能失效"));
            }
            WxPhoneModel wxPhoneModel = WxAppEncryptUtil.GetEncryptedDataStr(loginParam.EncryptedData, openIdParam.session_key, loginParam.Iv);

            if (wxPhoneModel == null)
            {
                return(ValidationProblem("用户信息解析错误"));
            }
            string phone = wxPhoneModel.PurePhoneNumber ?? wxPhoneModel.PhoneNumber;

            if (string.IsNullOrEmpty(phone))
            {
                return(ValidationProblem("可能未绑定手机号"));
            }
            TbUser user = await rep.GetEntityAsync(s => s.Phone.Equals(phone), s => new TbUser {
                State = s.State
            });

            if (user == null)
            {
                return(ValidationProblem("用户未注册"));
            }
            string token = AuthorizationUtil.GetToken(30, user.Id, user.Name, "user", user.CarNum);

            return(Ok(new { access_token = token }));
        }
Beispiel #4
0
        /// <summary>
        /// 申请支付
        /// </summary>
        public string Paying(string auth_code, string device_info, string body, string out_trade_no, string notify_url, string total_fee)
        {
            string ip = _contextAccessor.HttpContext.Connection.RemoteIpAddress.MapToIPv4().ToString();

            #region  单map
            SortedDictionary <string, string> sortedDictionary = new SortedDictionary <string, string>()
            {
                { "appid", WxConfig.AppId },            //微信分配的公众账号ID(企业号corpid即为此appId)
                { "attach", "wxpay" },                  //说明.
                { "auth_code", auth_code },             //扫码支付授权码
                { "body", body },                       //xxx店-收银机收款
                { "device_info", device_info },         //设备号
                { "mch_id", WxConfig.MCH_ID },          //商户号
                { "nonce_str", WxUtils.RandomStr(16) }, //随机16位字符串
                { "out_trade_no", out_trade_no },       //订单号
                { "notify_url", notify_url },
                { "spbill_create_ip", ip },             //用户IP
                { "total_fee", total_fee },             //金额
            };
            #endregion

            #region 生成sign
            string md5key = $@"{ sortedDictionary.SortedDictionaryToWxUrl()}&key={WxConfig.PARTNER_ID}";
            string sign   = WxUtils.GetSign(md5key, "utf-8");
            string xml    = sortedDictionary.SortedDictionaryToWxXml().Replace("</xml>", $@"<sign><![CDATA[{ sign }]]></sign></xml>");
            #endregion

            return(WxUtils.PostToWxOpenApi(payByCardUrl, xml));
        }
Beispiel #5
0
 public PayResult ToPayResult()
 {
     try
     {
         PayResult result = new PayResult();
         result.appid          = GetValue("appid") == null ? "" : GetValue("appid").ToString();
         result.mch_id         = GetValue("mch_id") == null ? "" : GetValue("mch_id").ToString();
         result.attach         = GetValue("attach") == null ? "" : GetValue("attach").ToString();
         result.err_code       = GetValue("err_code") == null ? "" : GetValue("err_code").ToString();
         result.err_code_des   = GetValue("err_code_des") == null ? "" : GetValue("err_code_des").ToString();
         result.fee_type       = GetValue("fee_type") == null ? "" : GetValue("fee_type").ToString();
         result.is_subscribe   = GetValue("is_subscribe") == null ? "" : GetValue("is_subscribe").ToString();
         result.openid         = GetValue("openid") == null ? "" : GetValue("openid").ToString();
         result.out_trade_no   = GetValue("out_trade_no") == null ? "" : GetValue("out_trade_no").ToString();
         result.result_code    = GetValue("result_code") == null ? "" : GetValue("result_code").ToString();
         result.time_end       = DateTime.ParseExact(GetValue("time_end").ToString(), "yyyyMMddHHmmss", null);
         result.total_fee      = Convert.ToInt32(GetValue("total_fee").ToString());
         result.trade_type     = GetValue("trade_type") == null ? "" : GetValue("trade_type").ToString();
         result.transaction_id = GetValue("transaction_id") == null ? "" : GetValue("transaction_id").ToString();
         if (!string.IsNullOrEmpty(result.attach))
         {
             //支付类型是在支付的时候paytype参数带过来的
             string paytype = WxUtils.getAttachValue(result.attach, "paytype");
             if (!string.IsNullOrEmpty(paytype))
             {
                 int type;
                 if (int.TryParse(paytype, out type))
                 {
                     result.paytype = type;
                 }
             }
             else
             {
                 log4net.LogHelper.WriteError(typeof(ResultNotify), new WxPayException("警报:回调函数获取不到支付类型!"));
             }
         }
         if (string.IsNullOrEmpty(result.transaction_id) || string.IsNullOrEmpty(result.openid))
         {
             return(null);
         }
         return(result);
     }
     catch (Exception ex)
     {
         throw ex;
     }
 }
Beispiel #6
0
        /// <summary>
        ///统一下单接口
        /// </summary>
        /// <param name="total_fee">订单金额</param>
        /// <param name="out_trade_no">订单号</param>
        /// <returns></returns>
        public MobilePayOutput Paying(string total_fee, string out_trade_no)
        {
            #region 统一下单map
            SortedDictionary <string, string> sortedDictionary = new SortedDictionary <string, string>()
            {
                { "appid", WxConfig.AppId },
                { "attach", "wxpay" },
                { "body", "订单支付" },
                { "mch_id", WxConfig.MCH_ID },
                { "nonce_str", WxUtils.RandomStr(16) },
                { "notify_url", WxConfig.AppPayNodifyUrl },
                { "spbill_create_ip", "" }, //用户IP
                { "total_fee", total_fee }, //金额
                { "trade_type", "APP" },
                { "out_trade_no", out_trade_no }//订单号
            };
            #endregion

            #region 生成sign
            string md5key = $@"{ sortedDictionary.SortedDictionaryToWxUrl()}&key={WxConfig.PARTNER_ID}";
            string sign   = WxUtils.GetSign(md5key, "utf-8");
            #endregion

            #region 请求微信统一下单接口 获取预支付订单号
            string xml         = sortedDictionary.SortedDictionaryToWxXml().Replace("</xml>", $@"<sign><![CDATA[{ sign }]]></sign></xml>");
            string callbackXml = WxUtils.PostToWxOpenApi(unifiedorderUrl, xml);//请求微信统一下单接口
            MobilePayCallbackDto callbackobj = (MobilePayCallbackDto)WxUtils.XmlDeserialize(typeof(MobilePayCallbackDto), callbackXml);
            #endregion

            #region 用户端sign
            MobilePayOutput output = new MobilePayOutput
            {
                appid     = WxConfig.AppId,
                noncestr  = WxUtils.RandomStr(16),
                package   = "Sign=WXPay",
                partnerid = WxConfig.PARTNER_ID,
                prepayid  = callbackobj.prepay_id,
                timestamp = DateTime.UtcNow.ToTimeStamp(),
                sign      = "",
            };
            var    appmap    = WxUtils.ObjToSortedDictionary(output);
            string appmd5key = $@"{ appmap.SortedDictionaryToWxUrl()}&key={WxConfig.PARTNER_ID}";
            output.sign = WxUtils.GetSign(appmd5key, "utf-8");
            #endregion
            return(output);
        }
Beispiel #7
0
        /// <summary>
        /// 根据商户订单号查询微信支付状态
        /// </summary>
        /// <param name="out_trade_no">商户订单号</param>
        /// <returns></returns>
        public string OrderQueryByOrderNumber(string out_trade_no)
        {
            #region 查询map
            SortedDictionary <string, string> sortedDictionary = new SortedDictionary <string, string>()
            {
                { "appid", WxConfig.AppId },            //微信分配的公众账号ID(企业号corpid即为此appId)
                { "mch_id", WxConfig.MCH_ID },          //商户号
                { "nonce_str", WxUtils.RandomStr(16) }, //随机16位字符串
                { "out_trade_no", out_trade_no }//微信订单号
            };
            #endregion
            #region 生成sign
            string md5key = $@"{ sortedDictionary.SortedDictionaryToWxUrl()}&key={WxConfig.PARTNER_ID}";
            string sign   = WxUtils.GetSign(md5key, "utf-8");
            string xml    = sortedDictionary.SortedDictionaryToWxXml().Replace("</xml>", $@"<sign><![CDATA[{ sign }]]></sign></xml>");
            #endregion

            return(WxUtils.PostToWxOpenApi(orderQueryUrl, xml));
        }
Beispiel #8
0
        //回调根据PayResult处理回调
        public bool NotifyOper(PayResult result)
        {
            if (WxUtils.getAttachValue(result.attach, "from") == "city")
            {
                CityMordersBLL citybll    = new CityMordersBLL(result);
                string         orderidstr = WxUtils.getAttachValue(result.attach, "orderid");
                if (string.IsNullOrEmpty(orderidstr))
                {
                    log4net.LogHelper.WriteError(GetType(), new Exception(JsonConvert.SerializeObject(result)));
                    return(false);
                }
                int         orderid = Convert.ToInt32(orderidstr);
                CityMorders order   = citybll.GetModel(orderid);
                //修改订单支付状态
                if (order == null)
                {
                    Exception ex = new Exception("警报:根据支付单号找不到相关订单!" + " out_trade_no='" + result.out_trade_no + "'");
                    log4net.LogHelper.WriteError(GetType(), ex);
                    log4net.LogHelper.WriteError(GetType(), new Exception(JsonConvert.SerializeObject(result)));
                    return(false);
                }
                if (order.payment_status != 0)
                {
                    return(false);
                }
                if (order.Percent < 0 || order.Percent > 100)
                {
                    Exception ex = new Exception("警报:出现异常订单!订单提成百分比为:" + order.Percent + " out_trade_no='" + result.out_trade_no + "'");
                    log4net.LogHelper.WriteError(GetType(), ex);
                    log4net.LogHelper.WriteError(GetType(), new Exception(JsonConvert.SerializeObject(result)));
                    return(false);
                }
                citybll.Order = order;
                //修改order支付商户
                order.mch_id = result.mch_id;
                order.appid  = result.appid;
                citybll.Update(order);
                switch (result.paytype)
                {
                //小程序商城
                case (int)ArticleTypeEnum.MiniappGoods:
                    return(citybll.MiniappStoreGoods());

                //小程序餐饮
                case (int)ArticleTypeEnum.MiniappFoodGoods:
                    return(citybll.MiniappFoodGoods());

                //小程序储值
                case (int)ArticleTypeEnum.MiniappSaveMoneySet:
                    return(citybll.MiniappSaveMoney());

                //小程序砍价
                case (int)ArticleTypeEnum.MiniappBargain:
                    return(citybll.MiniappBargainMoney());

                //小程序拼团
                case (int)ArticleTypeEnum.MiniappGroups:
                    return(citybll.MiniappStoreGroup());

                //小程序专业版
                case (int)ArticleTypeEnum.MiniappEnt:
                    return(citybll.MiniappEntGoods());

                //小程序足浴版
                case (int)ArticleTypeEnum.MiniappFootbath:
                    return(citybll.MiniappFootbath());

                case (int)ArticleTypeEnum.MiniappMultiStore:
                    return(citybll.MiniappMultiStore());

                //小程序专业版积分兑换(微信+积分方式兑换)
                case (int)ArticleTypeEnum.MiniappExchangeActivity:
                    return(citybll.PayMiniappExchangeActivity());

                //小程序同城模板
                case (int)ArticleTypeEnum.City_StoreBuyMsg:
                    return(citybll.cityBuyMsg());

                //小程序直接微信转账
                case (int)ArticleTypeEnum.MiniappWXDirectPay:
                    return(citybll.PayByStoredvalue());

                //智慧餐厅
                case (int)ArticleTypeEnum.DishOrderPay:
                    return(citybll.PayDishOrder());

                case (int)ArticleTypeEnum.DishStorePayTheBill:
                    return(citybll.PayDishStorePayTheBill());

                case (int)ArticleTypeEnum.DishCardAccount:
                    return(citybll.PayDishCardAccount());

                //平台版小程序分类信息发帖
                case (int)ArticleTypeEnum.PlatMsgPay:
                    return(citybll.PlatMsgPay());

                //付费内容支付购买
                case (int)ArticleTypeEnum.PayContent:
                    return(citybll.PayContentCallBack());

                //子模版订单平台支付
                case (int)ArticleTypeEnum.PlatChildOrderInPlatPay:
                //平台子模版支付
                case (int)ArticleTypeEnum.PlatChildOrderPay:
                    return(citybll.MiniappPlatChildGoods());

                //拼享惠支付
                case (int)ArticleTypeEnum.PinOrderPay:
                    return(citybll.PayPinOrder());

                //平台子模版支付
                case (int)ArticleTypeEnum.QiyeOrderPay:
                    return(citybll.QiyePayOrder());

                //平台店铺入驻支付
                case (int)ArticleTypeEnum.PlatAddStorePay:
                    return(citybll.PlatAddStorePay());

                //平台店铺续期支付
                case (int)ArticleTypeEnum.PlatStoreAddTimePay:
                    return(citybll.PlatStoreAddTimePay());

                //专业版预约表单付费
                case (int)ArticleTypeEnum.EntSubscribeFormPay:
                    return(citybll.EntSubscribeFormPay());
                }
            }
            return(false);
        }
Beispiel #9
0
        public CreateCardResult AddWxCoupons(Coupons coupons, XcxAppAccountRelation xcx, string accountId)
        {
            //默认专业版的
            string           center_app_brand_pass = "******";   //专业版 个人中心
            string           custom_app_brand_pass = "******"; //首页 专业版
            string           logo_url          = string.Empty;
            string           brand_name        = string.Empty;
            string           appOriginalId     = string.Empty;
            CreateCardResult _createCardResult = new CreateCardResult();
            XcxTemplate      xcxTemplate       = XcxTemplateBLL.SingleModel.GetModel($"id={xcx.TId}");

            if (xcxTemplate == null)
            {
                _createCardResult.errcode = 1;
                _createCardResult.errmsg  = "小程序模板不存在";
                return(_createCardResult);
            }

            List <OpenAuthorizerConfig> listOpenAuthorizerConfig = OpenAuthorizerConfigBLL.SingleModel.GetListByaccoundidAndRid(accountId, xcx.Id, 4);

            if (listOpenAuthorizerConfig == null)
            {
                _createCardResult.errcode = 1;
                _createCardResult.errmsg  = "请先绑定认证服务号才有生成卡券权限";
                return(_createCardResult);
            }
            OpenAuthorizerConfig umodel = listOpenAuthorizerConfig[0];

            switch (xcxTemplate.Type)
            {
            case (int)TmpType.小程序专业模板:
                EntSetting ent = EntSettingBLL.SingleModel.GetModel(coupons.appId);
                if (ent == null)
                {
                    _createCardResult.errcode = 1;
                    _createCardResult.errmsg  = "该专业版信息找不到";
                    return(_createCardResult);
                }
                OpenAuthorizerConfig XUserList = OpenAuthorizerConfigBLL.SingleModel.GetModelByAppids(xcx.AppId);
                if (XUserList == null)
                {
                    _createCardResult.errcode = 1;
                    _createCardResult.errmsg  = "请先授权给平台";
                    return(_createCardResult);
                }
                ConfParam imginfo = ConfParamBLL.SingleModel.GetModelByParamappid("logoimg", xcx.AppId);
                if (imginfo == null)
                {
                    _createCardResult.errcode = 1;
                    _createCardResult.errmsg  = "请先到小程序管理配置底部Logo";
                    return(_createCardResult);
                }
                logo_url   = imginfo.Value;
                brand_name = XUserList.nick_name;

                break;

            case (int)TmpType.小程序电商模板:
                center_app_brand_pass = "******";    //个人中心页面
                Store store = StoreBLL.SingleModel.GetModelByAId(xcx.Id);
                if (store == null)
                {
                    _createCardResult.errcode = 1;
                    _createCardResult.errmsg  = "电商版店铺不存在";
                    return(_createCardResult);
                }
                logo_url   = store.logo;
                brand_name = store.name;
                break;

            case (int)TmpType.小程序餐饮模板:
                center_app_brand_pass = "******";     //个人中心页面
                custom_app_brand_pass = "******"; //首页
                Food miAppFood = FoodBLL.SingleModel.GetModel($"appId={xcx.Id}");
                if (miAppFood == null)
                {
                    _createCardResult.errcode = 1;
                    _createCardResult.errmsg  = "餐饮版店铺不存在";
                    return(_createCardResult);
                }

                logo_url   = miAppFood.Logo;
                brand_name = miAppFood.FoodsName;
                break;

            case (int)TmpType.小程序足浴模板:
            case (int)TmpType.小程序多门店模板:
                int t = 0;
                if ((int)TmpType.小程序足浴模板 == xcxTemplate.Type)
                {
                    center_app_brand_pass = "******";     //个人中心页面
                    custom_app_brand_pass = "******"; //首页
                }
                else
                {
                    center_app_brand_pass = "******";    //个人中心页面
                    t = 1;
                }
                FootBath storeModel = FootBathBLL.SingleModel.GetModel($"appId={xcx.Id}");
                if (storeModel == null)
                {
                    _createCardResult.errcode = 1;
                    _createCardResult.errmsg  = "找不到该足浴版";
                    return(_createCardResult);
                }
                brand_name = storeModel.StoreName;
                List <C_Attachment> LogoList = C_AttachmentBLL.SingleModel.GetListByCache(storeModel.Id, t == 0 ? (int)AttachmentItemType.小程序足浴版店铺logo : (int)AttachmentItemType.小程序多门店版门店logo);
                if (LogoList != null && LogoList.Count > 0)
                {
                    logo_url = LogoList[0].filepath;
                }
                break;

            case (int)TmpType.小未平台子模版:
                center_app_brand_pass = "******";      //个人中心页面
                custom_app_brand_pass = "******"; //首页
                PlatStore platStore = PlatStoreBLL.SingleModel.GetPlatStore(xcx.Id, 2);
                if (platStore == null)
                {
                    _createCardResult.errcode = 1;
                    _createCardResult.errmsg  = "平台版店铺不存在";
                    return(_createCardResult);
                }
                brand_name = platStore.Name;
                logo_url   = platStore.StoreHeaderImg;
                break;
            }

            if (string.IsNullOrEmpty(logo_url) || string.IsNullOrEmpty(brand_name))
            {
                _createCardResult.errcode = 1;
                _createCardResult.errmsg  = "请先配置Logo以及名称";
                return(_createCardResult);
            }

            //这里可能会出现token失效 个人发布的未授权给我们第三方平台的卡券会生成不了
            string xcxapiurl = XcxApiBLL.SingleModel.GetOpenAuthodModel(umodel.user_name);
            string authorizer_access_token = CommondHelper.GetAuthorizer_Access_Token(xcxapiurl);

            string uploadImgResult = CommondHelper.WxUploadImg(authorizer_access_token, logo_url);

            if (!uploadImgResult.Contains("url"))
            {
                _createCardResult.errcode = 1;
                _createCardResult.errmsg  = $"上传Logo到微信失败uploadImgResult={uploadImgResult}";
                return(_createCardResult);
            }
            if (brand_name.Length >= 12)
            {
                brand_name = brand_name.Substring(0, 12);
            }



            WxUploadImgResult wxUploadImgResult = JsonConvert.DeserializeObject <WxUploadImgResult>(uploadImgResult);

            logo_url = wxUploadImgResult.url;

            base_info _base_info = new base_info();

            _base_info.logo_url   = logo_url;
            _base_info.code_type  = "CODE_TYPE_TEXT";
            _base_info.brand_name = brand_name;
            _base_info.title      = coupons.CouponName.Length > 9 ? Utility.StringHelper.strSubstring(coupons.CouponName, 0, 8) : coupons.CouponName;
            _base_info.color      = "Color010";

            _base_info.center_title = "立即使用";
            _base_info.center_app_brand_user_name = $"{appOriginalId}@app";
            _base_info.center_app_brand_pass      = center_app_brand_pass;

            _base_info.custom_url_name            = "小程序";
            _base_info.custom_app_brand_user_name = $"{appOriginalId}@app";
            _base_info.custom_app_brand_pass      = custom_app_brand_pass;
            _base_info.custom_url_sub_title       = "点击进入";


            _base_info.description  = coupons.Desc.Length > 1024 ? Utility.StringHelper.strSubstring(coupons.Desc, 0, 1023) : coupons.Desc;
            _base_info.notice       = "使用时向服务员出示此券";
            _base_info.sku.quantity = coupons.CreateNum;
            if (coupons.LimitReceive > 0)
            {
                //大于0表示限制,0表示无限制
                _base_info.get_limit = coupons.LimitReceive;
            }


            if (coupons.ValType == 0)
            {
                //表示固定日期
                _base_info.date_info = new Firstdate_infoItem()
                {
                    begin_timestamp = WxUtils.GetWeixinDateTime(coupons.StartUseTime),
                    end_timestamp   = WxUtils.GetWeixinDateTime(coupons.EndUseTime)
                };
            }
            if (coupons.ValType == 2 || coupons.ValType == 1)
            {
                //fixed_begin_term=0表示领取后当天开始生效 1表示次日后开始生效 领取当日N天内有效
                _base_info.date_info = new Seconddate_infoItem()
                {
                    fixed_begin_term = coupons.ValType == 2?0:1,
                    fixed_term       = coupons.ValDay
                };
            }


            string json = string.Empty;

            if (coupons.CouponWay == 0)
            {
                //表示是需要生成微信代金券
                WxCashCoupons wxCashCoupons = new WxCashCoupons();
                Cash          cash          = new Cash();
                cash.base_info = _base_info;//基础字段信息

                Use_condition use_condition = new Use_condition();

                use_condition.accept_category = coupons.GoodsType == 0 ? "全部产品" : "部分产品";
                if (coupons.LimitMoney > 0)
                {
                    cash.least_cost = coupons.LimitMoney;
                    //满减门槛
                    use_condition.least_cost = coupons.LimitMoney;
                }
                use_condition.can_use_with_other_discount = coupons.discountType == 0;

                cash.reduce_cost   = coupons.Money;
                cash.advanced_info = new Advanced_info()
                {
                    use_condition = use_condition
                };
                wxCashCoupons.cash = cash;
                json = JsonConvert.SerializeObject(new { card = wxCashCoupons });
            }
            else
            {
                //表示是需要生成微信折扣券
                WxDiscountCoupons wxDiscountCoupons = new WxDiscountCoupons();
                Discount          discount          = new Discount();
                discount.base_info         = _base_info;
                discount.discount          = (int)(100 - coupons.Money * 0.1);
                wxDiscountCoupons.discount = discount;
                json = JsonConvert.SerializeObject(new { card = wxDiscountCoupons });
            }

            string result = Utility.IO.Context.PostData($"https://api.weixin.qq.com/card/create?access_token={authorizer_access_token}", json);

            if (string.IsNullOrEmpty(result))
            {
                return(_createCardResult);
            }
            _createCardResult = JsonConvert.DeserializeObject <CreateCardResult>(result);
            return(_createCardResult);
        }
Beispiel #10
0
        /// <summary>
        /// 小程序-通过OpenId快捷登录
        /// </summary>
        /// <param name="code">微信临时code</param>
        /// <returns></returns>
        public async Task <WebResponseContent> Login(string code)
        {
            WebResponseContent responseContent = new WebResponseContent();
            WxUtils            _wxUtils        = new WxUtils();
            //取出appid和secret
            var config = DbContext.Set <Hiiops_Cart_System_Config>().Where(x => x.KEYNAME == Constant.WECHATAPPID || x.KEYNAME == Constant.WECHATAPPSECRET).ToList();

            if (config.Count < 2)
            {
                return(responseContent.Error("请先配置小程序参数"));
            }

            var    appid         = CacheContext.Get <string>(Constant.WECHATAPPID);
            string applet_appid  = "";
            string applet_secret = "";

            if (appid == null)
            {
                applet_appid = config.Where(x => x.KEYNAME == Constant.WECHATAPPID).FirstOrDefault().VAL;
                CacheContext.Add(Constant.WECHATAPPID, applet_appid);
            }
            else
            {
                applet_appid = appid;
            }
            var secret = CacheContext.Get <string>(Constant.WECHATAPPSECRET);

            if (secret == null)
            {
                applet_secret = config.Where(x => x.KEYNAME == Constant.WECHATAPPSECRET).FirstOrDefault().VAL;
                CacheContext.Add(Constant.WECHATAPPSECRET, applet_secret);
            }
            else
            {
                applet_secret = secret;
            }

            //通过code取openid
            string  jsonStr = _wxUtils.GetXcxKey(code, applet_appid, applet_secret);
            JObject json    = JObject.Parse(jsonStr);
            string  openid  = json["openid"].ToString();

            if (string.IsNullOrWhiteSpace(openid))
            {
                return(responseContent.Error("服务繁忙,请重试!"));
            }
            //通过openid判断系统是否存在当前微信用户
            var user = await DbContext.Set <Hiiops_Cart_SellerUser>().Where(x => x.OpenId == openid).FirstOrDefaultAsync();

            if (user == null)
            {
                return(responseContent.Error("第一次使用请先注册!"));
            }
            string token = JwtHelper.IssueJwt(user.Id.ToString());

            user.Token           = token;
            responseContent.Data = new { token, user.NickName, user.Phone, user.Account, user.Country, user.HeadImgUrl, user.Id, user.Name, user.Privilege, user.Province, user.Remark, user.SearchKey, user.Sex, user.Status };
            DbContext.Update(user);
            SellerContent.Current.LogOut(user.Id);
            return(responseContent.OK(ResponseType.LoginSuccess));
        }