Flutter

Flutter PayPal Payment Integration Using Sandbox Mode

In this tutorial, we’ll implement PayPal payment integration using its Sandbox Environment in a Flutter app. By the end, you’ll have a working payment gateway that redirects users to a Thank You page upon successful payment.

Prerequisites

  • Basic understanding of Flutter and Dart

  • Installed Flutter and Android Studio/VS Code

  • PayPal Developer Account (Create one at developer.paypal.com)


🚀 Step 1: Create a PayPal App in Sandbox

  1. Log in to the PayPal Developer Dashboard.

  2. Navigate to Apps & CredentialsCreate App.

  3. Get your Client ID and Secret.

  4. Make sure the app is set to Sandbox mode for testing.


🛠️ Step 2: Install Required Packages

Add the following packages to your pubspec.yaml:

yaml
dependencies:
flutter:
sdk: flutter
http: ^1.2.1
url_launcher: ^6.2.5

Run:

flutter pub get

🧱 Step 3: Configure Platform-Specific Settings

For Android

  • Add internet permission to AndroidManifest.xml:

<uses-permission android:name="android.permission.INTERNET"/>

For iOS

  • In ios/Runner/Info.plist, add the following:

<key>LSApplicationQueriesSchemes</key>
<array>
<string>https</string>
<string>http</string>
</array>
<key>NSAppTransportSecurity</key>
<dict>
<key>NSAllowsArbitraryLoads</key>
<true/>
</dict>

📁 Folder Structure

Here’s how the project will be organized:

- lib
- main.dart
- services
- paypal_service.dart
- screens
- paypal_
payment_screen.dart
- thank_
you_screen.dart

🧑‍💻 Step 4: Create PayPal Service for API Calls

Create a file named paypal_service.dart under the services folder.

import 'dart:convert';
import 'package:http/http.dart' as http;

class PayPalService {
  final String clientId = 'YOUR_PAYPAL_CLIENT_ID';
  final String secret = 'YOUR_PAYPAL_SECRET';
  final String baseUrl = 'https://api-m.sandbox.paypal.com';

  // Get Access Token
  Future<String?> getAccessToken() async {
    try {
      final response = await http.post(
        Uri.parse('$baseUrl/v1/oauth2/token'),
        headers: {
          'Authorization': 'Basic ${base64Encode(utf8.encode('$clientId:$secret'))}',
          'Content-Type': 'application/x-www-form-urlencoded',
        },
        body: 'grant_type=client_credentials',
      );

      if (response.statusCode == 200) {
        final data = jsonDecode(response.body);
        return data['access_token'];
      } else {
        print('Failed to get access token: ${response.body}');
        return null;
      }
    } catch (e) {
      print('Error getting access token: $e');
      return null;
    }
  }

  // Create PayPal Payment
  Future<String?> createPayment(double amount) async {
    final accessToken = await getAccessToken();
    if (accessToken == null) return null;

    try {
      final response = await http.post(
        Uri.parse('$baseUrl/v2/checkout/orders'),
        headers: {
          'Content-Type': 'application/json',
          'Authorization': 'Bearer $accessToken',
        },
        body: jsonEncode({
          'intent': 'CAPTURE',
          'purchase_units': [
            {
              'amount': {
                'currency_code': 'USD',
                'value': amount.toStringAsFixed(2),
              }
            }
          ]
        }),
      );

      if (response.statusCode == 201) {
        final data = jsonDecode(response.body);
        final approvalLink = data['links']
            .firstWhere((link) => link['rel'] == 'approve')['href'];
        return approvalLink;
      } else {
        print('Payment creation failed: ${response.body}');
        return null;
      }
    } catch (e) {
      print('Error creating payment: $e');
      return null;
    }
  }
}

 


🧑‍💻 Step 5: Create a PayPal Payment Screen

Create a file named paypal_payment_screen.dart.

import 'package:flutter/material.dart';
import '../services/paypal_service.dart';
import 'package:url_launcher/url_launcher.dart';
import 'thank_you_screen.dart';

class PayPalPaymentScreen extends StatefulWidget {
  const PayPalPaymentScreen({Key? key}) : super(key: key);

  @override
  State<PayPalPaymentScreen> createState() => _PayPalPaymentScreenState();
}

class _PayPalPaymentScreenState extends State<PayPalPaymentScreen> {
  final PayPalService _paypalService = PayPalService();

  Future<void> initiatePayment() async {
    const double amount = 10.0;
    final approvalUrl = await _paypalService.createPayment(amount);

    if (approvalUrl != null) {
      if (await canLaunchUrl(Uri.parse(approvalUrl))) {
        await launchUrl(Uri.parse(approvalUrl), mode: LaunchMode.externalApplication);
        Navigator.pushReplacement(
          context,
          MaterialPageRoute(builder: (context) => const ThankYouScreen()),
        );
      } else {
        ScaffoldMessenger.of(context).showSnackBar(
          const SnackBar(content: Text('Could not launch PayPal URL')),
        );
      }
    } else {
      ScaffoldMessenger.of(context).showSnackBar(
        const SnackBar(content: Text('Failed to initiate PayPal payment')),
      );
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: const Text('Pay with PayPal')),
      body: Center(
        child: ElevatedButton(
          onPressed: initiatePayment,
          child: const Text('Pay \$10 with PayPal'),
        ),
      ),
    );
  }
}

 


🎉 Step 6: Create a Thank You Screen

Create thank_you_screen.dart to display after successful payment.

import 'package:flutter/material.dart';

class ThankYouScreen extends StatelessWidget {
  const ThankYouScreen({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: const Text('Thank You')),
      body: const Center(
        child: Text('Thank you for your payment!'),
      ),
    );
  }
}

 


🚀 Step 7: Update main.dart

import 'package:flutter/material.dart';
import 'screens/paypal_payment_screen.dart';

void main() {
  runApp(const MaterialApp(
    home: PayPalPaymentScreen(),
  ));
}

 


🔎 Testing Your Payment

  1. Run the app using:

    flutter run
  2. Click the Pay with PayPal button.

  3. A browser will open with a sandbox PayPal checkout.

  4. Complete the payment using a sandbox buyer account.

  5. Upon success, you’ll be redirected to the Thank You screen.


🚦 Troubleshooting

  • MissingPluginException: Ensure you’ve run:

    flutter clean
    flutter pub get
    flutter run
  • Invalid Credentials: Double-check your Client ID and Secret.

  • URL Not Opening: Confirm you’ve added URL launcher permissions.


🎯 Conclusion

You have successfully integrated PayPal sandbox payments in your Flutter app. For a production setup, switch to Live Mode by using your live credentials.

Need further tweaks or explanations? Let me know! 😊

Leave a Reply

Your email address will not be published. Required fields are marked *