You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

求.NET MAUI集成Stripe实现Apple Pay支付的完整实现指南

.NET MAUI + Stripe Apple Pay 完整实现流程

1. 前置准备

  • Stripe与Apple开发者配置:
    • 登录Stripe Dashboard,在「支付方式」中启用Apple Pay,绑定你在Apple Developer账号中创建的Merchant ID
    • 在Apple Developer账号中,为你的MAUI App ID开启Apple Pay权限,并关联对应的Merchant ID
  • NuGet包安装:
    • 后端项目(如ASP.NET Core)安装Stripe.net
    • .NET MAUI项目安装Stripe.iOS(仅iOS平台会生效)
  • MAUI iOS项目配置:
    • 在项目的Capabilities中开启Apple Pay,选择已关联的Merchant ID
    • 在Info.plist中添加Merchant ID配置:
      <key>NSApplePayMerchantIdentifier</key>
      <string>你的Apple Merchant ID</string>
      

2. 后端核心实现(生成PaymentIntent)

Stripe要求支付意图必须由服务器端创建,避免客户端篡改支付参数。以下以ASP.NET Core为例:

  • 初始化Stripe密钥:
    // Program.cs
    StripeConfiguration.ApiKey = "你的Stripe Secret Key";
    
  • 创建生成PaymentIntent的接口:
    [ApiController]
    [Route("api/payments")]
    public class PaymentsController : ControllerBase
    {
        [HttpPost("create-intent")]
        public async Task<IActionResult> CreatePaymentIntent([FromBody] PaymentRequest request)
        {
            var options = new PaymentIntentCreateOptions
            {
                Amount = request.Amount, // 金额单位为分,例如100代表1美元
                Currency = request.Currency,
                PaymentMethodTypes = new List<string> { "apple_pay" },
                Metadata = new Dictionary<string, string>
                {
                    { "OrderId", request.OrderId }
                }
            };
    
            var service = new PaymentIntentService();
            var intent = await service.CreateAsync(options);
    
            return Ok(new { ClientSecret = intent.ClientSecret });
        }
    }
    
    public class PaymentRequest
    {
        public long Amount { get; set; }
        public string Currency { get; set; } = "usd";
        public string OrderId { get; set; }
    }
    

3. .NET MAUI iOS客户端实现

Apple Pay仅支持iOS平台,通过依赖服务隔离平台代码:

3.1 共享项目定义接口

public interface IApplePayProcessor
{
    Task HandleApplePayPayment(long amount, string orderId, string currency);
}

3.2 iOS平台实现

  • 初始化Stripe:在AppDelegate.cs的FinishedLaunching方法中添加:
    Stripe.StripeApi.SetDefaultPublishableKey("你的Stripe Publishable Key");
    
  • 实现依赖服务:
    [assembly: Dependency(typeof(ApplePayProcessor))]
    namespace YourApp.iOS.Services
    {
        public class ApplePayProcessor : IApplePayProcessor
        {
            private string _clientSecret;
    
            public async Task HandleApplePayPayment(long amount, string orderId, string currency)
            {
                // 1. 调用后端获取PaymentIntent的ClientSecret
                using var client = new HttpClient();
                var requestBody = new { Amount = amount, OrderId = orderId, Currency = currency };
                var json = JsonSerializer.Serialize(requestBody);
                var content = new StringContent(json, Encoding.UTF8, "application/json");
                var response = await client.PostAsync("你的后端接口地址/api/payments/create-intent", content);
                var responseData = await response.Content.ReadFromJsonAsync<dynamic>();
                _clientSecret = responseData.ClientSecret;
    
                // 2. 检查设备是否支持Apple Pay
                if (!Stripe.PKPaymentAuthorizationViewController.CanMakePayments)
                {
                    await App.Current.MainPage.DisplayAlert("提示", "当前设备不支持Apple Pay", "确定");
                    return;
                }
    
                // 3. 构建Apple Pay请求
                var paymentRequest = new Stripe.PKPaymentRequest
                {
                    MerchantIdentifier = "你的Apple Merchant ID",
                    CountryCode = "US", // 根据业务地区修改,如CN
                    CurrencyCode = currency.ToUpper(),
                    PaymentSummaryItems = new[]
                    {
                        new Stripe.PKPaymentSummaryItem("订单支付", new NSDecimalNumber(amount / 100.0m))
                    }
                };
    
                // 4. 创建并弹出支付授权界面
                var authVC = Stripe.STPPaymentAuthorizationViewController.PaymentAuthorizationViewControllerWithPaymentRequest(paymentRequest);
                authVC.Delegate = new ApplePayAuthDelegate(_clientSecret);
    
                var currentVC = UIApplication.SharedApplication.KeyWindow.RootViewController;
                currentVC.PresentViewController(authVC, true, null);
            }
        }
    
        // 支付授权回调处理
        public class ApplePayAuthDelegate : Stripe.STPPaymentAuthorizationViewControllerDelegate
        {
            private readonly string _clientSecret;
    
            public ApplePayAuthDelegate(string clientSecret) => _clientSecret = clientSecret;
    
            public override async void DidAuthorizePayment(Stripe.STPPaymentAuthorizationViewController controller, Stripe.PKPayment payment, Action<Stripe.STPPaymentAuthorizationResult> completion)
            {
                // 将Apple Pay支付信息转换为Stripe支付方式参数
                var paymentMethodParams = Stripe.STPPaymentMethodParams.PaymentMethodParamsWithApplePay(payment);
                var service = new Stripe.STPPaymentIntentService();
    
                // 确认PaymentIntent完成支付
                service.ConfirmPaymentIntentWithClientSecret(_clientSecret, paymentMethodParams, (intent, error) =>
                {
                    if (error != null)
                    {
                        completion(new Stripe.STPPaymentAuthorizationResult(Stripe.STPPaymentAuthorizationStatus.Failure, error.LocalizedDescription));
                        controller.DismissViewController(true, async () =>
                        {
                            await App.Current.MainPage.DisplayAlert("支付失败", error.LocalizedDescription, "确定");
                        });
                    }
                    else
                    {
                        completion(new Stripe.STPPaymentAuthorizationResult(Stripe.STPPaymentAuthorizationStatus.Success, null));
                        controller.DismissViewController(true, async () =>
                        {
                            await App.Current.MainPage.DisplayAlert("支付成功", "订单支付已完成", "确定");
                            // 此处可添加订单状态更新逻辑
                        });
                    }
                });
            }
    
            public override void DidFinish(Stripe.STPPaymentAuthorizationViewController controller)
            {
                controller.DismissViewController(true, null);
            }
        }
    }
    

3.3 共享页面调用

在MAUI的支付页面中,通过依赖服务触发支付:

private async void ApplePayBtn_Clicked(object sender, EventArgs e)
{
    var processor = DependencyService.Get<IApplePayProcessor>();
    if (processor != null)
    {
        // 示例:支付100分(1美元),订单ID为ORDER_001,货币为USD
        await processor.HandleApplePayPayment(100, "ORDER_001", "usd");
    }
    else
    {
        await DisplayAlert("提示", "当前平台不支持Apple Pay", "确定");
    }
}

4. 测试与验证

  • 使用Stripe测试密钥,在iOS模拟器或测试设备中添加Stripe提供的测试银行卡(如4242 4242 4242 4242)
  • 验证后端接口能正常返回ClientSecret,支付流程无报错
  • 监听Stripe Webhook事件(如payment_intent.succeeded),确保后端能正确接收支付成功通知,更新订单状态

关键注意事项

  • 所有涉及支付参数的操作必须在后端完成,禁止在客户端处理敏感数据
  • Apple Pay仅支持iOS 11+设备,且用户需绑定有效银行卡
  • 必须通过Stripe Webhook确认支付最终状态,避免依赖客户端回调导致的订单状态不一致

内容的提问来源于stack exchange,提问作者Seelam Mulinti Gurivi Reddy

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.19 18:24:49