Search code examples
laravelflutterpayment-gatewayrestrazorpay

Why Razorpay payment success handler method not calling my function?


I am trying to get details for payment made and update the details in the database subscription table, I am using Razorpay, Razorpay provides methods to handle different events that occurs. I want to send post request to the rest-api, Unfortunately, Razorpay's Payment success Event handler method is not calling my _subscription() function.

Here is my payment code.

import 'dart:convert';
import 'package:cached_network_image/cached_network_image.dart';
import 'package:flutter/material.dart';
import 'package:flutter_spinkit/flutter_spinkit.dart';
import 'package:razorpay_flutter/razorpay_flutter.dart';
import 'package:tneos_eduloution/network_utils/api.dart';
import 'package:flutter/services.dart';
import 'package:fluttertoast/fluttertoast.dart';

class Payment extends StatefulWidget {
  final int amount;
  final int categoryId;
  final int userId;
  final String name;
  final String image;
  final int packageClass;
  final String subject;
  final String board;
  Payment(this.amount, this.categoryId, this.userId, this.name, this.image, this.packageClass, this.subject, this.board);
  @override
  _PaymentState createState() => _PaymentState(this.amount, this.categoryId, this.categoryId, this.name, this.image, this.packageClass, this.subject, this.board);
}

class _PaymentState extends State<Payment> {
  static const platform = const MethodChannel("razorpay_flutter");
  int amount;
  int categoryId;
  int userId;
  String name;
  String image;
  int packageClass;
  String subject;
  String board;

  Razorpay _razorpay;
  // var orderId;
  // var razorpayId;

  _PaymentState(this.amount, this.categoryId, this.userId, this.name,
      this.image, this.packageClass, this.subject, this.board);


  @override
  Widget build(BuildContext context) {
    return Scaffold(
     // Code ....
        body: Container(
         // Code ....
              Expanded(
                flex: 2,
                child: Padding(
                  padding: const EdgeInsets.all(24.0),
                  child: RaisedButton(
                      elevation: 10,
                      shape: RoundedRectangleBorder(
                        borderRadius: BorderRadius.circular(18),
                      ),
                      color: ArgonColors.success,
                      child: Row(
                        mainAxisAlignment: MainAxisAlignment.center,
                        children: [
                          Icon(
                            Icons.add_shopping_cart,
                            color: ArgonColors.bgColorScreen,
                            size: 32,
                          ),
                          Text('BUY NOW', style: TextStyle(
                            color: ArgonColors.white,
                            fontSize: 32,
                            fontWeight: FontWeight.w600,
                            letterSpacing: 2,

                          ))
                        ],
                      ),
                      onPressed: () {
                        openCheckout();
                      }),
                ),
   // Code....
  }

  @override
  void initState() {
    super.initState();
    _razorpay = Razorpay();
    _razorpay.on(Razorpay.EVENT_PAYMENT_SUCCESS, _handlePaymentSuccess);
    _razorpay.on(Razorpay.EVENT_PAYMENT_ERROR, _handlePaymentError);
    _razorpay.on(Razorpay.EVENT_EXTERNAL_WALLET, _handleExternalWallet);
  }

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


  void openCheckout() async {
    var options = {
      'key': 'rzp_test_YbFME7OVSi2Kvx',
      'amount': amount * 100,
      'name': name,
      'image': 'https://tneos.in/app-assets/img/core-img/favicon.ico',
      'description': 'Buy the Course to get access for all live classes',
      'prefill': {'contact': '', 'email': ''},
      'external': {
        'wallets': ['paytm']
      }
    };
    try {
      _razorpay.open(options);
    } catch (e) {
      debugPrint(e);
    }
  }

  Future<void> _handlePaymentSuccess(PaymentSuccessResponse response) async {
    // orderId = 12123;
    // razorpayId = response.paymentId;
    _subscription();
    Fluttertoast.showToast(
        msg: "SUCCESS: " + response.paymentId, timeInSecForIosWeb: 4);
  }

  void _handlePaymentError(PaymentFailureResponse response) {
    Fluttertoast.showToast(
        msg: "ERROR: " + response.code.toString() + " - " + response.message,
        timeInSecForIosWeb: 4);
  }

  void _handleExternalWallet(ExternalWalletResponse response) {
    Fluttertoast.showToast(
        msg: "EXTERNAL_WALLET: " + response.walletName, timeInSecForIosWeb: 4);
  }

void _subscription() async {
  var data = {
    'name': name,
    'amount': amount,
    // 'order_id': orderId,
    // 'razorpay_id': razorpayId,
    'category_id': categoryId,
    'user_id': userId};
  var res = await Network().authData(data, '/subscription');
  var body = json.decode(res.body);
  if (body['success']) {
    print('success');
  } else {
    print('failure');
  }
}
}

authData comes from network class

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

class Network {
  final String _url = 'http://10.0.2.2:8000/api/v1';

  //if you are using android studio emulator, change localhost to 10.0.2.2
  var token;

  _getToken() async {
    SharedPreferences localStorage = await SharedPreferences.getInstance();
    token = jsonDecode(localStorage.getString('token'))['token'];
  }

  authData(data, apiUrl) async {
    var fullUrl = _url + apiUrl;
    return await http.post(fullUrl,
        body: jsonEncode(data), headers: _setHeaders());
  }

  getData(apiUrl) async {
    var fullUrl = _url + apiUrl;
    await _getToken();
    return await http.get(fullUrl, headers: _setHeaders());
  }

  _setHeaders() => {
        'Content-type': 'application/json',
        'Accept': 'application/json',
        'Authorization': 'Bearer $token',
        'connection': 'keep-alive',
      };
}

Laravel method API function which is working.

public function subscribed(Request $request) {
     
    $subscription = new Subscription;
    $subscription->title = $request->name;
    $subscription->amount = $request->amount;
    // $subscription->payment_id = $request->order_id;
    // $subscription->razorpay_id = $request->razorpay_id;
    $subscription->payment_done = 1;
    $subscription->category_id = $request->category_id;
    $subscription->user_id = $request->user_id;

    $subscription->save();

    return response()->json($subscription);

Postman response working. Postman API Response


Solution

  • It was my mistake, actually I was not doing things properly, I created new method first postData in network class.

      postData(data, apiUrl) async {
        var fullUrl = _url + apiUrl;
        await _getToken();
        return await http.post(fullUrl, body:jsonEncode(data), headers: _setHeaders());
      }
    

    Then I updated my Razorpay's Success Event handler method.

    
    void _handlePaymentSuccess(PaymentSuccessResponse response)  async {
        // orderId = 12123;
        // razorpayId = response.paymentId;
        var data = {
          'name': name,
          'amount': amount,
          // 'order_id': orderId,
          // 'razorpay_id': razorpayId,
          'category_id': categoryId,
          'user_id': userId};
        var res = await Network().postData(data, '/subscription');
        var body = json.decode(res.body);
        if (body['success']) {
           Fluttertoast.showToast(
               msg: "SUCCESS: " + response.paymentId, timeInSecForIosWeb: 4);
        } else {
          Fluttertoast.showToast(
              msg: "Kindly Contact US: " + response.paymentId, timeInSecForIosWeb: 4);
        }
        // _subscription();
    
      }