1. Anuncie Aqui ! Entre em contato fdantas@4each.com.br

[Flutter] Add trail period in flutter stripe. When i added parameter traildays in...

Discussão em 'Mobile' iniciado por Stack, Outubro 9, 2024 às 09:42.

  1. Stack

    Stack Membro Participativo

    Add trial period in flutter stripe. When i added parameter trial days in createPaymentIntend than successfuly payment without stripe take card details Expectation is when i clicked to payment a payment sheet will open and take card details and save and enable subscription with trial period but amount can't be cut , amount will cut automatically after trial period end.

    Future<void> makePayment(String paymentAmount, int index, BuildContext context) async {
    final signupProvider = Provider.of<SignUpProvider>(context, listen: false);
    final sp = Provider.of<SettingsProvider>(context, listen: false);

    final currentUser = FirebaseAuth.instance.currentUser;
    print("==== make payment");
    if (currentUser == null) {
    throw Exception("User not logged in");
    }

    try {
    // Show loading indicator
    signupProvider.changeLoaderValue(true);

    // Fetch user info from Firebase
    var userModel = await getCurrentUserInfo();
    String? customerId = userModel!.stripeCustomerId;
    String? stripeSubscriptionId = userModel!.stripeCustomerId;
    sp.updatePreSubs(stripeSubscriptionId??"");
    // print("==== created");
    if (customerId == null || customerId.isEmpty) {
    // Create Stripe customer
    var createCustomerResponse = await StripeBackendService.createCustomer(
    userModel!.email,
    userModel.name,
    currentUser.uid,
    );

    if (createCustomerResponse.statusCode == 201) {
    var decodedResponse = json.decode(createCustomerResponse.body);
    customerId = decodedResponse['customerId'];
    await updateUserInFirebase(customerId);
    print("==== created");

    } else {
    signupProvider.changeLoaderValue(false);
    print("==== faild to create stripe customer");
    throw Exception("Failed to create Stripe customer");
    }
    }

    String? subscriptionId = userModel?.stripeSubscriptionId;
    // Await the subscription creation and check for a valid response
    Map<String, dynamic>? paymentIntent = await createSubscriptionIntent(
    sp.subscriptions[index]['priceId'],
    customerId!,
    );

    signupProvider.changeLoaderValue(false);
    print('=============== ${paymentIntent!.containsKey('client_secret')}');
    // Check if paymentIntent contains a valid client_secret
    if (paymentIntent == null || !paymentIntent.containsKey('client_secret')) {
    throw Exception("${AppLocale.paymentProcessFailed.getString(context)}");
    }

    // Initialize Payment Sheet
    var gpay = const PaymentSheetGooglePay(
    merchantCountryCode: "US",
    currencyCode: "EUR", // Use the correct currency code here
    testEnv: false,
    );

    await Stripe.instance.initPaymentSheet(
    paymentSheetParameters: SetupPaymentSheetParameters(
    customerId: customerId,
    paymentIntentClientSecret: paymentIntent['client_secret'],
    style: ThemeMode.dark,
    merchantDisplayName: 'Ivan Stefina',
    billingDetailsCollectionConfiguration: const BillingDetailsCollectionConfiguration(
    name: CollectionMode.always,
    phone: CollectionMode.always,
    email: CollectionMode.always,
    address: AddressCollectionMode.automatic,
    ),
    googlePay: gpay,
    ),
    );

    // Display the payment sheet to the user
    displayPaymentSheet(index, context);
    } catch (e) {
    signupProvider.changeLoaderValue(false);
    print('Error: $e');
    }
    }

    Future<void> displayPaymentSheet(int index, BuildContext context) async {
    final sp = Provider.of<SettingsProvider>(context, listen: false);
    final signupProvider = Provider.of<SignUpProvider>(context, listen: false);

    try {
    await Stripe.instance.presentPaymentSheet().then((value) async {

    await cancelSubscription(context);

    // Process successful payment here
    signupProvider.changeLoaderValue(true);

    sp.saveAndStoreUserSubscription(
    context,
    sp.subscriptions[index]['title'],
    double.parse(sp.subscriptions[index]['subscriptionCharges']),
    sp.subscriptions[index]['duration'],
    sp.subscriptions[index]['freeTrailDays'],
    );

    // await signupProvider.notifyAdmin(
    // FirebaseAuth.instance.currentUser!.uid,
    // "newSubscription",
    // "${AppLocale.newSubscription.getString(context)}",
    // "${AppLocale.newSubscriptionpurchased.getString(context)}",
    // );
    });

    signupProvider.changeLoaderValue(false);
    } catch (e) {
    signupProvider.changeLoaderValue(false);
    print('Payment Sheet Error: $e');
    }
    }

    // Correct return type should be Future<Map<String, dynamic>?>
    Future<Map<String, dynamic>?> createSubscriptionIntent(String priceId, String customerId) async {
    // Get current time in seconds since epoch
    int? trialEnd;
    int currentTime = DateTime.now().millisecondsSinceEpoch ~/ 1000;
    // Calculate trial end time
    trialEnd = currentTime + (2 * 24 * 60 * 60); // Convert days to seconds

    try {
    Map<String, dynamic> body = {
    'customer': customerId,
    'items[0][price]': priceId,
    // 'trial_end': trialEnd.toString(),
    'payment_behavior': 'default_incomplete',
    'expand[]': 'latest_invoice.payment_intent',
    };

    var response = await http.post(
    Uri.parse('https://api.stripe.com/v1/subscriptions'),
    headers: {
    'Authorization': 'Bearer $key', // Replace with your Stripe Secret Key
    'Content-Type': 'application/x-www-form-urlencoded',
    },
    body: body,
    );

    var jsonResponse = json.decode(response.body);
    print('Subscription Response: $jsonResponse');

    if (jsonResponse.containsKey('latest_invoice')) {
    var paymentIntent = jsonResponse['latest_invoice']['payment_intent'];
    if (paymentIntent != null && paymentIntent.containsKey('client_secret')) {
    print('Subscription Response: retrun ');

    return paymentIntent; // Return the payment intent as a Map
    } else {
    throw Exception("Invalid subscription response: missing payment intent");
    }
    } else {
    throw Exception("Invalid server response: missing invoice");
    }
    } catch (e) {
    print('Error creating subscription: $e');
    throw e;
    }
    }


    Add trial period in flutter stripe. Expectation is when i clicked to payment a payment sheet will open and take card details and save and enable subscription with trial period but amount can't be cut , amount will cut automatically after trial period end.

    Continue reading...

Compartilhe esta Página