PhonePe / phonepe-pg-sdk-flutter

12 stars 7 forks source link

Success message is coming even the payment request is declined #11

Closed AlthafMjeelani closed 8 months ago

AlthafMjeelani commented 1 year ago

I was trying to integrate phonepay payment but [Success message is coming even the payment request is declined

Uploading eea91d04-ca1c-4966-aa4c-41a33b0df792.mp4…

hitanshu1 commented 1 year ago

can share your code

AlthafMjeelani commented 1 year ago

initPhonepe() async { PhonePePaymentSdk.init(AppConstant.phonePayenvironment, AppConstant.phonePayAppId, AppConstant.phonePayMerchentId, true) .then((val) => {print('PhonePe SDK Initialized -->> $val')}) .catchError((error) { return {}; }); }

Object? result;

Future<Object?> startPGTransaction( String body, String callback, String checksum, Map<String, String> headers, BuildContext context, amount, String merchantTransactionId, ) async { try { Map<dynamic, dynamic>? response = await PhonePePaymentSdk. startPGTransaction( body, callback, checksum, headers, AppConstant.phonePayapiEndpoint, AppConstant.phonePayPackgeName, );

if (kDebugMode) {
  print('Phonepe response --------------------->>>  response $response '

); }

if (response != null) {
  String status = response['status'].toString();
  String error = response['error'].toString();

  if (status == 'SUCCESS') {
    if (kDebugMode) {
      print('Phonepe response --------------------->>>  response $

response');

      print('Phonepe response --------------------->>>  $status ');
      print('Phonepe response --------------------->>>  $error ');
    }
    handlePaymentSuccess(amount, merchantTransactionId, context);
  } else if (status == 'FAILURE') {
    // Handle failure
    result = "Payment Failed - Error: $error";
    // You may want to navigate to a failure screen or handle it

accordingly. } else if (status == 'INTERUPTED') { // Handle interrupted status result = "Payment Interrupted - Error: $error"; // You may want to navigate to a specific screen or handle it accordingly. } else { // Handle other statuses result = "Payment Status: $status - Error: $error"; // You may want to handle other statuses here. } } else { result = "Flow Incomplete"; }

return response;

} catch (error) { handleError(error); // Handle other errors, and you may want to navigate to a failure screen. return {}; } }

goToPayment(double price, BuildContext context) { String merchantTransactionId = 'DMH${DateTime.now().millisecondsSinceEpoch}';

final jsonData = {
  "merchantId": AppConstant.phonePayMerchentId,
  "merchantTransactionId": merchantTransactionId,
  "merchantUserId": "MUID123",
  "amount": price * 100,
  "redirectUrl": "",
  "redirectMode": "POST",
  "callbackUrl": "",
  "mobileNumber": "9999999998",
  "paymentInstrument": {"type": "PAY_PAGE"},
  "deviceContext": {
    "deviceOS": Platform.isIOS ? "IOS" : "ANDROID",
  }
};

String jsonString = jsonEncode(jsonData);
String base64Data = jsonString.toBase64;
String dataToHash = base64Data +
    AppConstant.phonePayapiEndpoint +
    AppConstant.phonePaySaltKey;
String sHA256 = generateSha256Hash(dataToHash);

String checksum = '$sHA256###${AppConstant.phonePaySaltIndex}';

startPGTransaction(
    base64Data,
    'https://webhook.site/callback-url',
    checksum,
    {"Content-Type": "application/json"},
    context,
    price,
    merchantTransactionId);

}

void handleError(error) {}

void handlePaymentSuccess(amount, merchantTransactionId, context) async { placeOrder(context: context, payType: 'phonepe'); }

String generateSha256Hash(String input) { var bytes = utf8.encode(input); var digest = sha256.convert(bytes); return digest.toString(); }

List upiApps = []; void getInstalledUpiAppsForAndroid() { if (Platform.isAndroid) { PhonePePaymentSdk.getInstalledUpiAppsForAndroid().then((apps) { if (apps != null) { Iterable l = json.decode(apps); upiApps = List.from(l.map((model) => UPIApp.fromJson (model))); String appString = ''; for (var element in upiApps) { appString += "${element.applicationName} ${element.version} ${element. packageName}"; } result = 'Installed Upi Apps - $appString'; } else { result = 'Installed Upi Apps - 0'; } }).catchError((error) { handleError(error); return {}; }); } } }

extension EncodingExtensions on String { /// To Base64 /// This is used to convert the string to base64 String get toBase64 { return base64.encode(toUtf8); }

/// To Utf8 /// This is used to convert the string to utf8 List get toUtf8 { return utf8.encode(this); }

/// To Sha256 /// This is used to convert the string to sha256 String get toSha256 { return sha256.convert(toUtf8).toString(); } } static const String phonePaySaltKey = '4a181d5f-624e-45a5-bee4-57d634ce4828'; static const String phonePaySaltIndex = '1'; static const String phonePayapiEndpoint = '/pg/v1/pay'; static const String phonePayAppId = '57dc384d2dd8497d822a571d650a0bf2'; static const String phonePayMerchentId = 'ADVITHAONLINE'; static const String phonePayenvironment = 'PRODUCTION'; static const String phonePayPackgeName = 'com.phonepe.app'; this is my basic function regarding integration

On Fri, 1 Dec 2023 at 12:31, hitanshu1 @.***> wrote:

can share your code

— Reply to this email directly, view it on GitHub https://github.com/PhonePe/phonepe-pg-sdk-flutter/issues/11#issuecomment-1835571746, or unsubscribe https://github.com/notifications/unsubscribe-auth/AZNH7HLVYXIGUP2AW6RINR3YHF6FBAVCNFSM6AAAAABACLNA3GVHI2DSMVQWIX3LMV43OSLTON2WKQ3PNVWWK3TUHMYTQMZVGU3TCNZUGY . You are receiving this because you authored the thread.Message ID: @.***>

AlthafMjeelani commented 12 months ago

any update about this issue

RAJ-BODA commented 11 months ago

i have checked this issue deeper there is mistake in plugin file android/src/main/kotlin/com/phonepe/phonepe_payment_sdk/PhonePePaymentSdk.kt: line 113

if (resultCode != Activity.RESULT_CANCELED) is wrong condition because it should be something like this if (resultCode == Activity.RESULT_SUCCESS)

/**
     * This method gets called everytime from the app who has opened intent using startActivityOnResult()
     * Return true, If B2B_PG (725) & Container (101) which are phonepe payment request codes, we will be doing response handling.
     * Return false, if some other request code comes as it's not phonepe related code.
     */
    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?): Boolean {
        logInfo("onActivityResult: requestCode:$requestCode resultCode:$resultCode, data: ${data.convertResultToString()}")
        return try {
            if (requestCode == B2B_PG || requestCode == CONTAINER) {
                if (resultCode != Activity.RESULT_CANCELED)
                    result.success(hashMapOf(STATUS to GlobalConstants.Response.SUCCESS))
                else
                    result.success(hashMapOf(STATUS to FAILURE, ERROR to data.convertResultToString()))
                true
            } else
                false
        } catch (ex: Exception) {
            logInfo("Exception: ${ex.localizedMessage}")
            false
        }
    }
NitinVermaPpe commented 8 months ago

hi @AlthafMjeelani , can you please try with latest plugin version and go through PhonePe Developer Docs

please react out to merchant-integration@phonepe.com if you still face any issue