I am using flutter_stripe package to implement stripe pay in my app. PaymentSheet is being used for payment. I want to get the decline code or error message from the paymentSheet. I can get stripe exception when I cancel the payment like this.
StripeException(error: LocalizedErrorMessage(code: FailureCode.Canceled, localizedMessage: The payment has been canceled, message: The payment has been canceled, stripeErrorCode: null, declineCode: null, type: null))
I want to get the same result when the card is declined or doesn't have sufficient funds or any other issues. As you can see in the screenshot it displays "your card was declined". How can I catch this on code so I can get decline_code so that I can send it to the server?
My codes
Future<void> makePayment(
{String? clientSecret,
String? sessionId,
int? donationId,
Currency? currency}) async {
try {
var gpay = PaymentSheetGooglePay(
merchantCountryCode: currency!.code.substring(0, 2),
currencyCode: currency.code,
testEnv: true);
var apay = PaymentSheetApplePay(
merchantCountryCode: currency.code.substring(0, 2));
//STEP 2: Initialize Payment Sheet
await Stripe.instance.initPaymentSheet(
paymentSheetParameters: SetupPaymentSheetParameters(
billingDetailsCollectionConfiguration:
const BillingDetailsCollectionConfiguration(
address: AddressCollectionMode.never),
paymentIntentClientSecret: clientSecret, //Gotten from payment intent
merchantDisplayName: "Merchant",
googlePay: gpay,
applePay: apay,
));
displayPaymentSheet(sessionId: sessionId, donationId: donationId);
} catch (err) {
if (err is StripeException) {
// Handle canceled payment
log("${err.error.localizedMessage}");
// You can show a message to the user or navigate back to the previous screen
} else {
// Handle other errors
log('Error during payment: $err');
// You might want to show a generic error message or log the error for debugging
}
log("payment error $err");
}
}
displayPaymentSheet({String? sessionId, int? donationId}) async {
try {
await Stripe.instance.presentPaymentSheet().then((value) async {
try {} catch (e) {
log("error $e");
}
}).onError((error, stackTrace) {
throw Exception(error);
});
} on PlatformException catch (exception) {
log(exception.message ?? 'Something went wrong');
} catch (e) {
log("error $e");
if (e is StripeException) {
// Handle canceled payment
log("${e.error.localizedMessage}");
// You can show a message to the user or navigate back to the previous screen
} else {
// Handle other errors
log('Error during payment: $e');
// You might want to show a generic error message or log the error for debugging
}
log('payment error 2 $e');
}
}