在Capacitor应用中实施Stripe支付链接,遵守新Apple指南
自2025年5月1日起,苹果公司在苹果商店审查指南中实施了重大变化,这些变化是基于在Epic v. Apple案中做出的法院判决。 Epic v. Apple案.这些变化具体允许美国的应用开发者在数字商品和服务中链接到外部支付方法,从而为苹果公司的内购系统提供了替代方案。
改变移动支付的史诗级战斗
这一时刻的来临是漫长而充满争议的。它始于2020年8月,当时Epic Games,Fortnite的创造者,违反了苹果App Store的指南,通过在应用程序中直接实现支付选项,绕过苹果的30%佣金。苹果迅速从App Store中移除了Fortnite,Epic随后提起诉讼,挑战苹果对iOS应用程序分发和内购支付的控制。
经过多年的法律斗争、上诉和反诉,法院最终裁定苹果必须允许开发者将用户指向应用程序外的替代支付方法。这一决定彻底改变了App Store生态系统的经济模型,这一模型自2008年成立以来一直沿用不变。
最终裁决 - 无上诉权
这一裁决尤其重要,因为它是最终的,并且无法再上诉。最高法院在2025年初拒绝了苹果的上诉,确认了下级法院的决定为法律。这意味着开发者可以自信地实施外部支付方法,苹果无法通过进一步的法律挑战逆转这一决定。
法律保证平等的处理
最重要的是,裁决明确指出苹果不能歧视使用外部支付方法的应用程序。法院明确禁止苹果:
- 对使用外部支付方法的应用程序征收额外的费用或施加额外的要求
- 在搜索结果中给予使用苹果IAP系统的应用程序优惠待遇或特征
- 使用技术措施使外部支付体验不如苹果自己的系统
- 超出基本消费者信息的繁琐披露要求
这些明确的保护措施意味着开发者可以在不担心苹果的微妙报复或歧视的情况下实施Stripe或其他外部支付提供商。平衡场地已经被法律平等化,苹果必须无论开发者选择什么支付方法都对所有应用程序一视同仁。
本裁决代表了对苹果围栏式园艺方法的最重要挑战,也标志着移动应用程序盈利方式的转折点。对于长期抱怨苹果30%佣金(小企业降至15%)的开发者,这项裁决提供了更高利润率和更大控制力来管理客户体验的途径。
使用Stripe而不是苹果内购的财务好处
使用Stripe而不是苹果内购的财务好处
-
使用Stripe而不是苹果内购的财务好处苹果通常对内购征收30%的佣金(小企业15%),而Stripe的费用仅约为2.9% + $0.30每笔交易。这一差异可以显著增加您的收入利润率。
-
更快的付款在Apple中,通常需要45-90天才能收到资金。与此不同,Stripe会在2-3个工作日内将付款直接存入您的银行账户。
-
简化退款流程通过 Stripe 的控制台直接处理退款,而不是通过 Apple 的更复杂的退款系统。
这些成本节约和改善的现金流可以带来重大变化,尤其是对于较小的开发者和企业。
In this article, we’ll explore how to implement Stripe Payment Links in your Capacitor app to take advantage of these new rules, while ensuring compliance with Apple’s 更新指南.
基于此实现 Stripe 的官方支付链接文档,特别适用于 Capacitor 应用。
了解新指南
Capacitor 更新的App Store审查指南现在允许开发者将用户指向外部网站进行付款处理,特别是针对数字产品和订阅。这个变化目前仅适用于在美国App Store发布的应用。
了解的关键点:
- 您现在可以在应用程序中链接到数字商品的外部付款选项
- 此功能仅适用于美国App Store的应用程序
- 您仍然必须遵守苹果的披露要求
- 您仍然负责所有客户支持和退款处理
在Capacitor应用程序中设置Stripe付款链接
让我们深入到技术实现:
步骤1:在Stripe控制台中创建付款链接
首先,在您的Stripe控制台中创建一个付款链接
- 导航到Stripe控制台中的付款链接部分
- 点击“+新”创建一个新的付款链接
- 定义您的产品或订阅详细信息
- 在“付款后”设置中,选择“不显示确认页面”
- 设置一个通用链接作为您的成功 URL(我们稍后会配置此项)
- 点击“创建链接”以生成您的付款链接
步骤 2:在您的Capacitor应用中设置通用链接
为了将用户重定向回您的应用程序后付款完成,配置通用链接:
- 创建一个
apple-app-site-association文件在您的域名上:
{
"applinks": {
"apps": [],
"details": [
{
"appIDs": ["YOURTEAMID.com.yourdomain.yourapp"],
"components": [
{
"/": "/checkout_redirect*",
"comment": "Matches any URL whose path starts with /checkout_redirect"
}
]
}
]
}
}
-
将其托管在
https://yourdomain.com/.well-known/apple-app-site-association -
确保它以正确的 MIME 类型服务
application/json -
配置您的Capacitor应用程序处理通用链接,通过添加适当的特权。首先,在您的
capacitor.config.ts:
import { CapacitorConfig } from '@capacitor/cli';
const config: CapacitorConfig = {
// Your existing app configuration (appId, appName, etc.)
plugins: {
Geolocation: {
// Request precise location access on iOS
iosLocationAccuracy: 'reduced'
}
}
};
export default config;
- 添加 Associated Domains 特权到您的 Xcode 项目:
- 打开您的 Xcode 项目
- 选择您的应用程序目标
- 前往 “签名 & 权限”
- 点击 “+ 权限” 并选择 “关联域名”
- 添加
applinks:yourdomain.com
步骤 3:创建一个回退页面
创建一个回退页面来处理应用未安装的情况:
<!DOCTYPE html>
<html>
<head>
<title>Redirecting...</title>
<meta http-equiv="refresh" content="0;url=https://yourdomain.com/app-download">
</head>
<body>
<p>Redirecting to download page...</p>
</body>
</html>
步骤 4:在您的 Capacitor 应用中实现付款按钮
现在,添加付款按钮到您的应用中:
import { Capacitor } from '@capacitor/core';
export async function openPaymentLink(userEmail, userId) {
// Use your actual Stripe payment link
const baseUrl = 'https://buy.stripe.com/your_payment_link';
// Add URL parameters to customize the experience
const params = new URLSearchParams({
prefilled_email: encodeURIComponent(userEmail),
client_reference_id: userId
});
const fullUrl = `${baseUrl}?${params.toString()}`;
// Simple window.open works in both web and Capacitor
// Using _blank opens in Safari on iOS which is important for users with saved Stripe Link credentials
window.open(fullUrl, '_blank');
}
为什么 Safari 重要: 在 Safari(通过
window.open) 中打开付款链接,而不是在应用内浏览器中打开更有利,因为用户如果之前在 Stripe Link 中保存了付款信息,会自动获得凭证。这会创建一个更流畅的结账体验,用户不需要重新输入信用卡信息,显著降低了摩擦和放弃率。
步骤 5:在应用中处理 universal 链接
配置应用来处理用户被重定向回来的 universal 链接:
- 首先,安装 App 插件:
npm install @capacitor/app
- 在您的应用程序中注册 App 插件:
import { App } from '@capacitor/app';
// In your initialization code
App.addListener('appUrlOpen', (event) => {
// Example URL: https://yourdomain.com/checkout_redirect?session_id=cs_test_...
const url = new URL(event.url);
if (url.pathname.startsWith('/checkout_redirect')) {
// Extract any parameters you need
const params = new URLSearchParams(url.search);
const sessionId = params.get('session_id');
// Handle successful payment
if (sessionId) {
// Verify the payment on your server if needed
verifyPayment(sessionId);
// Update UI to reflect successful purchase
updatePurchaseStatus(true);
}
}
});
async function verifyPayment(sessionId) {
// Call your backend to verify the payment
// This is optional if you're relying on webhooks
}
function updatePurchaseStatus(success) {
// Update your app UI to reflect purchase status
}
第 6 步:为订单完成设置 Webhook
最后,配置一个 webhook 来处理成功的付款:
// Using Express.js as an example
const express = require('express');
const stripe = require('stripe')('sk_test_your_stripe_secret_key');
const app = express();
// Use raw body parser for webhook signature verification
app.post('/webhook', express.raw({type: 'application/json'}), async (req, res) => {
const sig = req.headers['stripe-signature'];
const webhookSecret = 'whsec_your_webhook_secret';
let event;
try {
event = stripe.webhooks.constructEvent(req.body, sig, webhookSecret);
} catch (err) {
console.log(`Webhook Error: ${err.message}`);
return res.status(400).send(`Webhook Error: ${err.message}`);
}
// Handle the checkout.session.completed event
if (event.type === 'checkout.session.completed') {
const session = event.data.object;
// Retrieve client_reference_id (your user ID)
const userId = session.client_reference_id;
// Grant access to the purchased content
await grantAccess(userId, session.id);
}
res.status(200).send();
});
async function grantAccess(userId, sessionId) {
// Your logic to grant access to the purchased content
// This could be updating a database, sending a notification, etc.
}
app.listen(3000, () => console.log('Webhook server running on port 3000'));
Android 兼容性
让我们明确一下:Epic v. Apple 案例已经彻底改变了移动支付的格局。它不仅直接影响 iOS 应用程序,而且也加强了 Android 开发者的地位,他们一直在使用外部支付方法。
Android 开发者现在可以完全信心地实现外部支付解决方案。 苹果案例的先例实际上为开发者在各个平台上使用外部支付方法提供了保护。这一法庭决定已经验证了许多 Android 开发者多年来一直在做的事情——提供低收费的替代支付选项。
Google Play 商店一直比苹果商店更宽容外部支付方法,现在法律先例已经确立,几乎没有风险在您的 Android 应用程序中实施 Stripe 或其他外部支付提供商。您可以放心地使用这些实现,知道您站在坚实的法律基础上。
我们为 iOS 提供的实现在 Android 设备上几乎相同。由于 Google Play 商店对外部支付方法没有苹果商店一样的限制,因此您可以使用相同的 Stripe 支付链接方法,无需特殊的披露对话框。
要处理深度链接(与 iOS universal 链接类似),您需要:
- 设置 App Links 在您的
AndroidManifest.xml来处理重定向 URL - 创建一个
.well-known/assetlinks.json文件在您的域名上,包含您的应用程序的详细信息 - 使用相同的
appUrlOpen监听逻辑来处理成功的付款
Capacitor 的美丽之处在于,一旦您实现了平台特定的配置,实际的付款流程 code 在两种平台上保持一致。
创建付款 UI
以下是一个 Vue 中的付款按钮组件的示例,您可以将其添加到您的 Capacitor 应用程序中:
<template>
<div class="payment-container">
<div class="pricing-card">
<h2 class="mb-4 text-xl font-bold">{{ product.name }}</h2>
<p class="mb-6 text-gray-600">{{ product.description }}</p>
<div class="mb-6 price-tag">
<span class="text-2xl font-bold">${{ product.price }}</span>
<span v-if="product.isSubscription" class="text-sm text-gray-500">/month</span>
</div>
<button
@click="handlePayment"
class="py-3 w-full font-medium text-white bg-indigo-600 rounded-lg transition-colors hover:bg-indigo-700"
>
Purchase Now
</button>
</div>
</div>
</template>
<script setup>
import { ref } from 'vue';
import { Dialog } from '@capacitor/dialog';
const props = defineProps({
product: {
type: Object,
required: true
},
userEmail: {
type: String,
default: ''
},
userId: {
type: String,
required: true
}
});
const isLoading = ref(false);
async function showExternalPaymentDisclosure() {
const { value } = await Dialog.confirm({
title: 'Leaving App for Payment',
message: 'You are about to leave this app to make a payment. Apple is not responsible for the privacy or security of payments that are not made through the App Store. All payment-related issues, including refunds, must be handled by our support team.',
okButtonTitle: 'Continue',
cancelButtonTitle: 'Cancel'
});
return value;
}
async function openPaymentLink() {
// Use your actual Stripe payment link
const baseUrl = 'https://buy.stripe.com/your_payment_link';
// Add URL parameters to customize the experience
const params = new URLSearchParams({
prefilled_email: encodeURIComponent(props.userEmail),
client_reference_id: props.userId
});
const fullUrl = `${baseUrl}?${params.toString()}`;
// Simple window.open works in both web and Capacitor
// Using _blank opens in Safari on iOS which is important for users with saved Stripe Link credentials
window.open(fullUrl, '_blank');
}
async function handlePayment() {
isLoading.value = true;
try {
// Only show the disclosure on iOS
if (window.Capacitor?.getPlatform() === 'ios') {
const userConfirmed = await showExternalPaymentDisclosure();
if (!userConfirmed) return;
}
await openPaymentLink();
} catch (error) {
console.error('Payment error:', error);
await Dialog.alert({
title: 'Payment Error',
message: 'There was an error initiating the payment. Please try again.'
});
} finally {
isLoading.value = false;
}
}
</script>
处理不同地区
由于新 Apple 指南仅适用于美国 App Store 的应用程序,您需要一个策略来检测用户地区并应用适当的付款方法。以下是一个更可靠的方法,使用 IP 地理位置:
import { Capacitor } from '@capacitor/core';
async function determinePaymentMethod() {
// Always use Stripe for Android
if (Capacitor.getPlatform() !== 'ios') {
return 'external';
}
try {
// Use a geolocation service to determine user's country
const response = await fetch('https://ipapi.co/json/');
const locationData = await response.json();
// Check if the user is in the United States
if (locationData.country_code === 'US') {
return 'external'; // Can use Stripe Payment Links
} else {
return 'iap'; // Must use In-App Purchases
}
} catch (error) {
console.error('Error detecting region:', error);
return 'iap'; // Default to IAP to be safe
}
}
export async function processPayment(product, userEmail, userId) {
const paymentMethod = await determinePaymentMethod();
if (paymentMethod === 'external') {
// Use Stripe Payment Links
await initiateExternalPayment(userEmail, userId);
} else {
// Use Apple's In-App Purchase
await initiateInAppPurchase(product.appleProductId);
}
}
该方法使用免费的 ipapi.co 基于用户 IP 地址来确定用户的国家。您也可以使用其他地理位置服务,如 MaxMind,或者在服务器端实现此检查以增加安全性。
注意:虽然这种方法有效,但请记住,IP 地理位置检测并不总是 100% 准确。对于 mission-critical 应用程序,考虑使用多种检测方法或允许用户手动选择区域。
更准确的位置检测方法:Capacitor 插件
为了更准确地检测位置,您可以使用 Capacitor 地理位置插件,结合 @capgo/capacitor-nativegeocoder 来确定用户的国家,精度更高:
- 首先,安装所需的插件:
npm install @capacitor/geolocation @capgo/capacitor-nativegeocoder
- 在您的 Capacitor 项目中配置插件。将以下内容添加到您的
capacitor.config.ts:
import { CapacitorConfig } from '@capacitor/cli';
const config: CapacitorConfig = {
// Your existing app configuration (appId, appName, etc.)
plugins: {
Geolocation: {
// Request precise location access on iOS
iosLocationAccuracy: 'reduced'
}
}
};
export default config;
- 实现基于位置的区域检测:
import { Capacitor } from '@capacitor/core';
import { Geolocation } from '@capacitor/geolocation';
import { NativeGeocoder } from '@capgo/capacitor-nativegeocoder';
async function isUserInUSA() {
try {
// Request permission first
const permissionStatus = await Geolocation.requestPermissions();
if (permissionStatus.location === 'granted') {
// Get current position
const position = await Geolocation.getCurrentPosition({
timeout: 10000,
enableHighAccuracy: false
});
// Use NativeGeocoder to reverse geocode the coordinates
const results = await NativeGeocoder.reverseGeocode({
latitude: position.coords.latitude,
longitude: position.coords.longitude,
useLocale: true,
maxResults: 1
});
if (results.addresses.length > 0) {
// Check if the user is in the USA
return results.addresses[0].countryCode === 'US';
}
}
// If we couldn't determine location or permission denied, fall back to IP detection
return await isUserInUSAByIP();
} catch (error) {
console.error('Error detecting location:', error);
// Fall back to IP detection on error
return await isUserInUSAByIP();
}
}
async function isUserInUSAByIP() {
try {
const response = await fetch('https://ipapi.co/json/');
const data = await response.json();
return data.country_code === 'US';
} catch (error) {
console.error('Error detecting IP location:', error);
return false; // Default to false to be safe
}
}
export async function determinePaymentMethod() {
// Always use Stripe for Android
if (Capacitor.getPlatform() !== 'ios') {
return 'external';
}
// Check if user is in the USA
const isUSA = await isUserInUSA();
return isUSA ? 'external' : 'iap';
}
export async function processPayment(product, userEmail, userId) {
const paymentMethod = await determinePaymentMethod();
if (paymentMethod === 'external') {
// Use Stripe Payment Links
await initiateExternalPayment(userEmail, userId);
} else {
// Use Apple's In-App Purchase
await initiateInAppPurchase(product.appleProductId);
}
}
此实现提供了更准确的方法来确定用户是否位于美国。它首先尝试使用设备的 GPS 和原生地理编码器来确定国家。如果失败(由于权限问题或其他错误),它会回退到基于 IP 的检测。
请记住,在您的 info.plist (iOS) 和 AndroidManifest.xml (Android) 文件中添加必要的权限:
For iOS (ios/App/App/Info.plist):
<key>NSLocationWhenInUseUsageDescription</key>
<string>We need your location to determine which payment method to use based on regional availability.</string>
For Android (android/app/src/main/AndroidManifest.xml):
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
使用这种方法可以准确地确定用户是否符合苹果新指南下的外部付款选项的资格。
Managing Subscriptions
使用 Stripe 进行付款的关键优势是可以提供和管理订阅。以下是如何在您的 Capacitor 应用中处理订阅管理的步骤:
1. 创建订阅管理页面
添加一个订阅管理页面到您的应用中,以显示用户的活跃订阅:
<template>
<div class="subscription-manager">
<div v-if="isLoading" class="loading-indicator">
Loading subscription data...
</div>
<div v-else-if="subscription" class="subscription-info">
<h2 class="mb-4 text-xl font-bold">Your Subscription</h2>
<div class="mb-6 plan-details">
<p><span class="font-medium">Plan:</span> {{ subscription.planName }}</p>
<p><span class="font-medium">Status:</span> {{ subscription.status }}</p>
<p><span class="font-medium">Renews:</span> {{ formatDate(subscription.currentPeriodEnd) }}</p>
</div>
<button
@click="manageSubscription"
class="py-3 w-full font-medium text-white bg-indigo-600 rounded-lg transition-colors hover:bg-indigo-700"
>
Manage Subscription
</button>
</div>
<div v-else class="no-subscription">
<p class="mb-4">You don't have an active subscription.</p>
<button
@click="goToPricingPage"
class="py-3 w-full font-medium text-white bg-indigo-600 rounded-lg transition-colors hover:bg-indigo-700"
>
View Plans
</button>
</div>
</div>
</template>
<script setup>
import { ref, onMounted } from 'vue';
import { getUserSubscription } from '../services/subscription';
const subscription = ref(null);
const isLoading = ref(true);
onMounted(async () => {
try {
const userData = await getUserSubscription();
subscription.value = userData.subscription;
} catch (error) {
console.error('Failed to load subscription:', error);
} finally {
isLoading.value = false;
}
});
function formatDate(timestamp) {
return new Date(timestamp * 1000).toLocaleDateString();
}
function manageSubscription() {
// Open Stripe Customer Portal
window.open(subscription.value.portalUrl, '_blank');
}
function goToPricingPage() {
// Navigate to pricing page
// router.push('/pricing');
}
</script>
2. 订阅管理客户端门户
Stripe 提供了一个客户端门户,允许用户管理他们的订阅。您可以从您的服务器创建一个指向此门户的链接:
// Server-side code (Node.js)
const stripe = require('stripe')('sk_your_stripe_secret_key');
async function createPortalSession(customerId) {
const session = await stripe.billingPortal.sessions.create({
customer: customerId,
return_url: 'https://yourdomain.com/account',
});
return session.url;
}
Ensuring App Store Compliance
为了确保您的实现符合苹果的指南:
- 包含适当的关于外部购买的披露
- 在 App 中实现一个提示用户离开应用的弹窗(苹果要求必须实现)
- 不要试图绕过苹果对应用内购买的佣金
- 清楚地告知用户苹果不负责交易
以下是实现所需的披露弹窗的示例
import { Dialog } from '@capacitor/dialog';
async function showExternalPaymentDisclosure() {
const { value } = await Dialog.confirm({
title: 'Leaving App for Payment',
message: 'You are about to leave this app to make a payment. Apple is not responsible for the privacy or security of payments that are not made through the App Store. All payment-related issues, including refunds, must be handled by our support team.',
okButtonTitle: 'Continue',
cancelButtonTitle: 'Cancel'
});
return value;
}
export async function initiateExternalPayment(userEmail, userId) {
const userConfirmed = await showExternalPaymentDisclosure();
if (userConfirmed) {
await openPaymentLink(userEmail, userId);
}
}
测试您的实现
要测试您的实现,请
- 在您的应用中点击支付按钮,应该显示披露并打开 Stripe 支付页面
- 使用 Stripe 测试卡完成测试支付
4242 4242 4242 4242 - 支付后,您应该通过 universal 链接返回您的应用
- 检查您的 webhook 是否接收到
checkout.session.completed事件
结论
使用外部付款选项为iOS应用提供数字商品的能力是一个重大变化,给开发者带来了更多的灵活性。虽然这个变化目前仅适用于美国App Store中的应用,但它为开发者提供了苹果内购系统的重要替代方案。
通过使用Stripe Payment Links和Capacitor,您可以快速实现流畅的支付体验,同时保持与苹果的指南的兼容性。对于美国以外的用户,苹果的内购系统仍然适用。 @capgo/native-purchases 实现了StoreKit和Google Play Billing的直接调用。这一方法还为您提供了Stripe强大的支付基础设施、更低的处理费率(3% vs 30%)以及更快的付款(几天而不是几个月)等优势,相比之下苹果的内购系统。
请记住,您需要直接处理所有客户支持和退款问题,因为这些交易发生在苹果的生态系统之外。
您是否在Capacitor应用中实现了Stripe Payment Links?请在下面的评论中分享您的经验!
常见问题
Q:这个方法是否符合苹果的指南?
A:是的,截至2025年5月1日,苹果允许将外部付款方法链接到数字商品和服务的应用程序,提供了所需的披露。
Q:使用外部付款方法时是否需要支付苹果的佣金?
A: 不,新规则的一个主要好处是,Apple系统外的支付处理不受他们的佣金.
Q: 我的公司需要在美国注册才能利用这些新规则?
A: 不,任何公司,无论来自世界的哪个地方,只要您的应用程序在美国App Store可用,用户在美国的位置在美国购买,您的公司不需要在美国注册。该规定适用于市场(美国App Store)和用户的位置,而不是您的公司的位置。这意味着来自欧洲、亚洲、南美洲或其他任何地方的开发者都可以为他们的美国客户实施Stripe支付链接.
Q: 如果一个美国以外的用户尝试使用外部支付选项?
A: 您应该实现区域检测(如文章中所示),只为美国用户提供外部支付选项。对于其他地区,您应该继续使用Apple的内购系统.
Q: 我可以用它来购买物理商品或在应用程序外部消耗的服务吗?
A: 是的,Apple一直允许外部支付方法用于物理商品和在应用程序外部消耗的服务(如出租车或食品配送).
Keep going from Stripe Payments in Capacitor: New Apple Guidelines
If you are using Stripe Payments in Capacitor: New Apple Guidelines to plan security and compliance, connect it with Encryption 为 __CAPGO_KEEP_0__ 加密的实现细节 合规 为 __CAPGO_KEEP_0__ 合规的实现细节 Capgo 安全扫描器 为 Capgo 安全扫描器的产品工作流 Capgo 安全 为 Capgo 安全的产品工作流,和 Capgo 信任中心 为 Capgo 信任中心的产品工作流