flutter-stripe / flutter_stripe

Flutter SDK for Stripe.
https://pub.dev/packages/flutter_stripe
929 stars 514 forks source link

PlatformException(flutter_stripe initialization failed, The plugin failed to initialize. Are you using FlutterFragmentActivity? #166

Closed coder-Aayush closed 3 years ago

coder-Aayush commented 3 years ago

I am trying to set up a payment using this plugin but can't able to initialize it. I followed the setup instruction for android but facing this issue.

PlatformException(flutter_stripe initialization failed, The plugin failed to initialize. Are you using FlutterFragmentActivity?

Initialization

android/app/src/main/kotlin/com/example/myapp/MainActivity.kt

import io.flutter.embedding.android.FlutterActivity
import io.flutter.embedding.android.FlutterFragmentActivity
class MainActivity: FlutterFragmentActivity() {
}

build.gradle

ext.kotlin_version = '1.5.10'

 dependencies {
        classpath 'com.android.tools.build:gradle:4.1.1'
        classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
    }

Smartphone / tablet

Is there any other implementation that I have missed?

remonh87 commented 3 years ago

Do you get a stacktrace in the logcat output?

Maybe 2 other things to check:

coder-Aayush commented 3 years ago

@remonh87 I have migrated flutter version 2.2.2 and the issue still arises. here is the error

[ERROR:flutter/lib/ui/ui_dart_state.cc(199)] Unhandled Exception: PlatformException(flutter_stripe initialization failed, The plugin failed to initialize. Are you using FlutterFragmentActivity? Please check the README: https://github.com/flutter-stripe/flutter_stripe#android, null, null)
E/flutter (10831): #0      JSONMethodCodec.decodeEnvelope
package:flutter/…/services/message_codecs.dart:155
E/flutter (10831): #1      MethodChannel._invokeMethod
package:flutter/…/services/platform_channel.dart:158
E/flutter (10831): <asynchronous suspension>
E/flutter (10831): #2      MethodChannelStripe.initialise
package:stripe_platform_interface/src/method_channel_stripe.dart:39
E/flutter (10831): <asynchronous suspension>
E/flutter (10831): #3      Stripe._initialise
package:flutter_stripe/src/stripe.dart:316
E/flutter (10831): <asynchronous suspension>
E/flutter (10831): #4      Stripe.createPaymentMethod
package:flutter_stripe/src/stripe.dart:116
E/flutter (10831): <asynchronous suspension>
E/flutter (10831):
JoyEnergiser commented 3 years ago

I too have this issue.

jonasbark commented 3 years ago

Does this happen to you on the example app from this repository as well? Can you share a small project where this issue is reproducible?

JoyEnergiser commented 3 years ago

So when I created an app from scratch and plugged everything in as an example to show you it worked fine and created the transaction in the stripe log, sigh. So there is something within my main app that is causing this. Will continue investigating.

[√] Flutter (Channel stable, 2.2.2, on Microsoft Windows [Version 10.0.19043.1052], locale en-GB) • Flutter version 2.2.2 at C:\flutter • Framework revision d79295af24 (3 weeks ago), 2021-06-11 08:56:01 -0700 • Engine revision 91c9fc8fe0 • Dart version 2.13.3

[√] Android toolchain - develop for Android devices (Android SDK version 30.0.1) • Android SDK at C:\Users\joyen\AppData\Local\Android\Sdk • Platform android-30, build-tools 30.0.1 • ANDROID_HOME = C:\Users\joyen\AppData\Local\Android\Sdk • ANDROID_SDK_ROOT = C:\Users\joyen\AppData\Local\Android\Sdk • Java binary at: C:\Program Files\Android\Android Studio\jre\bin\java • Java version OpenJDK Runtime Environment (build 1.8.0_242-release-1644-b01) • All Android licenses accepted.

[√] Chrome - develop for the web • Chrome at C:\Program Files (x86)\Google\Chrome\Application\chrome.exe

[√] Android Studio (version 4.1.0) • Android Studio at C:\Program Files\Android\Android Studio • Flutter plugin can be installed from: https://plugins.jetbrains.com/plugin/9212-flutter • Dart plugin can be installed from: https://plugins.jetbrains.com/plugin/6351-dart • Java version OpenJDK Runtime Environment (build 1.8.0_242-release-1644-b01)

[√] VS Code (version 1.57.1) • VS Code at C:\Users\joyen\AppData\Local\Programs\Microsoft VS Code • Flutter extension version 3.23.0

[√] Connected device (3 available) • sdk gphone x86 (mobile) • emulator-5554 • android-x86 • Android 11 (API 30) (emulator) • Chrome (web) • chrome • web-javascript • Google Chrome 91.0.4472.124 • Edge (web) • edge • web-javascript • Microsoft Edge 91.0.864.59

• No issues found!

JoyEnergiser commented 3 years ago

I managed to reproduce the error If you change the src/main/AndroidManifest.xml

android:name=".MainActivity" (This is the default when you create a new project) to android:name="io.flutter.embedding.android.FlutterActivity" (this is how it is on my app that was created a while ago)

unfortunately it instantly crashes at runtime when i try to change my one to .MainActivity so no luck there

jonasbark commented 3 years ago

as the error states your MainActivity class must extend from FlutterFragmentActivity. In the github project link you shared it still extended from FlutterActivity.

JoyEnergiser commented 3 years ago

as the error states your MainActivity class must extend from FlutterFragmentActivity. In the github project link you shared it still extended from FlutterActivity.

Hi yea sorry I deleted that comment after I realised my mistake.That example worked when I changed that FlutterFragmentActivity

subhra9326 commented 3 years ago

Hi I am getting same error but I have changed that in FlutterFragmentActivity. Please see the bellow I have given everything what I have implemented.

Technology:

Flutter 2.2.2 SDK: ">=2.12.0 <3.0.0" - Null safety added. FireBase Function for API call. FireBase FireStore for Data store. flutter_stripe: ^1.0.2

Error, I faced : Exception has occurred. PlatformException (PlatformException(flutter_stripe initialization failed, The plugin failed to initialize. Are you using FlutterFragmentActivity? Please check the README: https://github.com/flutter-stripe/flutter_stripe#android, null, null))

So far I have already tried,

Changes done on MainActivity.kt File

package io.talkeng.app.global import io.flutter.embedding.android.FlutterActivity import io.flutter.embedding.android.FlutterFragmentActivity class MainActivity: FlutterFragmentActivity() { }

App level build.gradle

applicationId "io.talkeng.app.global" minSdkVersion 23 targetSdkVersion 30

Root level build.gradle

buildscript { ext.kotlin_version = '1.5.20' repositories { google() jcenter() } dependencies { classpath 'com.android.tools.build:gradle:4.1.0' classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version" classpath 'com.google.gms:google-services:4.3.4' } }

Android Manifest File:

<manifest xmlns:android="http://schemas.android.com/apk/res/android" package="io.talkeng.app.global" xmlns:tools="http://schemas.android.com/tools">

<uses-permission android:name="android.permission.INTERNET"/>
<uses-feature android:name="android.hardware.camera" />
<uses-feature android:name="android.software.leanback" android:required="false" />
<uses-feature android:name="android.hardware.camera.autofocus" />
<uses-permission android:name="android.permission.CAMERA" />
<uses-permission android:name="android.permission.RECORD_AUDIO" />
<uses-permission android:name="android.permission.WAKE_LOCK" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.CHANGE_NETWORK_STATE" />
<uses-permission android:name="android.permission.MODIFY_AUDIO_SETTINGS" />
<uses-permission android:name="com.android.vending.BILLING" />
<uses-permission android:name="android.permission.VIBRATE" />
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED"/>

<application
    tools:replace="android:label"  
    android:name="io.flutter.app.FlutterApplication"
    android:label="TalkEng"
    android:icon="@mipmap/ic_launcher">
       <receiver android:name="com.dexterous.flutterlocalnotifications.ScheduledNotificationBootReceiver">
    </receiver>
    <receiver android:name="com.dexterous.flutterlocalnotifications.ScheduledNotificationReceiver" />

    <activity
        android:name=".MainActivity"
        android:showWhenLocked="true"
        android:turnScreenOn="true"
        android:launchMode="singleTop"
        android:theme="@style/LaunchTheme"
        android:configChanges="orientation|keyboardHidden|keyboard|screenSize|smallestScreenSize|locale|layoutDirection|fontScale|screenLayout|density|uiMode"
        android:hardwareAccelerated="true"
        android:requestLegacyExternalStorage="true"
        android:windowSoftInputMode="adjustResize">

        <meta-data android:name="io.flutter.embedding.android.NormalTheme"
          android:resource="@style/NormalTheme" />

        <meta-data android:name="com.google.firebase.messaging.default_notification_icon"
        android:resource="@drawable/ic_notification_logo" />

        <meta-data
          android:name="io.flutter.embedding.android.SplashScreenDrawable"
          android:resource="@drawable/launch_background"
          />

        <intent-filter>
            <action android:name="android.intent.action.MAIN"/>
            <category android:name="android.intent.category.LAUNCHER"/>
        </intent-filter>

        <intent-filter>
            <action android:name="FLUTTER_NOTIFICATION_CLICK" />
            <category android:name="android.intent.category.DEFAULT" />
        </intent-filter>

    </activity>
    <activity
android:name="com.yalantis.ucrop.UCropActivity"
android:screenOrientation="portrait"
android:theme="@style/Theme.AppCompat.Light.NoActionBar"/>

    <meta-data
        android:name="flutterEmbedding"
        android:value="2" />

</application>

Main.dart file:

WidgetsFlutterBinding.ensureInitialized(); SystemChrome.setPreferredOrientations( [DeviceOrientation.portraitUp, DeviceOrientation.portraitDown]);

Stripe.publishableKey = 'p_test_51IlUalSG0anJNv685kHO8qkXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX'; runApp(MyApp());

API calling code :

Testkey(Secret key) ; sk_test_51IlUalSG0anJNv68S2XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

const functions = require("firebase-functions"); const stripe = require('stripe')(functions.config().stripe.testkey); exports.stripePayment = functions.https.onRequest(async (req, res) => { const paymentIntent = await stripe.paymentIntents.create({ amount:1999, currency: 'usd' }, function (err, paymentIntent) { if(err != null){ console.log(err); }else{ res.json({ paymentIntent: paymentIntent.client_secret }) } } ) } )

Calling Url : https://us-central1-talkengserverinstance.cloudfunctions.net/stripePayment Method : GET Response : {"paymentIntent":"pi_1J8gubSG0anJNv68ade6sRu7_secret_6MEDAblTKy0Hy7mWXNg2H5qXR"}

FlutterFragmentActivity Functions : Map<String, dynamic>? paymentIntentData;

Future makePayment() async { final url = Uri.parse( 'https://us-central1-talkengserverinstance.cloudfunctions.net/stripePayment'); final response = await http.get(url, headers: {'Content-Type': 'application/json'}); paymentIntentData = json.decode(response.body); await Stripe.instance.initPaymentSheet( // Here I am getting the ERROR paymentSheetParameters: SetupPaymentSheetParameters( paymentIntentClientSecret: paymentIntentData!['paymentIntent'],

    applePay: false, // I tried both true and false
    googlePay: false, // I tried both true and false
    merchantCountryCode: 'US',
    merchantDisplayName: 'Subhra',
    // style: ThemeService().getThemMode()
    style: ThemeMode.dark,
    testEnv: true, // I tried both true and false
  ),
);
await displayPaymentSheet();

} Future displayPaymentSheet() async { try { await Stripe.instance.presentPaymentSheet( parameters: PresentPaymentSheetParameters( clientSecret: paymentIntentData!['paymentIntent'], confirmPayment: true)); paymentIntentData = null; showSnackBar( type: SUCCESS, message: ‘Congratulations! We have received your payment.'); } catch (e) { showSnackBar(type: ERROR, message: 'ERROR: ${e.toString()}'); } }

I called this function from button click:

onPressed: () async { await sc.makePayment(); },

jonasbark commented 3 years ago

@subhra9326 android:name="io.flutter.app.FlutterApplication" this should point to your MainActivity class instead

subhra9326 commented 3 years ago

Hi, @jonasbark can you tell me the step to do that. I don't understand what to do. Thank you.

JoyEnergiser commented 3 years ago

Good day, I have solved my issue by editing my AndroidManifest.xml

1) adding the following android:name=".MainActivity" instead of android:name="io.flutter.embedding.android.FlutterActivity" 2) removing meta-data android:name="io.flutter.app.android.SplashScreenUntilFirstFrame" android:value="true"

I found the solution here since it was crashing on runtime https://github.com/flutter/flutter/issues/47136

subhra9326 commented 3 years ago

Hi, @JoyEnergiser and @jonasbark, thanks for helping me, My problem is resolved. Again thanks a lot.

robyhuzwandar commented 3 years ago

Hi,not work for me, do you have another solution? @jonasbark

AndroidManifest.xml

image

MainActivity.kt

image

styles.xml

image

ERROR :

image

harguilar commented 3 years ago

I am also having the same issue I followed the above instructions but the issue prevails. Below is my manifest file:

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.good_wallet">
   <application
        android:label="good_wallet"
        android:icon="@mipmap/ic_launcher">
        <activity
            android:name="io.flutter.embedding.android.FlutterActivity"
            android:launchMode="singleTop"
            android:theme="@style/Theme.AppCompat"
            android:configChanges="orientation|keyboardHidden|keyboard|screenSize|smallestScreenSize|locale|layoutDirection|fontScale|screenLayout|density|uiMode"
            android:hardwareAccelerated="true"
            android:windowSoftInputMode="adjustResize">
            <!-- Specifies an Android theme to apply to this Activity as soon as
                 the Android process has started. This theme is visible to the user
                 while the Flutter UI initializes. After that, this theme continues
                 to determine the Window background behind the Flutter UI
                 //Harguilar The Below Code was above AppCompat 
                 android:theme="@style/LaunchTheme"
                 . -->
            <meta-data
              android:name="io.flutter.embedding.android.NormalTheme"
              android:resource="@style/NormalTheme"
              />
            <!-- Displays an Android View that continues showing the launch screen
                 Drawable until Flutter paints its first frame, then this splash
                 screen fades out. A splash screen is useful to avoid any visual
                 gap between the end of Android's launch screen and the painting of
                 Flutter's first frame. -->
            <meta-data
              android:name="io.flutter.embedding.android.SplashScreenDrawable"
              android:resource="@drawable/launch_background"
              />
            <intent-filter>
                <action android:name="android.intent.action.MAIN"/>
                <category android:name="android.intent.category.LAUNCHER"/>
            </intent-filter>
        </activity>
        <!-- Don't delete the meta-data below.
             This is used by the Flutter tool to generate GeneratedPluginRegistrant.java -->
        <meta-data
            android:name="flutterEmbedding"
            android:value="2" />
    </application>
</manifest>
harguilar commented 3 years ago

Hi there, I do not know if someone managed to overcome this issue as my one still prevails. Am wondering if anyone is looking at it or has any idea why this is happening. I followed the tips that were given and am still stuck with the issue. Am losing hope and start to consider a new direction.

remonh87 commented 3 years ago

@harguilar I checked your manifests and you need to use the FlutterFragmentActivity instead of the FlutterActivity. If you changed this it should work. Else check also our example app:

@robyhuzwandar you did not reference the mainactivity.kt in your manifest and you still use the standard Flutter embedding as your launch activity. See: https://github.com/flutter-stripe/flutter_stripe/blob/e50d4a5158651a2ef8a87b29b318980d926d790b/example/android/app/src/main/AndroidManifest.xml#L7

harguilar commented 3 years ago

@remonh87 Man thanks a lot I tested and my issue is sorted. Well appreciated.

xlcod commented 3 years ago

Also happening here, if i write android:name=".MainActivity" app doesn´t launch.

remonh87 commented 3 years ago

@xlcod you need to create a class called MainActivity . Please checkout our example app: link

xlcod commented 3 years ago

@remonh87 Thanks for your help, sadly its already created. My issue here #238

DevTiago commented 3 years ago

None of the above solutions works for me. Theres my settings:

main.dart i've initialised the stripe.publishableKey on main.dart

app\build.gradle

- compileSdkVersion 30
- defaultConfig {
        minSdkVersion 21
        targetSdkVersion 30
}

android\build.gradle

dependencies {
        classpath 'com.android.tools.build:gradle:3.5.4'
        classpath 'com.google.gms:google-services:4.3.8'
    }

android\app\src\main\AndroidManifest

<application
        android:name="io.flutter.app.FlutterApplication". // --> i've changed to .MainActivity but the app wont work with that
        android:label="myApp"
        android:icon="@mipmap/ic_launcher">

        <activity
            android:name=".MainActivity"
            android:launchMode="singleTop"
            android:theme="@style/LaunchTheme"
            android:configChanges="orientation|keyboardHidden|keyboard|screenSize|smallestScreenSize|locale|layoutDirection|fontScale|screenLayout|density|uiMode"
            android:hardwareAccelerated="true"
            android:windowSoftInputMode="adjustResize">

<meta-data
            android:name="flutterEmbedding"
            android:value="2" />

android\app\src\main\kotlin\com\myApp\MainActivity

package com.upgrade.myApp

import io.flutter.embedding.android.FlutterActivity
import io.flutter.embedding.android.FlutterFragmentActivity

class MainActivity: FlutterFragmentActivity() {
}

Theres my Output:

E/flutter (14699): [ERROR:flutter/lib/ui/ui_dart_state.cc(199)] Unhandled Exception: PlatformException(flutter_stripe initialization failed, The plugin failed to initialize. Are you using FlutterFragmentActivity? Please check the README: https://github.com/flutter-stripe/flutter_stripe#android, null, null)
E/flutter (14699): #0      JSONMethodCodec.decodeEnvelope (package:flutter/src/services/message_codecs.dart:155:7)
E/flutter (14699): #1      MethodChannel._invokeMethod (package:flutter/src/services/platform_channel.dart:158:18)
E/flutter (14699): <asynchronous suspension>
E/flutter (14699): #2      MethodChannelStripe.dangerouslyUpdateCardDetails (package:stripe_platform_interface/src/method_channel_stripe.dart:212:5)
E/flutter (14699): <asynchronous suspension>
E/flutter (14699): #3      Stripe.dangerouslyUpdateCardDetails (package:flutter_stripe/src/stripe.dart:326:12)
E/flutter (14699): <asynchronous suspension>
E/flutter (14699): #4      _CustomCardPaymentScreenState._handleStripePayment (package:upeats/Cart/stripePayment.dart:134:5)
E/flutter (14699): <asynchronous suspension>
jonasbark commented 3 years ago

Does it work when you put in

<activity
            android:name="io.flutter.embedding.android.FlutterFragmentActivity"
            ...

? If not we will need a GitHub project where this behavior is reproducible.

DevTiago commented 3 years ago

I guess so... now i have another error but i think its not related with the package.

Thanks!

xlcod commented 3 years ago
io.flutter.embedding.android.FlutterFragmentActivity

I tried writting that, it doesn´t show any errors but also it doesn´t show any google pay button in my case.

jonasbark commented 3 years ago

that would be another configuration issue, unrelated to this topic. Be sure to check out official stripe documentation around Google Pay + Payment Sheet which you're using I guess.

harguilar commented 3 years ago

hey @remonh87 thanks a lot my issue is fixed

kylegraycar commented 2 years ago

I had this issue too and was able to fix once I realized I needed to add FlutterFragementActivity to the right MainActivity.kt.

My app, decarbon, had the file for both: com.example.decarbon >>>> Updating this fixed the issue for me, I think because it's the one that my AndroidManifest.xml points to... and com.decarbonapp.decarbon.dcrbn3 within .../android/app/src/main/kotlin/com

sonalcodes commented 2 years ago

Anyone got the solution ? I tried everythinf above but I am still getting Unhandled Exception: PlatformException(flutter_stripe initialization failed, The plugin failed to initialize. Are you using FlutterFragmentActivity? Please check the README: https://github.com/flutter-stripe/flutter_stripe#android, null, null)

coder-Aayush commented 2 years ago

Anyone got the solution ? I tried everythinf above but I am still getting Unhandled Exception: PlatformException(flutter_stripe initialization failed, The plugin failed to initialize. Are you using FlutterFragmentActivity? Please check the README: https://github.com/flutter-stripe/flutter_stripe#android, null, null)

For me, it solve when I upgrade to the latest flutter version i.e 2.8.1