支付宝支付

环境:.NetCore、AlipaySDKNet.Standard

  //支付宝支付
  "AliPay": {
    "AliAppId": "",
    "GateWay": "https://openapi-sandbox.dl.alipaydev.com/gateway.do",
    //私钥
    "RSAPrivateKey": "",
    //支付公钥
    "AliPayRSAPublicKey": "",
    //异步通知地址,用于接收支付宝推送给商户的支付/退款成功的消息,仅支持http/https,公网可访问
    "NotifyUrl": "/api/order/main/ali-pay-notify",
    //支付成功后点击完成会自动跳转回商家页面地址,仅支持http/https,公网可访问
    "ReturnUrl": "/#/paymentSuccess"
  },
 1  /// <summary>
 2  /// 支付
 3  /// </summary>
 4  /// <returns></returns>
 5  [AllowAnonymous]
 6  [HttpPost]
 7  [Route("pay")]
 8  public async Task<string> PayOrderAsync(CreateOrderDto input)
 9  {
10      //订单是否超时、是否超出报名人数验证
11      bool overtime = await _orderAppService.CheckOrderOvertime(input.OrderNo, input.ProductId);
12 
13      var config = _aliPayConfigOptions.Value;
14      var client = new DefaultAopClient(config);
15 
16      AlipayTradeWapPayRequest request = new AlipayTradeWapPayRequest();
17      var domain = _configuration.GetSection("Domain").Value;
18      request.SetNotifyUrl(domain + _configuration.GetSection("AliPay:NotifyUrl").Value);
19      request.SetReturnUrl(domain + _configuration.GetSection("AliPay:ReturnUrl").Value);
20 
21      AlipayTradeWapPayModel model = new AlipayTradeWapPayModel();
22      model.OutTradeNo = input.OrderNo;
23      model.TotalAmount = input.PayAmount.ToString();
24      model.Subject = input.ProductName;
25      request.SetBizModel(model);
26      _logger.LogInformation("支付宝支付请求参数:" + JsonConvert.SerializeObject(request));
27      AlipayTradeWapPayResponse response = client.pageExecute(request);
28      _logger.LogInformation("支付宝支付返回参数:" + JsonConvert.SerializeObject(response));
29      return response.Body;
30  }
31 
32  [AllowAnonymous]
33  [ApiExplorerSettings(IgnoreApi = true)]
34  [HttpPost]
35  [Route("ali-pay-notify")]
36  public async Task<IActionResult> AliPayNotify()
37  {
38      _logger.LogInformation("----------支付完成开始回调----------");
39      // 获取待签名字符串
40      var parameters = GetSignContent();
41      string alipayPublicKey = _configuration.GetSection("AliPay:AliPayRSAPublicKey").Value;
42      bool is_sign = AlipaySignature.RSACheckV1(parameters, alipayPublicKey, "utf-8", "RSA2", false);
43 
44      if (is_sign)
45      {
46          string trade_status = Request.Form["trade_status"];
47          if (trade_status == "TRADE_FINISHED" || trade_status == "TRADE_SUCCESS")
48          {
49              #region 回调
50              var response = new OrderPaymentResponseDto()
51              {
52                  out_trade_no = parameters["out_trade_no"],
53                  trade_no = parameters["trade_no"],
54                  gmt_create = parameters["gmt_create"] == null ? null : DateTime.Parse(parameters["gmt_create"]),
55                  gmt_payment = parameters["gmt_payment"] == null ? null : DateTime.Parse(parameters["gmt_payment"]),
56                  notify_time = DateTime.Parse(parameters["notify_time"]),
57                  notify_id = parameters["notify_id"],
58                  notify_type = parameters["notify_type"],
59                  app_id = parameters["app_id"],
60                  seller_id = parameters["seller_id"],
61                  //buyer_id = parameters["buyer_id"],
62                  receipt_amount = parameters["receipt_amount"] == null ? null : decimal.Parse(parameters["receipt_amount"]),
63                  trade_status = trade_status
64              };
65 
66              _logger.LogInformation($"支付完成回调:{JsonConvert.SerializeObject(response)}");
67              //更新订单状态
68              await _orderAppService.UpdateOrderAsync(response);
69              #endregion
70          }
71 
72          return Content("success");
73      }
74      else
75      {
76          //验签失败
77          _logger.LogInformation("验签失败:" + JsonConvert.SerializeObject(parameters));
78          return Content("fail");
79      }
80  }
81 
82  /// <summary>
83  /// 待签名字符串
84  /// </summary>
85  /// <returns></returns>
86  private Dictionary<string, string> GetSignContent()
87  {
88      // 获取支付宝异步通知返回参数
89      IEnumerable<string> parameterKeys = HttpContext.Request.Form.Keys;
90      _logger.LogInformation("异步通知返回参数:" + JsonConvert.SerializeObject(parameterKeys));
91      Dictionary<string, string> parameters = new Dictionary<string, string>();
92      foreach (string key in parameterKeys)
93      {
94          parameters.Add(key, HttpContext.Request.Form[key]);
95      }
96 
97      _logger.LogInformation("异步通知返回Key+Value:" + JsonConvert.SerializeObject(parameters));
98      return parameters;
99  }
View Code

 

posted @ 2024-02-19 11:23  智者见智  阅读(40)  评论(0编辑  收藏  举报