Home Blog Page 24

PayPal Payment Integration in Flutter

0

Flutter PayPal Payment Gateway Integration

At the time of writing, PayPal does not provide an SDK/package for their Paypal payment Integration in Flutter 

We will cover how to integrate PayPal into a flutter project using web-view. We must take a few actions to do this.

What is PayPal ?

PayPal is a payment platform featuring a website and a phone app that allows for online money transactions between parties.

PayPal is a highly secure banking service that employs some of the most cutting-edge end-to-end encryption technology available. You should also activate two-factor authentication and erase any inactive bank accounts or email addresses.

Because PayPal is not presently providing an SDK/package for their payment gateway integration in Flutter, I successfully implemented PayPal using WebView. I’ve used several of PayPal’s payment Web services that are available for integration in websites all around the world, so I decided to test it in a flutter to reach my aim.

First, we’ll make a PayPal application.

In this example, PayPal Sandbox is used to test the payment integration.

What is the PayPal sandbox?

The PayPal sandbox is a virtual testing environment that is segregated from the actual PayPal production environment. The PayPal sandbox mimics the functionality accessible on PayPal’s production servers. While several PayPal features, such as account termination, monthly statement creation, preserving shipping preferences, and PayPal Shops support, are not available in the paypal sandbox, it does have the same PayPal API feature set as the live environment. You may test your PayPal procedures in the sandbox. Processes behave precisely as they do on production servers in the sandbox.

PayPal developer dashboard

Now. Go to the PayPal developer account dashboard to start utilizing PayPal with Flutter.

Account for PayPal sandbox testing

You’ll see a sidebar in the SANDBOX option where you may pick the accounts and obtain this screen.

Make a PayPal application.

Select My Apps & Credentials from the left panel as shown in this image, then click the “Build App” button to create an app in PayPal.

Include appName, appType, and sandbox account information.

Include this page in your app’s Name, AppType, and Sandbox Business Accounts, as instructed by PayPal, and then click the “Create App” button to acquire the app credentials.

This screen contains the secret id and client id.

After successfully constructing the application, you must retrieve the secret id and client id by clicking on the application detail.

Implementation of Paypal In Flutter App:

Download/Install dependencies.

Add the required dependencies in pubspec.yaml file as shown below.

http_auth:^any
http:^any
webview_flutter:^any

Code implement

To begin, we’ll develop a PaypalHomeScreen and populate it with our simple sample UI and Navigation to pay the payment .

 final GlobalKey<ScaffoldState> _scaffoldKey = GlobalKey<ScaffoldState>();

 @override
 Widget build(BuildContext context) {
   return Scaffold(
     backgroundColor: Colors.white,
     key: _scaffoldKey,
     appBar: AppBar(
       centerTitle: true,
       backgroundColor: Colors.white,
       title: const Text(
         'Paypal Payment',
         style: TextStyle(
           fontSize: 18.0,
           color: Colors.black,
           fontWeight: FontWeight.bold,
         ),
       ),
     ),
     body: SizedBox(
         width: MediaQuery.of(context).size.width,
         child: Column(
           crossAxisAlignment: CrossAxisAlignment.center,
           mainAxisAlignment: MainAxisAlignment.center,
           children: <Widget>[
             Column(
               children: const [
                 Text(
                   "Items in your Cart",
                   style: TextStyle(fontSize: 16, fontWeight: FontWeight.w600),
                 ),
                 ListTile(
                   title: Text(
                     "Product: One plus 10",
                     style:
                         TextStyle(fontSize: 14, fontWeight: FontWeight.w600),
                   ),
                   subtitle: Text(
                     "Quantity: 1",
                     style:
                         TextStyle(fontSize: 14, fontWeight: FontWeight.w600),
                   ),
                   trailing: Text(
                     "\$100",
                     style:
                         TextStyle(fontSize: 16, fontWeight: FontWeight.w600),
                   ),
                 )
               ],
             ),
             RaisedButton(
               color: Colors.red,
               onPressed: () {
                 // make PayPal payment
                 Navigator.of(context).push(
                   MaterialPageRoute(
                     builder: (BuildContext context) => Payment(
                       onFinish: (number) async {
                         // payment done
                         final snackBar = SnackBar(
                           content: const Text("Payment done Successfully"),
                           duration: const Duration(seconds: 5),
                           action: SnackBarAction(
                             label: 'Close',
                             onPressed: () {
                               // Some code to undo the change.
                             },
                           ),
                         );
                         _scaffoldKey.currentState!.showSnackBar(snackBar);
                       },
                     ),
                   ),
                 );
               },
               child: const Text(
                 'Pay with Paypal',
                 textAlign: TextAlign.center,
                 style: TextStyle(color: Colors.white),
               ),
             ),
           ],
         )),
   );
 }

The next step is to establish the PayPalService page, from which we will use the PayPal APIs; for now, because we are testing, we will use the URL https://api.sandbox.paypal.com . If you wish to make an actual transaction, replace that with https://api.paypal.com .

Note : In testing mode, a sandbox account is used, but in live mode, a genuine PayPal account is used.

We will now create a PaypalService.dart screen.

PaypalService.dart

class PaypalServices {
 String domain = "https://api.sandbox.paypal.com";

 /// for testing mode
//String domain = "https://api.paypal.com"; /// for production mode

 /// Change the clientId and secret given by PayPal to your own.
 String clientId =
     'Here add clientId';
 String secret =
     'Here add secretId';

 /// for obtaining the access token from Paypal
 Future<String?> getAccessToken() async {
   try {
     var client = BasicAuthClient(clientId, secret);
     var response = await client.post(
         Uri.parse('$domain/v1/oauth2/token?grant_type=client_credentials'));
     if (response.statusCode == 200) {
       final body = convert.jsonDecode(response.body);
       return body["access_token"];
     }
     return null;
   } catch (e) {
     rethrow;
   }
 }

 // for generating the PayPal payment request
 Future<Map<String, String>?> createPaypalPayment(
     transactions, accessToken) async {
   try {
     var response = await http.post(Uri.parse("$domain/v1/payments/payment"),
         body: convert.jsonEncode(transactions),
         headers: {
           "content-type": "application/json",
           'Authorization': 'Bearer ' + accessToken
         });

     final body = convert.jsonDecode(response.body);
     if (response.statusCode == 201) {
       if (body["links"] != null && body["links"].length > 0) {
         List links = body["links"];

         String executeUrl = "";
         String approvalUrl = "";
         final item = links.firstWhere((o) => o["rel"] == "approval_url",
             orElse: () => null);
         if (item != null) {
           approvalUrl = item["href"];
         }
         final item1 = links.firstWhere((o) => o["rel"] == "execute",
             orElse: () => null);
         if (item1 != null) {
           executeUrl = item1["href"];
         }
         return {"executeUrl": executeUrl, "approvalUrl": approvalUrl};
       }
       return null;
     } else {
       throw Exception(body["message"]);
     }
   } catch (e) {
     rethrow;
   }
 }

 /// for carrying out the payment process
 Future<String?> executePayment(url, payerId, accessToken) async {
   try {
     var response = await http.post(url,
         body: convert.jsonEncode({"payer_id": payerId}),
         headers: {
           "content-type": "application/json",
           'Authorization': 'Bearer ' + accessToken
         });

     final body = convert.jsonDecode(response.body);
     if (response.statusCode == 200) {
       return body["id"];
     }
     return null;
   } catch (e) {
     rethrow;
   }
 }
}

To submit the order and payment details to PayPal, we will now create a payment screen.

payment screen

GlobalKey<ScaffoldState> _scaffoldKey = GlobalKey<ScaffoldState>();
 String? checkoutUrl;
 String? executeUrl;
 String? accessToken;
 PaypalServices services = PaypalServices();

 // You may alter the default value to whatever you like.
 Map<dynamic, dynamic> defaultCurrency = {
   "symbol": "USD ",
   "decimalDigits": 2,
   "symbolBeforeTheNumber": true,
   "currency": "USD"
 };

 bool isEnableShipping = false;
 bool isEnableAddress = false;

 String returnURL = 'return.example.com';
 String cancelURL = 'cancel.example.com';

 @override
 void initState() {
   super.initState();

   Future.delayed(Duration.zero, () async {
     try {
       accessToken = await services.getAccessToken();

       final transactions = getOrderParams();
       final res =
           await services.createPaypalPayment(transactions, accessToken);
       if (res != null) {
         setState(() {
           checkoutUrl = res["approvalUrl"];
           executeUrl = res["executeUrl"];
         });
       }
     } catch (ex) {
       final snackBar = SnackBar(
         content: Text(ex.toString()),
         duration: const Duration(seconds: 10),
         action: SnackBarAction(
           label: 'Close',
           onPressed: () {
             // Some code for undoing the alteration.
           },
         ),
       );
       _scaffoldKey.currentState!.showSnackBar(snackBar);
     }
   });
 }

 // item name, price and quantity here
 String itemName = 'One plus 10';
 String itemPrice = '100';
 int quantity = 1;

 Map<String, dynamic> getOrderParams() {
   List items = [
     {
       "name": itemName,
       "quantity": quantity,
       "price": itemPrice,
       "currency": defaultCurrency["currency"]
     }
   ];

   // Checkout Invoice Specifics
   String totalAmount = '100';
   String subTotalAmount = '100';
   String shippingCost = '0';
   int shippingDiscountCost = 0;
   String userFirstName = 'john';
   String userLastName = 'smith';
   String addressCity = 'USA';
   String addressStreet = "i-10";
   String addressZipCode = '44000';
   String addressCountry = 'Pakistan';
   String addressState = 'Islamabad';
   String addressPhoneNumber = '+1 223 6161 789';

   Map<String, dynamic> temp = {
     "intent": "sale",
     "payer": {"payment_method": "paypal"},
     "transactions": [
       {
         "amount": {
           "total": totalAmount,
           "currency": defaultCurrency["currency"],
           "details": {
             "subtotal": subTotalAmount,
             "shipping": shippingCost,
             "shipping_discount": ((-1.0) * shippingDiscountCost).toString()
           }
         },
         "description": "The payment transaction description.",
         "payment_options": {
           "allowed_payment_method": "INSTANT_FUNDING_SOURCE"
         },
         "item_list": {
           "items": items,
           if (isEnableShipping && isEnableAddress)
             "shipping_address": {
               "recipient_name": userFirstName + " " + userLastName,
               "line1": addressStreet,
               "line2": "",
               "city": addressCity,
               "country_code": addressCountry,
               "postal_code": addressZipCode,
               "phone": addressPhoneNumber,
               "state": addressState
             },
         }
       }
     ],
     "note_to_payer": "Contact us for any questions on your order.",
     "redirect_urls": {"return_url": returnURL, "cancel_url": cancelURL}
   };
   return temp;
 }

 @override
 Widget build(BuildContext context) {
   print(checkoutUrl);

   if (checkoutUrl != null) {
     return Scaffold(
       appBar: AppBar(
         backgroundColor: Theme.of(context).backgroundColor,
         leading: GestureDetector(
           child: const Icon(Icons.arrow_back_ios),
           onTap: () => Navigator.pop(context),
         ),
       ),
       body: WebView(
         initialUrl: checkoutUrl,
         javascriptMode: JavascriptMode.unrestricted,
         navigationDelegate: (NavigationRequest request) {
           if (request.url.contains(returnURL)) {
             final uri = Uri.parse(request.url);
             final payerID = uri.queryParameters['PayerID'];
             if (payerID != null) {
               services
                   .executePayment(executeUrl, payerID, accessToken)
                   .then((id) {
                 widget.onFinish!(id);
                 Navigator.of(context).pop();
               });
             } else {
               Navigator.of(context).pop();
             }
             Navigator.of(context).pop();
           }
           if (request.url.contains(cancelURL)) {
             Navigator.of(context).pop();
           }
           return NavigationDecision.navigate;
         },
       ),
     );
   } else {
     return Scaffold(
       key: _scaffoldKey,
       appBar: AppBar(
         leading: IconButton(
             icon: const Icon(Icons.arrow_back),
             onPressed: () {
               Navigator.of(context).pop();
             }),
         backgroundColor: Colors.black12,
         elevation: 0.0,
       ),
       body: const Center(child: CircularProgressIndicator()),
     );
   }
 }

Your desired output is 👍

flutter paypal github complete code

https://github.com/kevalv001/paypal_demo.git

Conclusion

This was a brief overview of the PayPal services; I covered the service in the post; you may modify the code to suit your needs. I believe you now have enough information from this blog to experiment with PayPal in your flutter projects.

Thank you very much!!Have a Good day…..

Firebase dynamic link in flutter

0
firebase dynamic links in flutter

By using dynamic linking, increase user experience, engagement, and retention

You may redirect both current and potential users to any point within your iOS or Android app using dynamic links, which are clever URLs. Even new users see the content they’re seeking for when they open the app for the first time because they survive the app installation process. Dynamic Links are always free, regardless of scale.

What distinguishes a static link from a dynamic link

For managing deep linking for applications and websites, Firebase Dynamic Links offers a wealth of features. The nicest aspect is that any scale of Firebase deep connection is free. Instead of sending the user to the Play Store, dynamic links improve the user experience by leading him to the intended equivalent site or app content. This appears to be helping to develop, improve, and expand applications for various platform domains.

Firebase Dynamic Links: 

The following circumstances are handled by Firebase Dynamic Links:

  • If a user clicks on one of your dynamic links, they will be instantly sent to the play store or app store to download your app in order to view the link.
  • Opening the link will launch the programme on the device if it is installed but not currently running in the foreground.
  • The user can access a dynamic link in the registered listener if the app is in the forefront.

How to integrate Dynamic Links in flutter using Firebase

Initial Configuration & Setup

First and foremost, we set up our Firebase project to support dynamic linking. Click on the link below to start your firebase project.

Log in to the Firebase console, then click Add project.

Open the firebase console and tap the “Add project option” , and get this type of screen.

Here add your firebase project name.

  1. Select your existing Google Cloud project from the dropdown menu, then click Continue.
  2. (Optional) Select or create a Google Analytics account after enabling Google Analytics for your project.
  3. When you’re finished, scroll down and select “Create Project.”

The firebase console might take some few seconds to go through your application. Once everything is done, click the proceed button to see the project overview page.

Select here Android or/ and IOS platform.

You can skip this step if you have already configured your project for Dynamic Links.

Firebase Dynamic Links From the Firebase console setting 

  • Launch the Firebase console. Open the Firebase project where Firebase Dynamic Links need to be added.
  • Configure your Firebase project’s App: (Android, iOS) option.
  • The Dynamic Links section will appear after the Grow Section.
  • To create a URL prefix, now click Get Started.
  • Make a dynamic link with the app’s distinctive domain name in it. Using firebasedynamiclinks.page.link as an illustration. Here, the suffix page.link is added to the domain name.
  • then perform the steps to Configure, Verify, and Finish.

The first step is, Enter your domain here and press the continue button , 

Dynamic links are created on a domain, which you can modify by adding your own name, company name, brand, and so on. Customized links appear more relevant and Display this dialogue, then click Finish.

The following screen will then display this dialog.

Click on the three dots on the right side, then select Allowlist URL pattern, then enter the link below and click on the add option.

Create a dynamic link inside the Firebase Console

a). Click the image below into the “New Dynamic link” button.

b). Set up a short URL link and then click “Next”.

Set up for short dynamic link

Put your custom URL in the URL prefix header.

c). Then, in the second step “Set up your Dynamic Link,” enter the URL for your dynamic link. There is a deep link to your application, and if a specific user has not installed the app, he or she should be redirected to the appropriate location. As an example, as the dynamic link, you could provide an app play store link. You can give your dynamic link any meaningful short name you want. Click the “Next” button.

add the dynamic link URL & name.

d). in the fourth step of Select the “Open the deep link URL in a browser” option. If the specific app is not installed in your app, the link will open in the browser. If you don’t have an iOS app, you can select “Open the deep link in your iOS App.” Then press the “Next” button.

Choose link behavior for ios.

e). In this section, we define Android behavior. Choose “Open the deep link in your Android App” and enter the name of your Android app. Then press the “Next” button.

Choose link behavior for android.

f). You can also change some advanced settings. Then click “Create”.

Now , let’s move to the Flutter code side…

Installing the plugin for Firebase Dynamic Links:

There are packages available for Flutter that give users access to many different services on each platform.

Step : 1) Open the pubspec.yaml file in the project’s root directory, then add the following package:

firebase_dynamic_links: ^any

Step : 2) Get the flutter packages.

Add the command on specific IDE terminal flutter packages get

This will allow you to add Firebase Dynamic Links to your Flutter project.

Create a Dynamic Link In Programming

Make a dynamic Link instance.

FirebaseDynamicLinks dynamicLinks = FirebaseDynamicLinks.instance;

Add the function for create dynamic link

Future<void> _createDynamicLink() async {
 final DynamicLinkParameters parameters = DynamicLinkParameters(
   uriPrefix: 'https://croudoperationapp.page.link',
   link: Uri.parse(
     "https://croudoperationapp.page.link/referral?code=12345&amp;userId=${123)}"),
   androidParameters: const AndroidParameters(
     packageName: 'Add your app package name',
     minimumVersion: 0,
   ),
   iosParameters: const IOSParameter(
     bundleId: 'Add your app bundle Id',
     minimumVersion: ‘0’,
     appStoreId: ‘Add your app store Id’
   ),
   socialMetaTagParameters: SocialMetaTagParameters(
    title: "Example of a Dynamic Link",
    imageUrl: Uri.parse("https://example.com/image.png"),
  ),
 );
}

Use the DynamicLinkParameters instead of the DynamicLinkParameters to create a short Dynamic Link. method buildShortLink()

String? _deepLink;

 final ShortDynamicLink shortLink =
     await dynamicLinks.buildShortLink(parameters);
 Uri url = shortLink.shortUrl;
 setState(() {
   _deepLink = url.toString();
 });

Use the DynamicLinkParameters to abbreviate a lengthy Dynamic Link. method shortenUrl

call the _createDynamicLink function on the button where to create a link.

FloatingActionButton.extended(
 backgroundColor: Theme.of(context).colorScheme.primary,
 onPressed: () async {
   await _createDynamicLink();
   print(_deepLink);
   if (_deepLink != null) {
     Share.share(_deepLink!);
   }
 },
 icon: const Icon(
   Icons.share,
   color: Colors.white,
 ),
 label: const Text(
   "Referral code",
   style: TextStyle(color: Colors.white),
 ),
)

Add the code into the main.dart file.

Future<void> main() async {
  WidgetsFlutterBinding.ensureInitialized();
  await Firebase.initializeApp();
  await GetStorage.init();
  runApp(
    MaterialApp(
      title: 'Dynamic Links Example',
      debugShowCheckedModeBanner: false,
      home: const LoginPage(),
      theme: ThemeData(
        colorScheme: defaultColorScheme,
        primarySwatch: Colors.blue,
      ),
      builder: EasyLoading.init(),
    ),
  );
}

Now, Handling dynamic links and redirecting them to particular content.

Void handleDynamicLink(){

var data = await FirebaseDynamicLinks.instance.getInitialLink();
var deepLink = data;

if (deepLink != null) {
  // kill state dynamic link handling here
  //navigate here
}

 dynamicLinks.onLink.listen((dynamicLinkData) async {
 print('on listen');
           print(dynamicLinkData.link.queryParameters["code"]);
   // open and not terminated state dynamic link handling here
  //navigate here
    }).onError((error) {
      print('onLink error');
      print(error.message);
    });
}

Github code link for reference:

https://github.com/kevalv001/deep_link_app.git

Flutter Dynamic Link – Integrating Refer & earn in app

Conclusion 

In the post, I showed the fundamental structure of dynamicLink; you may adapt this code to suit your needs, and this was a brief introduction to dynamicLink using Firebase and how it works with Flutter.

Thank you !!! Have a good day 😊 😊 ..

Basic Windows command everyone should know

0
windows cmd

Hi, Here are some basic windows command that everyone one should remember.

1. Create New Folder

mkdir -> make directory / Create a new folder in the working directory.

mkdir [directory name]

2. Change director/navigate to directory

cd -> Change directory let you to navigate directory & access different folders.

cd [folder/directory name]
windows cmd to change working directory folder

3. List all files

dir -> List the files & folders contained in the current working directory.

dir
windows command to list file in current working directory
windows command to list file in current working directory

4. Rename folder or file name

ren -> to re-name files or folder name.

ren [old folder name] [new folder name]

5. Copy file

copy -> copies the files to specified folder.

copy [file] [destination]

5. Delete file

del -> delete files or folder

del folder Name
del file name

What is git? Why we use GitHub

0
Why we use GitHub

GitHub is a platform by which you can collaboration and version control your project. That enables you & your team to remote collaboration on projects.

Why we use GitHub

Version Control

  • Git is a version control system.
  • Version control is used to track changes and manage code.
  • Version Control system are used by any type of developer as a part of their workflow.

Staging Environment

  • git has it’s own staging envirnoment.
  • By using staging envirnoment, you can make changes to the working directory.
  • Staging makes it easier to adjust what you commit.

Branches

  • Branch help you structure new changes.
  • By using branches, you can work on your repository without any risk.
  • when finished and finalizing the code, your branch can be merged with master/main github branch.

Collaboration

  • When working with other programmers, git comes in handy as a collaboration tool.

As version control is a necessory part of development, Git knowledge is needed in most developers job.

React vs Angular – Difference between react and angular

0
difference between react and angular
React vs Angular

Hi Guys, Welcome to Proto Coders Point. In this Article let’s check out the difference between react and angular.

Difference between react and angular

ReactAngular
React is a JS library developed by Facebook which allows us in building UI Components. It facilitates the creation of interactive user interface.Angular is a structured framework from developing dynamic web apps. It allows developers to use HTML as a template and allow HTML’s syntax to express the application’s components briefly and clearly.
FeatureFeatures of ReactJS is Code reusability, Rich JavaScript library, one -way data binding.Feature of Angular is Testing, Creating templates, accessibility, low-code framework.
Easy to learnIt is easier to grasp compared to angular. However, When it come integrating with Redux it become difficult.Learning Angular is not easy for beginners. This, Angular require lot’s of training.
When dynamic content is required, React.js is suggested.Angular is platform-independent and hence is compatible to work in any platform.
LanguageReact.js written using JavaScript.Angular uses microsoft’s TypeScript language, Which is a super set if ECMAScript 6 (ES6).
InjectionReact.js, Does not use the dependencies Injection concept.Angular Hierarchical Dependency Injection system is used.
Data-BindingIn react Data binding is one-way type.In react Data binding is two-way type.
App BuildInstagram, Yahoo, Netflix, Facebook, Dropbox, Uber etc are build using React.Microsoft, Apple, GoPro, Mesh, Telegram, Google, Paypal..etc are using Angular.

Recommended Article

Learn Angular – Build first web app using angular

Flutter vs React native

7 best tools for react development

How to use bootstrap in React

How to create custom hooks in react

How do I turn off refresh rate hz that is always showing on MSI Monitor Screen

0

I recently got a new MSI optix G241 monitor, and on a left corner of monitor their is a screen refresh rate been showing.

Let’s check out how to display refresh rate hz showing on monitor screen.

Solution:

On MSI monitor on back there is a small red joystick button using which you can change MSI monitor settings.

Follow this Step to disable refresh rate been show in screen.

  • Open Monitor Menu – Click red button on back of monitor.
  • Select Gaming Option.
  • then select Refresh Rate.
  • and then turn it off.