Ошибка в намерениях подписки Stripe в течение 3 дней
У меня проблема с интеграцией подписки Stripe в flutter (серверная часть - Django)
Внутри Views.py У меня есть
class CreateSubscriptionIntentView(APIView):
permission_classes = [IsAuthenticated]
def post(self, request):
try:
stripe.api_key = settings.STRIPE_SECRET_KEY
price_id = request.data.get('priceId')
if not price_id:
return Response({'error': 'priceId is required'}, status=400)
# Get or create user profile
profile = request.user.profile
# Create customer if missing
if not profile.stripe_customer_id:
customer = stripe.Customer.create(
email=request.user.email,
metadata={'django_user_id': request.user.id}
)
profile.stripe_customer_id = customer.id
profile.save()
# Create subscription with retry logic
subscription = None
invoice = None
payment_intent = None
for _ in range(3): # Retry up to 3 times
try:
# 1. Create subscription
subscription = stripe.Subscription.create(
customer=profile.stripe_customer_id,
items=[{'price': price_id}],
payment_behavior='default_incomplete',
payment_settings={
'payment_method_types': ['card'],
'save_default_payment_method': 'on_subscription'
}
)
# 2. Retrieve invoice with expansion
invoice = stripe.Invoice.retrieve(
subscription.latest_invoice,
expand=['payment_intent']
)
if invoice.payment_intent:
payment_intent = invoice.payment_intent
break
except stripe.error.StripeError:
time.sleep(1) # Wait 1 second before retry
continue
if not payment_intent:
return Response({'error': 'Payment intent not available after creation'}, status=500)
# Save subscription ID
profile.stripe_subscription_id = subscription.id
profile.save()
return Response({
'clientSecret': payment_intent.client_secret,
'subscriptionId': subscription.id
})
except Exception as e:
return Response({'error': str(e)}, status=500)
Внутри страницы Flutter, которая называется final_payment_screen.dart у меня есть
Future<void> _initSheet() async {
setState(() {
_loading = true;
_error = null;
});
try {
// Pick your price IDs
final priceId = widget.selectedPlan == 'Pro'
? (widget.isYearly
? 'price_1RG54vKBrgQdk6FTt7pw84SK'
: 'price_1RG54vKBrgQdk6FTmXfd1ohY')
: (widget.isYearly
? 'price_1RG58PKBrgQdk6FTQ8vBYbvY'
: 'price_1RG58PKBrgQdk6FT1cPfGxI9');
// Call backend
_clientSecret = await _svc.createSubscriptionIntent(priceId);
// Init the native Payment Sheet
await Stripe.instance.initPaymentSheet(
paymentSheetParameters: SetupPaymentSheetParameters(
paymentIntentClientSecret: _clientSecret,
merchantDisplayName: 'RedShield Inc.',
// Supply ApplePay / GooglePay configs (not just bools):
applePay: PaymentSheetApplePay(
merchantCountryCode: 'US',
),
googlePay: PaymentSheetGooglePay(
merchantCountryCode: 'US',
testEnv: true, // false in prod
),
style: ThemeMode.system,
),
);
setState(() => _loading = false);
} catch (e) {
setState(() {
_error = e.toString();
_loading = false;
});
}
}
Future<void> _presentPaymentSheet() async {
if (_processing) return;
setState(() => _processing = true);
try {
await Stripe.instance.presentPaymentSheet();
StatusBanner.showSuccess(context, 'Subscription successful!');
Navigator.pop(context, true);
} on StripeException catch (e) {
StatusBanner.showError(
context,
e.error.localizedMessage ?? 'Payment cancelled',
);
} catch (e) {
StatusBanner.showError(context, e.toString());
} finally {
setState(() => _processing = false);
}
}
внутри событий Stripe я вижу payment_intent.created, invoice.created, счет-фактуру.завершено и customer.subscription.created, но django возвращает ошибку
Внутренняя ошибка сервера: /api/stripe/create-subscription-intent/ [22/Apr/2025 18:50:41] "ОПУБЛИКОВАТЬ /api/stripe/создать-подписку-намерение/ HTTP/1.1" 500 55
Я настроил способы оплаты в Stripe, идентификаторы цен и так далее.
Кстати, я работаю в тестовом режиме Stripe.
я попробовал подождать Stripe несколько секунд, как предлагали некоторые Limbs (так что, возможно, для этого потребуется некоторое время, например, 1 секунда или что-то в этом роде)
я также попробовал настроить прямую оплату, и это работает без каких-либо проблем, мне просто нужна подписка