Using a razorpay plugin in flutter Giving a error

88 Views Asked by At

I have a create a application where if user click then it should make a payment. for payment gateway purpose I use razoerpay .I also added dependency in pubspec.yml file & API key of razorpay. but after a building application for android they give me following error

FAILURE: Build failed with an exception.

  • What went wrong: A problem occurred configuring project ':razorpay_flutter'.

Could not create an instance of type com.android.build.api.variant.impl.LibraryVariantBuilderImpl. Namespace not specified. Specify a namespace in the module's build file. See https://d.android.com/r/tools/upgrade-assistant/set-namespace for information about setting the namespace.

 If you've specified the package attribute in the source AndroidManifest.xml, you can use the AGP Upgrade Assistant to migrate to the namespace value in the build file. Refer to https://d.android.com/r/tools/upgrade-assistant/agp-upgrade-assistant for general information about using the AGP Upgrade Assistant.
  • Try:

Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output. Run with --scan to get full insights.

BUILD FAILED in 34s Exception: Gradle task assembleDebug failed with exit code 1

file where i use razorpay plugin

import 'dart:convert';

import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:firebase_auth/firebase_auth.dart';
import 'package:firebase_messaging/firebase_messaging.dart';
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
import 'package:fluttertoast/fluttertoast.dart';
import 'package:razorpay_flutter/razorpay_flutter.dart';

class BillingDialogBox extends StatefulWidget {
  BillingDialogBox({
    Key? key,
    required this.providerName,
    required this.categoryName,
    required this.charges,
    required this.selectedDate,
    required this.seekername,
  }) : super(key: key);

  final String providerName;
  final String categoryName;
  final String charges;
  final DateTime? selectedDate;
  final String seekername;

  @override
  State<BillingDialogBox> createState() => _BillingDialogBoxState();
}

class _BillingDialogBoxState extends State<BillingDialogBox> {
  late String providerName;
  late String categoryName;
  late double charges;
  late DateTime? selectedDate;
  final FirebaseMessaging _firebaseMessaging = FirebaseMessaging.instance;
  late String seekername;

  late Razorpay _razorpay;

  bool _isPaymentProcessing = false;

  @override
  void initState() {
    super.initState();
    _razorpay = Razorpay();
    _razorpay.on(Razorpay.EVENT_PAYMENT_SUCCESS, handlePaymentSuccess);
    _razorpay.on(Razorpay.EVENT_PAYMENT_ERROR, handlePaymentError);
    providerName = widget.providerName;
    categoryName = widget.categoryName;
    charges = double.parse(widget.charges);
    selectedDate = widget.selectedDate;
    seekername = widget.seekername;
  }

  @override
  void dispose() {
    super.dispose();
    _razorpay.clear();
  }

  void handlePaymentError(PaymentFailureResponse response) {
    Fluttertoast.showToast(msg: "Error while payment ${response.code}");
    setState(() {
      _isPaymentProcessing = false;
    });
  }

  void handlePaymentSuccess(PaymentSuccessResponse response) async {
    Fluttertoast.showToast(msg: "Payment Successful ${response.paymentId}");
    final String uid = FirebaseAuth.instance.currentUser!.uid;
    await FirebaseFirestore.instance.collection('Scheduling').add({
      "UID": uid,
      'provider_name': providerName,
      'date': selectedDate,
      'status': 'pending',
      'amount': charges,
      'seeker_name': seekername,
    });
    storePaymentDetails(response.paymentId!);
    sendNotification(providerName);
    setState(() {
      _isPaymentProcessing = false;
    });
  }

  Future<void> storePaymentDetails(String paymentID) async {
    await FirebaseFirestore.instance.collection('Payment').add({
      "payment ID": paymentID,
      'provider_name': providerName,
      'date': selectedDate,
      'amount': charges,
      'seeker_name': seekername,
    });
  }

  void makePayment() async {
    setState(() {
      _isPaymentProcessing = true;
    });

    var options = {
      'key': 'YOUR_RAZORPAY_KEY_ID', // Replace with your Razorpay Key ID
      'amount': (charges * 100).toInt(),
      'name': seekername,
      'description': 'Payment for $categoryName Service',
      'prefill': {'email': '[email protected]'},
      'external': {
        'wallets': ['paytm']
      }
    };
    _razorpay.open(options);
  }

  @override
  Widget build(BuildContext context) {
    double GST = charges * 0.05;
    double total = charges + GST + GST;

    return Container(
      height: MediaQuery.of(context).size.height * 0.8,
      padding: const EdgeInsets.fromLTRB(16, 48, 16, 16),
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          const Text(
            "Billing Info",
            style: TextStyle(fontSize: 20, fontWeight: FontWeight.bold),
          ),
          const Divider(color: Colors.black),
          const SizedBox(height: 10),
          Row(
            mainAxisAlignment: MainAxisAlignment.end,
            crossAxisAlignment: CrossAxisAlignment.center,
            children: [
              Text("Provider Name: $providerName"),
              const Spacer(),
              Text("Service Name: $categoryName"),
            ],
          ),
          const Divider(color: Colors.black),
          const SizedBox(height: 20),
          Row(
            children: [
              const Text("Service Charges:"),
              const Spacer(),
              Text("₹ $charges"),
            ],
          ),
          const SizedBox(height: 10),
          const Text("GST ", style: TextStyle(fontWeight: FontWeight.bold)),
          Row(
            children: [
              const Text("CGST 5%:"),
              const Spacer(),
              Text("₹ $GST"),
            ],
          ),
          const SizedBox(height: 10),
          Row(
            children: [
              const Text("SGST 5%:"),
              const Spacer(),
              Text("₹  $GST"),
            ],
          ),
          const Divider(color: Colors.black),
          Row(
            children: [
              const Text("Total Payable Amount:"),
              const Spacer(),
              Text("₹  $total"),
            ],
          ),
          const Divider(color: Colors.black),
          const SizedBox(height: 20),
          Row(
            children: [
              TextButton(
                onPressed: () {
                  Navigator.pop(context);
                },
                child: const Text("Cancel"),
              ),
              ElevatedButton(
                onPressed: _isPaymentProcessing ? null : makePayment,
                child: _isPaymentProcessing
                    ? CircularProgressIndicator()
                    : const Text('Make Payment'),
              ),
            ],
          ),
        ],
      ),
    );
  }

  void sendNotification(String providerName) {
    FirebaseFirestore.instance
        .collection('tokens')
        .where('name', isEqualTo: providerName)
        .get()
        .then((QuerySnapshot querySnapshot) {
      querySnapshot.docs.forEach((doc) {
        if (doc.exists) {
          String providerToken = doc['token'];
          RemoteMessage notificationMessage = RemoteMessage(
            data: {
              'title': 'New Service Request',
              'body': 'You have a new service request from $seekername.',
            },
          );
          sendNotificationToServer(providerToken, notificationMessage);
        }
      });
    });
  }

  void sendNotificationToServer(
      String providerToken, RemoteMessage notificationMessage) {
    http.post(
      Uri.parse('https://fcm.googleapis.com/fcm/send'),
      body: jsonEncode({
        'to': providerToken,
        'data': notificationMessage.data,
        'notification': notificationMessage.notification,
      }),
      headers: {
        'Content-Type': 'application/json',
        'Authorization':
            'AAAARVTHu4M:APA91bHTwGD9scs5f-WhOX0D-a4NX-Vo4-1T8rahNQnwhF9UJJ_RBssouK4ChS-p7r1TmgKSwjHfPgCx8cIjgpTtRS32m03TTW83XJvGnr8gjQVDPtFkEnBwgat6xCrLjXr4G8wRCy1B'
      },
    );
  }
}

android/build.gradel:

buildscript {
    ext.kotlin_version = '1.9.21'
    repositories {
        google()
        mavenCentral()
    }



    dependencies {
        classpath 'com.android.tools.build:gradle:8.1.4'
        classpath 'com.google.gms:google-services:4.4.0' 
        classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
        
    }
}

allprojects {
    repositories {
        google()
        mavenCentral()
    }
}

rootProject.buildDir = '../build'
subprojects {
    project.buildDir = "${rootProject.buildDir}/${project.name}"
}
subprojects {
    project.evaluationDependsOn(':app')
}

tasks.register("clean", Delete) {
    delete rootProject.buildDir
}

android/app/build.gradel:

plugins {
    id "com.android.application"
    id "kotlin-android"
    id "dev.flutter.flutter-gradle-plugin"
    id 'com.google.gms.google-services'
}

def localProperties = new Properties()
def localPropertiesFile = rootProject.file('local.properties')
if (localPropertiesFile.exists()) {
    localPropertiesFile.withReader('UTF-8') { reader ->
        localProperties.load(reader)
    }
}

def flutterVersionCode = localProperties.getProperty('flutter.versionCode')
if (flutterVersionCode == null) {
    flutterVersionCode = '1'
}

def flutterVersionName = localProperties.getProperty('flutter.versionName')
if (flutterVersionName == null) {
    flutterVersionName = '1.0'
}

android {
    namespace "com.example.local_service_provider"
    compileSdkVersion flutter.compileSdkVersion
    ndkVersion flutter.ndkVersion

    compileOptions {
        sourceCompatibility JavaVersion.VERSION_1_8
        targetCompatibility JavaVersion.VERSION_1_8
    }

    kotlinOptions {
        jvmTarget = '1.8'
    }

    sourceSets {
        main.java.srcDirs += 'src/main/kotlin'
    }

    defaultConfig {
        // TODO: Specify your own unique Application ID (https://developer.android.com/studio/build/application-id.html).
        applicationId "com.example.local_service_provider"
        // You can update the following values to match your application needs.
        // For more information, see: https://docs.flutter.dev/deployment/android#reviewing-the-gradle-build-configuration.
        minSdkVersion 21
        targetSdkVersion flutter.targetSdkVersion
        versionCode flutterVersionCode.toInteger()
        versionName flutterVersionName
    }

    buildTypes {
        release {
            // TODO: Add your own signing config for the release build.
            // Signing with the debug keys for now, so `flutter run --release` works.
            signingConfig signingConfigs.debug
        }
    }
}

flutter {
    source '../..'
}

dependencies {
    implementation platform('com.google.firebase:firebase-bom:32.7.2')
    implementation("com.google.firebase:firebase-auth")
}

AndroidManifest.xml:

<manifest xmlns:android="http://schemas.android.com/apk/res/android">
    <application
        android:label="local_service_provider"
        android:name="${applicationName}"
        android:icon="@mipmap/ic_launcher">
        <activity
            android:name=".MainActivity"
            android:exported="true"
            android:launchMode="singleTop"
            android:theme="@style/LaunchTheme"
            android:configChanges="orientation|keyboardHidden|keyboard|screenSize|smallestScreenSize|locale|layoutDirection|fontScale|screenLayout|density|uiMode"
            android:hardwareAccelerated="true"
            android:windowSoftInputMode="adjustResize">
            <!-- Specifies an Android theme to apply to this Activity as soon as
                 the Android process has started. This theme is visible to the user
                 while the Flutter UI initializes. After that, this theme continues
                 to determine the Window background behind the Flutter UI. -->
            <meta-data
              android:name="io.flutter.embedding.android.NormalTheme"
              android:resource="@style/NormalTheme"
              />
            <intent-filter>
                <action android:name="android.intent.action.MAIN"/>
                <category android:name="android.intent.category.LAUNCHER"/>
            </intent-filter>
        </activity>
        <!-- Don't delete the meta-data below.
             This is used by the Flutter tool to generate GeneratedPluginRegistrant.java -->
        <meta-data
            android:name="flutterEmbedding"
            android:value="2" />
    </application>
</manifest>

pubspec.yaml:

name: local_service_provider
description: A new Flutter project.
# The following line prevents the package from being accidentally published to
# pub.dev using `flutter pub publish`. This is preferred for private packages.
publish_to: 'none' # Remove this line if you wish to publish to pub.dev

# The following defines the version and build number for your application.
# A version number is three numbers separated by dots, like 1.2.43
# followed by an optional build number separated by a +.
# Both the version and the builder number may be overridden in flutter
# build by specifying --build-name and --build-number, respectively.
# In Android, build-name is used as versionName while build-number used as versionCode.
# Read more about Android versioning at https://developer.android.com/studio/publish/versioning
# In iOS, build-name is used as CFBundleShortVersionString while build-number is used as CFBundleVersion.
# Read more about iOS versioning at
# https://developer.apple.com/library/archive/documentation/General/Reference/InfoPlistKeyReference/Articles/CoreFoundationKeys.html
# In Windows, build-name is used as the major, minor, and patch parts
# of the product and file versions while build-number is used as the build suffix.
version: 1.0.0+1

environment:
  sdk: '>=3.1.5 <4.0.0'

# Dependencies specify other packages that your package needs in order to work.
# To automatically upgrade your package dependencies to the latest versions
# consider running `flutter pub upgrade --major-versions`. Alternatively,
# dependencies can be manually updated by changing the version numbers below to
# the latest version available on pub.dev. To see which dependencies have newer
# versions available, run `flutter pub outdated`.
dependencies:
  flutter:
    sdk: flutter


  # The following adds the Cupertino Icons font to your application.
  # Use with the CupertinoIcons class for iOS style icons.
  cupertino_icons: ^1.0.2
  cloud_firestore: ^4.14.0
  firebase_auth: ^4.16.0
  firebase_core: ^2.24.2
  firebase_storage: ^11.6.0
  email_validator: '^2.1.16'
  provider: ^6.1.1
  image_picker: ^1.0.7
  flutter_datetime_picker: ^1.5.1
  intl: ^0.18.1
  firebase_messaging: ^14.7.10
  http: ^1.1.0
  razorpay_flutter: ^1.3.6
  toast: ^0.3.0


dev_dependencies:
  flutter_test:
    sdk: flutter

  # The "flutter_lints" package below contains a set of recommended lints to
  # encourage good coding practices. The lint set provided by the package is
  # activated in the `analysis_options.yaml` file located at the root of your
  # package. See that file for information about deactivating specific lint
  # rules and activating additional ones.
  flutter_lints: ^2.0.0

# For information on the generic Dart part of this file, see the
# following page: https://dart.dev/tools/pub/pubspec

# The following section is specific to Flutter packages.
flutter:

  # The following line ensures that the Material Icons font is
  # included with your application, so that you can use the icons in
  # the material Icons class.
  uses-material-design: true

  # To add assets to your application, add an assets section, like this:
  assets:
    - Images/logo1.jpg
  #   - images/a_dot_ham.jpeg

  # An image asset can refer to one or more resolution-specific "variants", see
  # https://flutter.dev/assets-and-images/#resolution-aware

  # For details regarding adding assets from package dependencies, see
  # https://flutter.dev/assets-and-images/#from-packages

  # To add custom fonts to your application, add a fonts section here,
  # in this "flutter" section. Each entry in this list should have a
  # "family" key with the font family name, and a "fonts" key with a
  # list giving the asset and other descriptors for the font. For
  # example:
  # fonts:
  #   - family: Schyler
  #     fonts:
  #       - asset: fonts/Schyler-Regular.ttf
  #       - asset: fonts/Schyler-Italic.ttf
  #         style: italic
  #   - family: Trajan Pro
  #     fonts:
  #       - asset: fonts/TrajanPro.ttf
  #       - asset: fonts/TrajanPro_Bold.ttf
  #         weight: 700
  #
  # For details regarding fonts from package dependencies,
  # see https://flutter.dev/custom-fonts/#from-packages
1

There are 1 best solutions below

0
On

Because you are using Gradle 8+,

classpath 'com.android.tools.build:gradle:8.1.4'

there is a requirement there, that all modules declare a namespace. I can't see your AGP (Android Gradle Plugin) version, but since you are using Gradle 8.1.4 it must be higher than 8 as well (since AGP 8 and above requires Gradle 8 and above).

Seeing as you are using the latest version of razorpay_flutter, I can recommend downgrading to Gradle and AGP below 8 and seeing if that works.

Also, there is an issue already open in razorpay's repository for this exactly.