Flutter oAuth : how to get started with OAuth and Stripe connect

前端 未结 3 819
南笙
南笙 2021-01-23 02:25

I am trying to implement stripe connect in my flutter app. Here are the steps I need to implement. Can anyone please navigate me on how I could achieve this in Flutter?

相关标签:
3条回答
  • 2021-01-23 02:49

    If you want to create an in-app stripe connect account registration with flutter you will need these:

    1. A server or service to complete the OAuth like Firebase Functions or Integromat (I used Integromat)
    2. A link that will redirect to your app (I used Firebase Dynamic Link)

    STEPS TO CREATE THE REGISTRATION FLOW

    INTEGROMAT/FIREBASE FUNCTIONS SETUP

    I decided to use Integromat instead of Firebase Functions because is easier to set up, doesn't need any code, and decreases my server load.

    If you want to create it on Firebase Functions you will need to have a Blaze Plan

    If you don't know it, Integromat will automate processes that you currently handle manually, via webhooks. It is not only capable of connecting apps (like GoogleCloud, Facebook, AWS...) but can also transfer and transform data.

    Create a new scenario and add a Custom Webhook. Click on it and click on add, name it, and save it. It will now create a custom link to your webhook.

    Close and click on the semi-sphere next to the webhook, to add the new module. Select HTTP and Make a Request.

    In the URL section insert https://connect.stripe.com/oauth/token. Method POST. Body Type Application/x-www-form-urlencoded.

    Create now those fields :

    Key client_secret - value your stripe client secret You can find it on your stripe dashboard. I advise you to first use the test mode and after that, change the value to the live key.

    Key grant_type - value authorization_code

    Key code - leave the value blank. We will add it later.

    Save and close

    For Firebase Functions you can create a new HTTPS function (I didn't test this)

    var stripe = require("stripe")(*your stripe client secret*);
    
    exports.connectStripeStandardAccount = functions.https.onRequest((req, res) =>{
    
      let authCode = req.query.code;
      return stripe.oauth.token({
        grant_type: 'authorization_code',
        code: authCode,
      });
    });
    

    Remember to install stripe package npm install stripe


    STRIPE SETUP

    If you are in the test mode go to this link If you are in the live mode go to this link

    Go on the bottom and activate oAuth for standard accounts or for Express Account.

    Click on Add URI and add the webhook link of Integromat that you created or the link related to your Firebase function.

    If you used Firebase add this link https://us-central1-<project-id>.cloudfunctions.net/connectStripeStandardAccount

    For Integromat you will need to create the structure. To do this click on Test OAuth, copy the link, and open it in incognito mode. Open your Integromat scenario and click on your webhook. Now click on Re-determine data structure.

    Return to your stripe registration page and click on Ignore account form at the top.

    Return on Integromat and select the HTTPS request, modify the field code, and insert the variable code (will open a dialog with all queries from the webhook). Confirm and save.

    Now click on the play button and reopen the stripe registration link in incognito mode and click on Ignore account form. Return in Integromat and add a JSON module after the HTTPS request. In the JSON string insert the Data variable and save. Create a Webhook Response module after the JSON module.

    In the status put 301, then click on Ok.


    DEEP LINK SETUP

    It's time to set up the redirect link that will return the user to our flutter app or on our website if the user hasn't it installed.

    I used Firebase Dynamic Link You can follow this tutorial for set up.

    Go to the dashboard and create a new Link prefix and a new dynamic link, remember to select to redirect your users to the right app.

    Click on the three dots in your dynamic link row and click on Link Details. Copy the extended link.

    Open Integromat and select the last module you created (Webhook Response). Click on Show advanced settings and on the Header add :

    Key Location - value the extended dynamic link that you copied.

    If you want your app to elaborate data from the stripe OAuth response you can modify the extended dynamic link by adding ? on the link parameter: link=https://test.page.link?stripe_user_id={{14.stripe_user_id}}

    And select the variable parsed from the JSON module. Remember to click on the save icon to save your scenario.

    On Firebase Functions you can do this when the function stripe.oauth.token finish (I didn't test it):

    res.setHeader('Location', your dynamic link);
    res.status(301).send();
    

    Remember to deploy it.


    FLUTTER APP SETUP

    The code here is very simple. To initialize the connect account registration you only need to set up a button that will launch the stripe connect URL. You can use launch(url);

    You can find that URL here. Remember to be logged in to your stripe account to get the right stripe client id. You can easily get it in the same section you added the webhook link in your stripe connect settings.

    Delete &redirect_uri=https://sub2.example.com on the URL.

    Now you can test your app and will see that when you complete your stripe connect registration/login you will be redirected to your app.

    If you want to have an in-app web view you can use this package

    To handle the response, you need to have installed the package firebase_dynamic_links

    Set your Main widget Stateful and on the initState run the method getDynamic() :

    void getDynamic() {
        FirebaseDynamicLinks.instance.getInitialLink().then((value) {
          if (value != null) {
            _connect(value);
          }
        });
    
        FirebaseDynamicLinks.instance.onLink(onSuccess: (value) async {
          if (value != null) {
            _connect(value);
          }
        }, onError: (error) async {
          debugPrint('DynamicLinks onError $error');
        });
      }
    
    void _connect(value) {
        Uri deepLink = value.link;
    
        print("Link :" + deepLink.path);
    
        print("Query :" + deepLink.queryParameters.toString());
    
        String stripeUserId = deepLink.queryParameters["stripe_user_id"];
        
      }
    

    You need to have both of them to handle dynamic links when your app is running and when it's closed.

    0 讨论(0)
  • 2021-01-23 03:02

    The answer selected is not completely correct: If you dont assign the account_id to a user then it's of no use. The only way to pass the user_id (fUser.uid) is to pass it using the state parameter.

    exports.StripePI = functions.https.onRequest(async (req, res) => {
    //    console.log('accountIdq ' + req.query.error);
    //    console.log('accountIdq ' + req.query.state);
    //    return;
    //        if(!req.query.code)
    //            return res.send("An Error has occured please try again");
        const response = await stripe.oauth.token({
          grant_type: 'authorization_code',
          code: req.query.code,
        }).then(async response => {
                var connected_account_id = response.stripe_user_id;
              await admin.firestore().collection('Registration').doc(req.query.state)
                               .update({customer_id : connected_account_id});
               return res.send("Well done, account integration is completed. You can now close the window and go back to the app");
            });
    });
    
    0 讨论(0)
  • 2021-01-23 03:08

    I found out this myself using firebase cloud functions:

    • first you create an https function in the firebase cloud function
    • then you add the link created by the function to your stripe dashboard
    • then you write the following logic to your function
      • obtain the the authorisation code
      • fetch data from stripe
      • save the response somewhere (in my case in realtime database)

    Here is the function

    exports.connectStripeStandardAccount = functions.https.onRequest((req, res) => {
    
      let authCode = req.query.code;
      return stripe.oauth.token({
        grant_type: 'authorization_code',
        code: authCode,
      }).then(async response => {
    
        await admin.database()
           .ref(`/accounts/${authCode}`)
           .set(response);
         return res.send("Well done, account integration is completed. You can now close the window and go back to the app");
      });
    });
    
    0 讨论(0)
提交回复
热议问题