ezet / stripe-sdk

A simple and flexible Stripe library for Flutter with complete support for SCA and PSD2.
https://pub.dev/packages/stripe_sdk
Other
137 stars 137 forks source link

A little confused about initialisation #150

Closed vinnytwice closed 2 years ago

vinnytwice commented 2 years ago

I'm a bit confused abut how to initialise the package properly given the Stripe terminology.

App => my platform , which has an AccountId and a publishable key. Account => any seller connected to my platform. Customer => any buyer paying to my sellers.

As I first understood, I should initialise it with my platform publishable key as Stripe.init(Environment.stripePublishableKey); and my platform AccountId as I saw the stripeAccount optional parameter, but the I saw the doc hint acc_ so it was clear to initialise Stripe with a CustomerId contrarily to the AccountId .

But then I initialise the CustomerSession with api version ( I upgraded in console to the latest ), customerId (same as above) but it trows an Unhandled Exception: Failed to parse Ephemeral Key, Please return the response as it is as you received from stripe server .

Can you please help me clarify this? I 've looked around but haven't seen any explanation. Many thanks.

Here's my inits, what am I doing wrong?:

try {
              Stripe.init(Environment.stripePublishableKey,
                  stripeAccount: state.user.stripeId);

              CustomerSession.initCustomerSession((apiVersion) async {
                print('apiVersion is : $apiVersion');
                return apiVersion;
              }, apiVersion: '2020-08-27', stripeAccount: state.user.stripeId);
            } catch (error) {
              print('Stripe error: $error');
            }
vinnytwice commented 2 years ago

Finally after a better look at the method description

void initCustomerSession( 
Future<String> Function(String) provider,
{ String apiVersion = defaultApiVersion,
String stripeAccount,
bool prefetchKey = true,
})

I saw that I needed to create it using the Stipe api from my Node server:

stripe.ephemeralKeys.create({customer: customer}, {apiVersion: apiVersion})
            .then((result) => {
                console.log('Mongoose findUser customer && stripe_version ephemeralKey is: ', result);
                if(result != null) {
                    res.status(200).send({message: 'Ephemeral key created successfully.', data : result});
                } else {
                    res.status(400).send({message: 'Ephemeral key not created'});
                }
            }).catch((err) => {
                console.log('Mongoose findUser customer && stripe_version ephemeralKey error: ', err);
                res.status(503).send({message: 'Internal error, Ephemeral key not created'});
            });

retrieve it with a method in my repository that hits the endpoint:

Future<String> getEphemeralKey({String apiVersion, String stripeId}) async {
    String ephemeralKey;
    await _firebaseAuth.currentUser.getIdToken().then((idToken) {
      headers = {
        'Content-Type': 'application/json',
        'api_key': Environment.dbApiKey,
        'AuthToken': idToken
      };
    });
    var params = {'customer': stripeId, 'apiVersion': apiVersion};
    final Uri uri = Uri.http(Environment.dbUrl, 'api/users', params);

    await get(uri, headers: headers).then((resp) {
      if (resp.statusCode == 200) {
        ephemeralKey = jsonEncode(jsonDecode(resp.body)['data']);
      }
    }).catchError((e) {
      print('PaymentMongoRepository getEphemeralKey error: $e');
    });
    return ephemeralKey;
  }

and finally I Initialise customerSession:

Future<String> createCustomerEphemeralKey(
                  {String apiVersion, String customerId}) async {
                String ephemeralKey;
                await _mongoRepository
                    .getEphemeralKey(
                        apiVersion: apiVersion, stripeId: state.user.stripeId)
                    .then((key) {
                  ephemeralKey = key;
                }).catchError((e) {
                  print(
                      '∞∞∞∞∞∞∞∞∞∞∞∞∞∞∞∞∞∞∞∞∞  AccountConnectionManager getEphemeralKey key error: $e');
                });
                return ephemeralKey;
              }

              CustomerSession.initCustomerSession(
                  (apiVersion) => createCustomerEphemeralKey(
                      apiVersion: '2020-08-27',
                      customerId: state.user.stripeId),
                  stripeAccount: state.user.stripeId);

The method is expecting an Ephemeral key in a json formatted string (which is not specified anywhere except in the error:

Unhandled Exception: Failed to parse Ephemeral Key, `Please return the response as it is as you received from stripe server`

I discovered it looking at the actual package code for EphimeralKey .. Hope this helps others.. Cheers