ASP.NET MVC 支付宝沙箱集成教程:实现支付功能

本教程将引导您在 ASP.NET MVC 项目中集成支付宝沙箱,并实现一个简单的支付功能。通过本教程,您将学会如何使用 Alipay SDK、配置 Web.config、创建支付请求、处理支付结果以及更新订单状态。

步骤:

  1. 创建支付宝沙箱账号并获取沙箱密钥

    在支付宝开发者平台创建沙箱账号,并获取 App ID、沙箱网关、RSA 私钥等信息。

  2. 在 ASP.NET MVC 项目中添加 Alipay SDK 引用

    在 Visual Studio 中打开 ASP.NET MVC 项目,右键选择'引用',点击'管理 NuGet 程序包',搜索'Alipay.AopSdk',安装 Alipay SDK。

  3. 在 Web.config 中添加支付宝配置信息

    在 Web.config 中添加如下配置信息:

    <configuration>
      <appSettings>
        <add key='AlipayAppId' value='沙箱 App ID' />
        <add key='AlipayGateway' value='https://openapi.alipaydev.com/gateway.do' />
        <add key='AlipayPublicKey' value='沙箱支付宝公钥' />
        <add key='AlipayPrivateKey' value='沙箱商户私钥' />
      </appSettings>
    </configuration>
    
  4. 在 Controller 中编写 Action,调用 Alipay SDK 提供的 API 进行支付操作

    using Aop.Api;
    using Aop.Api.Request;
    using Aop.Api.Response;
    
    public class PaymentController : Controller
    {
        [HttpPost]
        public ActionResult Pay(string orderId, decimal amount)
        {
            // 获取配置信息
            var appId = ConfigurationManager.AppSettings['AlipayAppId'];
            var gateway = ConfigurationManager.AppSettings['AlipayGateway'];
            var privateKey = ConfigurationManager.AppSettings['AlipayPrivateKey'];
            var publicKey = ConfigurationManager.AppSettings['AlipayPublicKey'];
    
            // 创建 Alipay 客户端
            var client = new DefaultAopClient(gateway, appId, privateKey, 'json', '1.0', 'RSA2', publicKey, 'utf-8', false);
    
            // 创建支付请求
            var request = new AlipayTradePagePayRequest();
            request.SetReturnUrl('http://localhost:1234/Payment/ReturnUrl');
            request.SetNotifyUrl('http://localhost:1234/Payment/NotifyUrl');
    
            // 设置订单信息
            request.SetBizContent(JsonConvert.SerializeObject(new
            {
                out_trade_no = orderId,
                total_amount = amount.ToString('0.00'),
                subject = '订单支付',
                product_code = 'FAST_INSTANT_TRADE_PAY'
            }));
    
            // 调用支付接口
            var response = client.pageExecute(request);
    
            // 返回支付页面
            return Content(response.Body);
        }
    
        public ActionResult ReturnUrl()
        {
            // 处理支付结果
            var request = HttpContext.Request;
            var dict = new Dictionary<string, string>();
            foreach (var key in request.Form.AllKeys)
            {
                dict.Add(key, request.Form[key]);
            }
            var client = new DefaultAopClient(ConfigurationManager.AppSettings['AlipayGateway'], ConfigurationManager.AppSettings['AlipayAppId'], ConfigurationManager.AppSettings['AlipayPrivateKey'], 'json', '1.0', 'RSA2', ConfigurationManager.AppSettings['AlipayPublicKey'], 'utf-8', false);
            var response = client.Execute(new AlipayTradePagePayResponse(), dict);
            if (response.Code == '10000' && response.TradeStatus == 'TRADE_SUCCESS')
            {
                // 支付成功,更新订单状态
                return Content('支付成功');
            }
            else
            {
                // 支付失败,返回错误信息
                return Content(response.SubMsg);
            }
        }
    
        public ActionResult NotifyUrl()
        {
            // 处理支付结果
            var request = HttpContext.Request;
            var dict = new Dictionary<string, string>();
            foreach (var key in request.Form.AllKeys)
            {
                dict.Add(key, request.Form[key]);
            }
            var client = new DefaultAopClient(ConfigurationManager.AppSettings['AlipayGateway'], ConfigurationManager.AppSettings['AlipayAppId'], ConfigurationManager.AppSettings['AlipayPrivateKey'], 'json', '1.0', 'RSA2', ConfigurationManager.AppSettings['AlipayPublicKey'], 'utf-8', false);
            var response = client.Execute(new AlipayTradePagePayResponse(), dict);
            if (response.Code == '10000' && response.TradeStatus == 'TRADE_SUCCESS')
            {
                // 支付成功,更新订单状态
                return Content('success');
            }
            else
            {
                // 支付失败,返回错误信息
                return Content('fail');
            }
        }
    }
    
  5. 编写视图文件,显示支付按钮和订单信息

    @model OrderViewModel
    
    <h2>订单详情</h2>
    <p>订单号:@Model.OrderId</p>
    <p>订单金额:@Model.Amount</p>
    
    <form method='post' action='/Payment/Pay'>
        <input type='hidden' name='orderId' value='@Model.OrderId' />
        <input type='hidden' name='amount' value='@Model.Amount' />
        <button type='submit'>立即支付</button>
    </form>
    

总结

以上示例实现了一个简单的支付宝沙箱支付功能,用户可以在订单详情页面点击“立即支付”按钮,跳转到支付宝支付页面进行支付操作。支付成功后,用户会被重定向回网站,并显示支付成功或失败的提示信息。

注意:

  • 请将代码中的沙箱 App ID、沙箱网关、沙箱支付宝公钥和沙箱商户私钥替换为您的实际信息。
  • 本教程仅供学习参考,实际项目中可能需要根据具体情况进行调整。
  • 为了保障用户资金安全,请务必在正式环境中使用支付宝官方提供的正式接口和密钥。
ASP.NET MVC 支付宝沙箱集成教程:实现支付功能

原文地址: https://www.cveoy.top/t/topic/oYX6 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录