public IActionResult BillOfSettlement([FromBody] TextModel model)
        {
            var results = new List <SendTemplateMessageResult>();

            try
            {
                foreach (var t in model.openIds)
                {
                    var templateData = new WeixinTemplate_PaySuccess(
                        model.sheeturl,
                        "TibdpHeQ2tRibjn6smyVQsTeGhabrb-uHUDY_3sGRZI", "结算单提醒")
                    {
                        first    = new TemplateDataItem(model.array[0]),
                        keyword1 = new TemplateDataItem(model.array[1]),
                        keyword2 = new TemplateDataItem(model.array[2]),
                        keyword3 = new TemplateDataItem(model.array[3]),
                        keyword4 = new TemplateDataItem(model.array[4]),
                        remark   = new TemplateDataItem(model.array[5]),
                    };
                    var result = Send(templateData, t);
                    if (result.Result.ErrorCodeValue != 0)
                    {
                        results.Add(result.Result);
                    }
                }
            }
            catch (Exception e)
            {
                return(Content(e.Message));
            };
            return(Ok(new { code = results.Count == 0 ? 0 : 1, errorList = results }));
        }
        //[ActionName("ReceiveMessage")] [FromBody]
        public IActionResult ReceiveMessage([FromBody] TextModel model)
        {
            //TextModel model = JsonConvert.DeserializeObject<TextModel>(message);//反序列化
            var templateData = new WeixinTemplate_PaySuccess(
                "https://brmagent.gopas.com.cn/order/OrderDetail?finterid=" + model.finterid + "&FBillNo=" +
                model.array[0] + "&State=新订单&FDate=" + DateTime.Now,
                "7QwjDkatTivuRTB9SIEYX8kEu-cUWhXD9jiBFAMWaFM", "新订单")
            {
                keyword1 = new TemplateDataItem(model.array[0]), keyword2 = new TemplateDataItem(model.array[1])
            };


            try
            {
                foreach (var t in model.openIds)
                {
                    Send(templateData, t);
                }
            }
            catch (Exception e) {
                return(Content(e.ToString()));
            };
            return(Content("https://brmagent.gopas.com.cn/order/OrderDetail?finterid=" + model.finterid + "&FBillNo" + model.array[0] + "&State=新订单&FDate=" + DateTime.Now));
        }
Esempio n. 3
0
        /// <summary>
        /// JS-SDK支付回调地址(在统一下单接口中设置notify_url)
        /// </summary>
        /// <returns></returns>
        public ActionResult PayNotifyUrl()
        {
            try
            {
                ResponseHandler resHandler = new ResponseHandler(HttpContext);

                string return_code = resHandler.GetParameter("return_code");
                string return_msg  = resHandler.GetParameter("return_msg");

                string res = null;

                resHandler.SetKey(TenPayV3Info.Key);
                //验证请求是否从微信发过来(安全)
                if (resHandler.IsTenpaySign() && return_code.ToUpper() == "SUCCESS")
                {
                    res = "success";//正确的订单处理
                    //直到这里,才能认为交易真正成功了,可以进行数据库操作,但是别忘了返回规定格式的消息!
                }
                else
                {
                    res = "wrong";//错误的订单处理
                }

                /* 这里可以进行订单处理的逻辑 */

                //发送支付成功的模板消息
                try
                {
                    string appId        = Config.SenparcWeixinSetting.TenPayV3_AppId;//与微信公众账号后台的AppId设置保持一致,区分大小写。
                    string openId       = resHandler.GetParameter("openid");
                    var    templateData = new WeixinTemplate_PaySuccess("https://weixin.senparc.com", "购买商品", "状态:" + return_code);

                    Senparc.Weixin.WeixinTrace.SendCustomLog("支付成功模板消息参数", appId + " , " + openId);

                    var result = AdvancedAPIs.TemplateApi.SendTemplateMessage(appId, openId, templateData);
                }
                catch (Exception ex)
                {
                    Senparc.Weixin.WeixinTrace.SendCustomLog("支付成功模板消息", ex.ToString());
                }

                #region 记录日志

                var logDir = ServerUtility.ContentRootMapPath(string.Format("~/App_Data/TenPayNotify/{0}", SystemTime.Now.ToString("yyyyMMdd")));
                if (!Directory.Exists(logDir))
                {
                    Directory.CreateDirectory(logDir);
                }

                var logPath = Path.Combine(logDir, string.Format("{0}-{1}-{2}.txt", SystemTime.Now.ToString("yyyyMMdd"), SystemTime.Now.ToString("HHmmss"), Guid.NewGuid().ToString("n").Substring(0, 8)));

                using (var fileStream = System.IO.File.OpenWrite(logPath))
                {
                    var notifyXml = resHandler.ParseXML();
                    //fileStream.Write(Encoding.Default.GetBytes(res), 0, Encoding.Default.GetByteCount(res));

                    fileStream.Write(Encoding.Default.GetBytes(notifyXml), 0, Encoding.Default.GetByteCount(notifyXml));
                    fileStream.Close();
                }

                #endregion


                string xml = string.Format(@"<xml>
<return_code><![CDATA[{0}]]></return_code>
<return_msg><![CDATA[{1}]]></return_msg>
</xml>", return_code, return_msg);
                return(Content(xml, "text/xml"));
            }
            catch (Exception ex)
            {
                WeixinTrace.WeixinExceptionLog(new WeixinException(ex.Message, ex));
                throw;
            }
        }
Esempio n. 4
0
        /// <summary>
        /// JS-SDK支付回调地址(在下单接口中设置的 notify_url)
        /// </summary>
        /// <returns></returns>
        public async Task <IActionResult> PayNotifyUrl()
        {
            try
            {
                //获取微信服务器异步发送的支付通知信息
                var resHandler      = new TenPayNotifyHandler(HttpContext);
                var orderReturnJson = await resHandler.AesGcmDecryptGetObjectAsync <OrderReturnJson>();

                //记录日志
                Senparc.Weixin.WeixinTrace.SendCustomLog("PayNotifyUrl 接收到消息", orderReturnJson.ToJson(true));

                //演示记录 transaction_id,实际开发中需要记录到数据库,以便退款和后续跟踪
                TradeNumberToTransactionId[orderReturnJson.out_trade_no] = orderReturnJson.transaction_id;

                //获取支付状态
                string trade_state = orderReturnJson.trade_state;

                //验证请求是否从微信发过来(安全)
                NotifyReturnData returnData = new();

                //验证可靠的支付状态
                if (orderReturnJson.VerifySignSuccess == true && trade_state == "SUCCESS")
                {
                    returnData.code = "SUCCESS";//正确的订单处理

                    /* 提示:
                     * 1、直到这里,才能认为交易真正成功了,可以进行数据库操作,但是别忘了返回规定格式的消息!
                     * 2、上述判断已经具有比较高的安全性以外,还可以对访问 IP 进行判断进一步加强安全性。
                     * 3、下面演示的是发送支付成功的模板消息提示,非必须。
                     */

                    #region 发送支付成功模板消息提醒
                    try
                    {
                        string appId        = Config.SenparcWeixinSetting.TenPayV3_AppId;//与微信公众账号后台的AppId设置保持一致,区分大小写。
                        string openId       = orderReturnJson.payer.openid;
                        var    templateData = new WeixinTemplate_PaySuccess("https://weixin.senparc.com", "微信支付 V3 购买商品", "状态:" + trade_state);

                        Senparc.Weixin.WeixinTrace.SendCustomLog("TenPayV3 支付成功模板消息参数", "AppId:" + appId + " ,openId: " + openId);

                        var result = await MP.AdvancedAPIs.TemplateApi.SendTemplateMessageAsync(appId, openId, templateData);
                    }
                    catch (Exception ex)
                    {
                        Senparc.Weixin.WeixinTrace.SendCustomLog("TenPayV3 支付成功模板消息", ex.ToString());
                    }
                    #endregion
                }
                else
                {
                    returnData.code    = "FAILD";//错误的订单处理
                    returnData.message = "验证失败";

                    //此处可以给用户发送支付失败提示等
                }

                #region 记录日志(也可以记录到数据库审计日志中)

                var logDir = ServerUtility.ContentRootMapPath(string.Format("~/App_Data/TenPayNotify/{0}", SystemTime.Now.ToString("yyyyMMdd")));
                if (!Directory.Exists(logDir))
                {
                    Directory.CreateDirectory(logDir);
                }

                var logPath = Path.Combine(logDir, string.Format("{0}-{1}-{2}.txt", SystemTime.Now.ToString("yyyyMMdd"), SystemTime.Now.ToString("HHmmss"), Guid.NewGuid().ToString("n").Substring(0, 8)));

                using (var fileStream = System.IO.File.OpenWrite(logPath))
                {
                    var notifyJson = orderReturnJson.ToString();
                    await fileStream.WriteAsync(Encoding.Default.GetBytes(notifyJson), 0, Encoding.Default.GetByteCount(notifyJson));

                    fileStream.Close();
                }
                #endregion

                //https://pay.weixin.qq.com/wiki/doc/apiv3/apis/chapter3_1_5.shtml
                return(Json(returnData));
            }
            catch (Exception ex)
            {
                WeixinTrace.WeixinExceptionLog(new WeixinException(ex.Message, ex));
                throw;
            }
        }
Esempio n. 5
0
        /// <summary>
        /// JS-SDK支付回调地址(在统一下单接口中设置notify_url)
        /// </summary>
        /// <returns></returns>
        public ActionResult PayNotifyUrl(bool isWxOpenPay = false)//注意:统一下单接口中不能带参数!
        {
            WeixinTrace.SendCustomLog("微信支付回调", "来源:" + (isWxOpenPay ? "微信支付" : "小程序支付"));

            try
            {
                ResponseHandler resHandler = new ResponseHandler(null);

                string return_code = resHandler.GetParameter("return_code");
                string return_msg  = resHandler.GetParameter("return_msg");

                bool paySuccess = false;

                resHandler.SetKey(TenPayV3Info.Key);
                //验证请求是否从微信发过来(安全)
                if (resHandler.IsTenpaySign() && return_code.ToUpper() == "SUCCESS")
                {
                    paySuccess = true;//正确的订单处理
                    //直到这里,才能认为交易真正成功了,可以进行数据库操作,但是别忘了返回规定格式的消息!
                }
                else
                {
                    paySuccess = false;//错误的订单处理
                }

                if (paySuccess)
                {
                    /* 这里可以进行订单处理的逻辑 */

                    //发送支付成功的模板消息
                    try
                    {
                        string appId  = Config.SenparcWeixinSetting.WeixinAppId;//与微信公众账号后台的AppId设置保持一致,区分大小写。
                        string openId = resHandler.GetParameter("openid");

                        if (isWxOpenPay)
                        {
                            //DPBMARK MiniProgram
                            var cacheStrategy           = CacheStrategyFactory.GetObjectCacheStrategyInstance();
                            var unifiedorderRequestData = cacheStrategy.Get <TenPayV3UnifiedorderRequestData>($"WxOpenUnifiedorderRequestData-{openId}"); //获取订单请求信息缓存
                            var unifedorderResult       = cacheStrategy.Get <UnifiedorderResult>($"WxOpenUnifiedorderResultData-{openId}");               //获取订单信息缓存

                            if (unifedorderResult != null || !string.IsNullOrEmpty(unifedorderResult.prepay_id))
                            {
                                Senparc.Weixin.WeixinTrace.SendCustomLog("支付成功模板消息参数(小程序)", appId + " , " + openId);

                                //小程序支付,发送小程序模板消息
                                var templateData = new WxOpenTemplateMessage_PaySuccessNotice(
                                    "在线购买(小程序支付)测试", SystemTime.Now, "小程序支付 | 注意:这条消息来自微信服务器异步回调,官方证明支付成功! | prepay_id:" + unifedorderResult.prepay_id,
                                    unifiedorderRequestData.OutTradeNo, unifiedorderRequestData.TotalFee, "400-031-8816", "https://weixin.senparc.com");

                                //微信官方已停用此接口
                                //Senparc.Weixin.WxOpen.AdvancedAPIs
                                //    .Template.TemplateApi
                                //    .SendTemplateMessage(
                                //        Config.SenparcWeixinSetting.WxOpenAppId, openId, templateData.TemplateId, templateData, unifedorderResult.prepay_id, "pages/index/index", "图书", "#fff00");
                            }
                            else
                            {
                                Senparc.Weixin.WeixinTrace.SendCustomLog("支付成功模板消息参数(小程序)", "prepayId未记录:" + appId + " , " + openId);
                            }
                            //DPBMARK_END
                        }
                        else
                        {
                            //微信公众号支付
                            var templateData = new WeixinTemplate_PaySuccess("https://weixin.senparc.com", "购买商品", "状态:" + return_code);

                            Senparc.Weixin.WeixinTrace.SendCustomLog("支付成功模板消息参数(公众号)", appId + " , " + openId);

                            var result = AdvancedAPIs.TemplateApi.SendTemplateMessage(appId, openId, templateData);
                        }
                    }
                    catch (Exception ex)
                    {
                        WeixinTrace.WeixinExceptionLog(new WeixinException("支付成功模板消息异常", ex));
                        //WeixinTrace.SendCustomLog("支付成功模板消息", ex.ToString());
                    }

                    WeixinTrace.SendCustomLog("PayNotifyUrl回调", "支付成功");
                }
                else
                {
                    Senparc.Weixin.WeixinTrace.SendCustomLog("PayNotifyUrl回调", "支付失败");
                }



                #region 记录日志

                var logDir = ServerUtility.ContentRootMapPath(string.Format("~/App_Data/TenPayNotify/{0}", SystemTime.Now.ToString("yyyyMMdd")));
                if (!Directory.Exists(logDir))
                {
                    Directory.CreateDirectory(logDir);
                }

                var logPath = Path.Combine(logDir, string.Format("{0}-{1}-{2}.txt", SystemTime.Now.ToString("yyyyMMdd"), SystemTime.Now.ToString("HHmmss"), Guid.NewGuid().ToString("n").Substring(0, 8)));

                using (var fileStream = System.IO.File.OpenWrite(logPath))
                {
                    var notifyXml = resHandler.ParseXML();
                    //fileStream.Write(Encoding.Default.GetBytes(res), 0, Encoding.Default.GetByteCount(res));

                    fileStream.Write(Encoding.Default.GetBytes(notifyXml), 0, Encoding.Default.GetByteCount(notifyXml));
                    fileStream.Close();
                }

                #endregion


                string xml = string.Format(@"<xml>
<return_code><![CDATA[{0}]]></return_code>
<return_msg><![CDATA[{1}]]></return_msg>
</xml>", return_code, return_msg);
                return(Content(xml, "text/xml"));
            }
            catch (Exception ex)
            {
                WeixinTrace.WeixinExceptionLog(new WeixinException(ex.Message, ex));
                throw;
            }
        }
Esempio n. 6
0
        /// <summary>
        /// JS-SDK支付回调地址(在统一下单接口中设置notify_url)
        /// </summary>
        /// <returns></returns>
        public async Task <ActionResult> PayNotifyUrl(Guid id)
        {
            try
            {
                ResponseHandler resHandler = new ResponseHandler(HttpContext);

                string return_code = resHandler.GetParameter("return_code");
                string return_msg  = resHandler.GetParameter("return_msg");
                resHandler.SetKey(TenPayV3Info.Key);
                bool succeed = resHandler.IsTenpaySign() && return_code.ToUpper() == "SUCCESS";

                /* 这里可以进行订单处理的逻辑 */
                string out_trade_no = resHandler.GetParameter("out_trade_no");
                var    pay          = _paySrv.UpdatePaymentResult(GuidEncoder.Decode(out_trade_no), succeed);
                if (succeed)
                {
                    var result = await ExecuteOrder((Guid)pay.OrderId, pay.Id, true);
                }

                //发送支付成功的模板消息
                try
                {
                    string appId        = Config.SenparcWeixinSetting.TenPayV3_AppId;//与微信公众账号后台的AppId设置保持一致,区分大小写。
                    string openId       = resHandler.GetParameter("openid");
                    var    templateData = new WeixinTemplate_PaySuccess(_siteUrl, "购买商品", "状态:" + return_code);

                    Senparc.Weixin.WeixinTrace.SendCustomLog("支付成功模板消息参数", appId + " , " + openId);

                    // var result = Senparc.Weixin.MP.AdvancedAPIs.TemplateApi.SendTemplateMessage(appId, openId, templateData);
                }
                catch (Exception ex)
                {
                    Senparc.Weixin.WeixinTrace.SendCustomLog("支付成功模板消息", ex.ToString());
                }

                #region 记录日志

                var logDir = ServerUtility.ContentRootMapPath(string.Format("~/App_Data/TenPayNotify/{0}", SystemTime.Now.ToString("yyyyMMdd")));
                if (!Directory.Exists(logDir))
                {
                    Directory.CreateDirectory(logDir);
                }

                var logPath = Path.Combine(logDir, string.Format("{0}-{1}-{2}.txt", SystemTime.Now.ToString("yyyyMMdd"), SystemTime.Now.ToString("HHmmss"), Guid.NewGuid().ToString("n").Substring(0, 8)));

                using (var fileStream = System.IO.File.OpenWrite(logPath))
                {
                    var notifyXml = resHandler.ParseXML();
                    //fileStream.Write(Encoding.Default.GetBytes(res), 0, Encoding.Default.GetByteCount(res));

                    fileStream.Write(Encoding.Default.GetBytes(notifyXml), 0, Encoding.Default.GetByteCount(notifyXml));
                    fileStream.Close();
                }

                #endregion


                string xml = string.Format(@"<xml>
<return_code><![CDATA[{0}]]></return_code>
<return_msg><![CDATA[{1}]]></return_msg>
</xml>", return_code, return_msg);
                return(Content(xml, "text/xml"));
            }
            catch (Exception ex)
            {
                WeixinTrace.WeixinExceptionLog(new WeixinException(ex.Message, ex));
                throw;
            }
        }
 private Task <SendTemplateMessageResult> Send(WeixinTemplate_PaySuccess templateData, string t) => TemplateApi.SendTemplateMessageAsync(WeixinSetting.WeixinAppId, t, templateData);
Esempio n. 8
0
        IActionResult PayNotifyUrl_Ex(bool isWxOpenPay)//注意:统一下单接口中不能带参数!
        {
            WeixinTrace.SendCustomLog("微信支付回调", "来源:" + (isWxOpenPay ? "微信支付" : "小程序支付"));

            try
            {
                ResponseHandler resHandler = new ResponseHandler(null);

                string return_code = resHandler.GetParameter("return_code");
                string return_msg  = resHandler.GetParameter("return_msg");

                bool paySuccess = false;

                resHandler.SetKey(TenPayV3Info.Key);
                //验证请求是否从微信发过来(安全)
                if (resHandler.IsTenpaySign() && return_code.ToUpper() == "SUCCESS")
                {
                    string out_trade_no   = resHandler.GetParameter("out_trade_no");
                    string openid         = resHandler.GetParameter("openid");
                    string total_fee      = resHandler.GetParameter("total_fee");
                    string transaction_id = resHandler.GetParameter("transaction_id");
                    string end_time       = resHandler.GetParameter("time_end");
                    try
                    {
                        var order = _context.Order.FirstOrDefault(od => od.OrderID == out_trade_no);
                        if (order != null)
                        {
                            if (order.OrderStatus == TradeState.NOTPAY || order.OrderStatus == TradeState.USERPAYING)
                            {
                                order.TransactionId = transaction_id;
                                order.ActPay        = decimal.Parse(total_fee);
                                order.OrderStatus   = TradeState.SUCCESS;
                                order.PayType       = "WeiXin";
                                order.OpenID        = openid;
                                if (DateTime.TryParseExact(end_time, "yyyyMMddHHmmss", null, System.Globalization.DateTimeStyles.None, out DateTime paydatetime_))
                                {
                                    order.PayDateTime = paydatetime_;
                                }
                                else
                                {
                                    order.PayDateTime = DateTime.Now;
                                }
                                _context.Order.Update(order);
                                _context.SaveChanges();
                                paySuccess = true;//正确的订单处理
                            }
                            else
                            {
                                return_code = "SUCCESS";
                                return_msg  = "订单已支付";
                                paySuccess  = true;
                            }
                        }
                        else
                        {
                            return_code = "FAIL";
                            return_msg  = "订单不存在";
                            paySuccess  = false;
                        }
                    }
                    catch (Exception ex)
                    {
                        return_code = "FAIL";
                        return_msg  = "服务器异常";
                        paySuccess  = false;
                        _logger.LogError(ex, "数据无法保存" + ex.Message);
                    }
                }
                else
                {
                    paySuccess = false;//错误的订单处理
                }
                if (paySuccess)
                {
                    /* 这里可以进行订单处理的逻辑 */

                    //发送支付成功的模板消息
                    try
                    {
                        string appId  = Config.SenparcWeixinSetting.WeixinAppId;//与微信公众账号后台的AppId设置保持一致,区分大小写。
                        string openId = resHandler.GetParameter("openid");

                        if (isWxOpenPay)
                        {
                            var cacheStrategy           = CacheStrategyFactory.GetObjectCacheStrategyInstance();
                            var unifiedorderRequestData = cacheStrategy.Get <TenPayV3UnifiedorderRequestData>($"WxOpenUnifiedorderRequestData-{openId}"); //获取订单请求信息缓存
                            var unifedorderResult       = cacheStrategy.Get <UnifiedorderResult>($"WxOpenUnifiedorderResultData-{openId}");               //获取订单信息缓存

                            if (unifedorderResult != null || !string.IsNullOrEmpty(unifedorderResult.prepay_id))
                            {
                                Senparc.Weixin.WeixinTrace.SendCustomLog("支付成功模板消息参数(小程序)", appId + " , " + openId);

                                //小程序支付,发送小程序模板消息
                                var templateData = new WxOpenTemplateMessage_PaySuccessNotice(
                                    "在线购买(小程序支付)测试", DateTime.Now, "小程序支付 | 注意:这条消息来自微信服务器异步回调,官方证明支付成功! | prepay_id:" + unifedorderResult.prepay_id,
                                    unifiedorderRequestData.OutTradeNo, unifiedorderRequestData.TotalFee, "400-031-8816", "https://weixin.senparc.com");

                                Senparc.Weixin.WxOpen.AdvancedAPIs
                                .Template.TemplateApi
                                .SendTemplateMessage(
                                    Config.SenparcWeixinSetting.WxOpenAppId, openId, templateData.TemplateId, templateData, unifedorderResult.prepay_id, "pages/index/index", "图书", "#fff00");
                            }
                            else
                            {
                                Senparc.Weixin.WeixinTrace.SendCustomLog("支付成功模板消息参数(小程序)", "prepayId未记录:" + appId + " , " + openId);
                            }
                        }
                        else
                        {
                            //微信公众号支付
                            var templateData = new WeixinTemplate_PaySuccess("https://weixin.senparc.com", "购买商品", "状态:" + return_code);
                            Senparc.Weixin.WeixinTrace.SendCustomLog("支付成功模板消息参数(公众号)", appId + " , " + openId);
                            var result = Senparc.Weixin.MP.AdvancedAPIs.TemplateApi.SendTemplateMessage(appId, openId, templateData);
                        }
                    }
                    catch (Exception ex)
                    {
                        WeixinTrace.WeixinExceptionLog(new WeixinException("支付成功模板消息异常", ex));
                        //WeixinTrace.SendCustomLog("支付成功模板消息", ex.ToString());
                    }

                    WeixinTrace.SendCustomLog("PayNotifyUrl回调", "支付成功");
                }
                else
                {
                    Senparc.Weixin.WeixinTrace.SendCustomLog("PayNotifyUrl回调", "支付失败");
                }
                string xml = string.Format(@"<xml>
<return_code><![CDATA[{0}]]></return_code>
<return_msg><![CDATA[{1}]]></return_msg>
</xml>", return_code, return_msg);

                return(Content(xml, "text/xml"));
            }
            catch (Exception ex)
            {
                WeixinTrace.WeixinExceptionLog(new WeixinException(ex.Message, ex));
                throw;
            }
        }