partner_library_flutter 1.0.11 copy "partner_library_flutter: ^1.0.11" to clipboard
partner_library_flutter: ^1.0.11 copied to clipboard

Partner UI Integration Library for Flutter

example/lib/main.dart

import 'package:partner_library_flutter/partner_library_flutter.dart';
import 'package:dart_jsonwebtoken/dart_jsonwebtoken.dart';

import 'package:flutter/material.dart';
import 'package:flutter_dotenv/flutter_dotenv.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:partner_library_flutter_example/DeepLinkTest.dart';
import 'package:partner_library_flutter/src/utils/widgets/RateLimiterScreen.dart';

void main() async {
  WidgetsFlutterBinding.ensureInitialized();
  await dotenv.load(fileName: "lib/.env");

  await PartnerLibrary.init(
    "https://sbmsmartbankinguat.esbeeyem.com",
    whitelistedDomains: [
      "razorpay.com",
      "sbmkycuat.esbeeyem.com",
      "m2pfintech.com"
    ],
    deviceBindingEnabled: false,
  );

  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      debugShowCheckedModeBanner: false,
      home: MyHome(),
    );
  }
}

class MyHome extends StatefulWidget {
  @override
  _MyHomeState createState() => _MyHomeState();
}

class _MyHomeState extends State<MyHome> {
  final _formKey = GlobalKey<FormState>();
  final _nameController = TextEditingController();
  final _emailController = TextEditingController();
  final _phoneController = TextEditingController();

  String name = '';
  String email = '';
  String phone = '';
  final String? clientId = dotenv.env['KID'];
  String baseUrl = '';
  String token = '';

  @override
  void initState() {
    baseUrl = dotenv.env['BASE_URL']!;
    super.initState();
    // _setupDeepLinks();
    _checkSession((WebViewCallback action) {
      switch (action.type) {
        case WebViewCallbackType.redirect:
          print("Redirected with status: ${action.status}");
          break;
        case WebViewCallbackType.logout:
          print("User logged out");
          break;
      }
    });
  }

  Future<void> _checkSession(WebViewCallbackFunction callback) async {
    SharedPreferences prefs = await SharedPreferences.getInstance();

    String? name = prefs.getString('name');
    String? email = prefs.getString('email');
    String? phone = prefs.getString('phone');
    setState(() {
      _nameController.text = name ?? '';
      _emailController.text = email ?? '';
      _phoneController.text = phone ?? '';
    });
    // final String clientId = dotenv.env['KID']!;

    // if (name != null && email != null && phone != null) {
    //   await createToken('/banking/sbm/credit_card/CRE','', callback,
    //       nameInput: name, emailInput: email, phoneInput: phone);
    // }
  }

  Future<void> createToken(
      String module, String photo, WebViewCallbackFunction callback,
      {String? nameInput, String? emailInput, String? phoneInput}) async {
    setState(() {
      name = nameInput?.isNotEmpty == true ? nameInput! : _nameController.text;
      email =
          emailInput?.isNotEmpty == true ? emailInput! : _emailController.text;
      phone =
          phoneInput?.isNotEmpty == true ? phoneInput! : _phoneController.text;
    });
    SharedPreferences prefs = await SharedPreferences.getInstance();
    await prefs.setString('name', name);
    await prefs.setString('email', email);
    await prefs.setString('phone', phone);
    final String clientId = dotenv.env['KID']!;

    final Map<String, Object> headers = {
      'kid': clientId,
      'typ': 'JWT',
      'alg': 'HS256',
    };

    final Map<String, String> attributes = {
      'name': name,
      'photo': photo,
    };
    const Duration expirationDuration = Duration(milliseconds: 300000);
    final clientSecret = dotenv.env['CLIENT_SECRET'];
    final jwt = JWT(
      {
        'email': email,
        'phone': phone,
        'attributes': attributes,
        'module': module
      },
      header: headers,
    );

    token = await jwt.sign(
      SecretKey(clientSecret!),
      expiresIn: expirationDuration,
    );

    print("Token generated FROM client side is: $token");

    await PartnerLibrary.instance.open(context, module, token, callback);
  }

  // void _setupDeepLinks() {
  //   partnerLibrary.initializeDeepLinks(
  //     context,
  //     onDeepLinkNavigate: (String path) {
  //       switch (path) {
  //         case '/deeplink1':
  //           Navigator.of(context).push(MaterialPageRoute(
  //             builder: (context) => DeepLinkTest(),
  //           ));
  //           break;
  //         case '/deeplink2':
  //           Navigator.of(context).push(MaterialPageRoute(
  //             builder: (context) => DeepLinkTest2(),
  //           ));
  //           break;
  //       }
  //     },
  //     onSpenseLoadSlug: (String loadSlug) {
  //       print("Handling Spense load slug: $loadSlug");
  //     },
  //   );
  // }

  @override
  void dispose() {
    _nameController.dispose();
    _emailController.dispose();
    _phoneController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: SafeArea(
        child: Padding(
          padding: const EdgeInsets.all(16.0),
          child: Form(
            key: _formKey,
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Row(
                  children: [
                    Spacer(),
                    SizedBox(
                      height: 48,
                      child: TextButton(
                        style: TextButton.styleFrom(
                          foregroundColor: Colors.black,
                        ),
                        onPressed: () {
                          if (_formKey.currentState!.validate()) {
                            createToken(dotenv.env['MODULE']!, '',
                                (WebViewCallback action) {
                              switch (action.type) {
                                case WebViewCallbackType.redirect:
                                  print(
                                      "Redirected with status: ${action.status}");
                                  break;
                                case WebViewCallbackType.logout:
                                  print("User logged out");
                                  break;
                              }
                            });
                          }
                        },
                        child: const Text(
                          'Dashboard',
                          style: TextStyle(
                            fontWeight: FontWeight.bold,
                            fontSize: 20,
                          ),
                        ),
                      ),
                    ),
                  ],
                ),
                SizedBox(height: MediaQuery.of(context).size.height * 0.02),
                const Text(
                  'User Details',
                  style: TextStyle(fontSize: 30, fontWeight: FontWeight.bold),
                ),
                SizedBox(height: MediaQuery.of(context).size.height * 0.02),
                TextFormField(
                  controller: _nameController,
                  decoration: const InputDecoration(
                    fillColor: Colors.grey,
                    labelText: 'Name',
                    border: OutlineInputBorder(),
                  ),
                  validator: (value) {
                    if (value == null || value.isEmpty) {
                      return 'Please enter your name';
                    }
                    return null;
                  },
                ),
                SizedBox(height: MediaQuery.of(context).size.height * 0.02),
                TextFormField(
                  controller: _emailController,
                  decoration: const InputDecoration(
                    fillColor: Colors.grey,
                    labelText: 'Email',
                    border: OutlineInputBorder(),
                  ),
                  validator: (value) {
                    if (value == null || value.isEmpty) {
                      return 'Please enter your email';
                    }
                    return null;
                  },
                ),
                SizedBox(height: MediaQuery.of(context).size.height * 0.02),
                TextFormField(
                  controller: _phoneController,
                  decoration: const InputDecoration(
                    fillColor: Colors.grey,
                    labelText: 'Phone number',
                    border: OutlineInputBorder(),
                  ),
                  validator: (value) {
                    if (value == null || value.isEmpty) {
                      return 'Please enter your phone number';
                    }
                    return null;
                  },
                ),
                SizedBox(
                  height: 48,
                  child: TextButton(
                    style: TextButton.styleFrom(
                      foregroundColor: Colors.black,
                    ),
                    onPressed: () {
                      if (_formKey.currentState!.validate()) {
                        createToken('${dotenv.env['MODULE']!}/pay_bill', '',
                            (WebViewCallback action) {
                          switch (action.type) {
                            case WebViewCallbackType.redirect:
                              print("Redirected with status: ${action.status}");
                              break;
                            case WebViewCallbackType.logout:
                              print("User logged out");
                              break;
                          }
                        });
                      }
                    },
                    child: const Text(
                      'Pay Bill',
                      style: TextStyle(
                        fontWeight: FontWeight.bold,
                        fontSize: 20,
                      ),
                    ),
                  ),
                ),
                SizedBox(
                  height: 48,
                  child: TextButton(
                    style: TextButton.styleFrom(
                      foregroundColor: Colors.black,
                    ),
                    onPressed: () {
                      if (_formKey.currentState!.validate()) {
                        createToken('${dotenv.env['MODULE']!}/card_limits', '',
                            (WebViewCallback action) {
                          switch (action.type) {
                            case WebViewCallbackType.redirect:
                              print("Redirected with status: ${action.status}");
                              break;
                            case WebViewCallbackType.logout:
                              print("User logged out");
                              break;
                          }
                        });
                      }
                    },
                    child: const Text(
                      'Manage Card',
                      style: TextStyle(
                        fontWeight: FontWeight.bold,
                        fontSize: 20,
                      ),
                    ),
                  ),
                ),
                SizedBox(
                  height: 48,
                  child: TextButton(
                    style: TextButton.styleFrom(
                      foregroundColor: Colors.black,
                    ),
                    onPressed: () {
                      if (_formKey.currentState!.validate()) {
                        createToken(
                            '${dotenv.env['MODULE']!}/all_transactions', '',
                            (WebViewCallback action) {
                          switch (action.type) {
                            case WebViewCallbackType.redirect:
                              print("Redirected with status: ${action.status}");
                              break;
                            case WebViewCallbackType.logout:
                              print("User logged out");
                              break;
                          }
                        });
                      }
                    },
                    child: const Text(
                      'Transactions',
                      style: TextStyle(
                        fontWeight: FontWeight.bold,
                        fontSize: 20,
                      ),
                    ),
                  ),
                ),
                SizedBox(
                  height: 48,
                  child: TextButton(
                    style: TextButton.styleFrom(
                      foregroundColor: Colors.black,
                    ),
                    onPressed: () {
                      if (_formKey.currentState!.validate()) {
                        createToken('${dotenv.env['MODULE']!}/enhance', '',
                            (WebViewCallback action) {
                          switch (action.type) {
                            case WebViewCallbackType.redirect:
                              print("Redirected with status: ${action.status}");
                              break;
                            case WebViewCallbackType.logout:
                              print("User logged out");
                              break;
                          }
                        });
                      }
                    },
                    child: const Text(
                      'Enhance',
                      style: TextStyle(
                        fontWeight: FontWeight.bold,
                        fontSize: 20,
                      ),
                    ),
                  ),
                ),
                const Spacer(),
                ElevatedButton(
                    onPressed: () {
                      Navigator.of(context).push(MaterialPageRoute(
                        builder: (context) => DeepLinkTest(),
                      ));
                    },
                    child: Text('Go to DeepLink')),
                ElevatedButton(
                  onPressed: () {
                    Navigator.of(context).push(MaterialPageRoute(
                      builder: (context) => RateLimiterScreen(
                        onCallback: (WebViewCallback action) {
                          switch (action.type) {
                            case WebViewCallbackType.redirect:
                              print("Redirected with status: ${action.status}");
                              break;
                            case WebViewCallbackType.logout:
                              print("User logged out");
                              break;
                          }
                        },
                      ),
                    ));
                  },
                  child: Text('Rate Limiter'),
                ),
              ],
            ),
          ),
        ),
      ),
    );
  }
}