Afaq Khan
Afaq Khan

Reputation: 332

Telr WebView doesn't redirects me to Failed or Success Activity, Unable to Cast Status Response into Failed Status Reponse

I am implementing Telr Payment Gateway in Android. I have been facing issues while my transaction is failed or even successful the Telr's WebView doesn't redirect me to the Failed or Success Activity. And if it fails I get a crash which tells that:

java.lang.ClassCastException: com.telr.mobile.sdk.entity.response.status.StatusResponse cannot be cast to com.telr.mobile.sdk.entity.response.status.StatusResponseFailed

Following is my Payment Fragment code which has a method named "sendMessage"(which opens WebView through intent) then there is a method named "messageRequest" which requests all the required data for a transaction WebView to be set:

    private lateinit var binding: FragmentPaymentBinding
    val isSecurityEnabled = true
    val REQUEST_CODE = 100


    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        val sharedPref: SharedPreferences =
            requireContext().getSharedPreferences("telr", Context.MODE_PRIVATE)

        val ref = sharedPref.getString("ref", null)
        if (ref != null) {
            binding.btnSavedCards.visibility = View.VISIBLE
        } else {
            binding.btnSavedCards.visibility = View.GONE
        }
        binding.btnPay.setOnClickListener {
            sendMessage()
        }
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (requestCode == REQUEST_CODE &&
            resultCode == Activity.RESULT_OK
        ) {
            val paymentMethod: String = data?.getStringExtra("auth").toString()
            if (paymentMethod.equals("yes", ignoreCase = true)) {
                val status =
                    data?.getParcelableExtra<Parcelable>(WebviewActivity.PAYMENT_RESPONSE) as MobileResponse

//                TextView textView = (TextView)findViewById(R.id.text_payment_result);
//                TextView txt_code=(TextView)findViewById(R.id.txt_code);
//                txt_code.setText("Code : "+intent.getStringExtra("Code"));
//                textView.setText(textView.getText() +" : " + status.getTrace());
                //  Log.e("CODEZZZ",":"+ TelrSharedPreference.getInstance(this).getDataFromPreference("Code"));
                if (status.auth != null) {
                    status.auth.status // Authorisation status. A indicates an authorised transaction. H also indicates an authorised transaction, but where the transaction has been placed on hold. Any other value indicates that the request could not be processed.
                    status.auth.avs /* Result of the AVS check:
                                            Y = AVS matched OK
                                            P = Partial match (for example, post-code only)
                                            N = AVS not matched
                                            X = AVS not checked
                                            E = Error, unable to check AVS */
                    status.auth.code// If the transaction was authorised, this contains the authorisation code from the card issuer. Otherwise it contains a code indicating why the transaction could not be processed.
                    status.auth.message// The authorisation or processing error message.
                    status.auth.ca_valid
                    status.auth.cardcode // Code to indicate the card type used in the transaction. See the code list at the end of the document for a list of card codes.
                    status.auth.cardlast4 // The last 4 digits of the card number used in the transaction. This is supplied for all payment types (including the Hosted Payment Page method) except for PayPal.
                    status.auth.cvv/* Result of the CVV check:
                                           Y = CVV matched OK
                                           N = CVV not matched
                                           X = CVV not checked
                                           E = Error, unable to check CVV */
                    status.auth.tranref //The payment gateway transaction reference allocated to this request.
                    status.auth.card.first6 // The first 6 digits of the card number used in the transaction, only for version 2 is submitted in Tran -> Version
                    status.auth.card.country
                    status.auth.card.expiry.month
                    status.auth.card.expiry.year

                    if (binding.radioButton.isChecked) {
                        setTransactionDetails(status.auth.tranref, status.auth.cardlast4)
                    }

                }
            }
//            StatusResponse status = intent.getParcelableExtra(WebviewActivity.PAYMENT_RESPONSE);
//            if(status.getAuth()!= null) {
//                Log.d("DataVal:",  status.getAuth().getCard().getFirst6());
//                Log.d("Code", intent.getStringExtra("Code"));
//
//
//            }
        }

    }

    fun sendMessage() {
        val intent = Intent(requireContext(), WebviewActivity::class.java)

//        intent.addFlags(Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT);
//         intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        intent.putExtra(WebviewActivity.EXTRA_MESSAGE, getMobileRequest())
        intent.putExtra(
            WebviewActivity.SUCCESS_ACTIVTY_CLASS_NAME,
            "com.example.telrimplementationinandroid.SuccessTransationActivity"
        )
        intent.putExtra(
            WebviewActivity.FAILED_ACTIVTY_CLASS_NAME,
            "com.example.telrimplementationinandroid.FailedTransationActivity"
        )
        intent.putExtra(WebviewActivity.IS_SECURITY_ENABLED, isSecurityEnabled)
        //        startActivity(intent);
        startActivityForResult(intent, REQUEST_CODE)
    }


    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View {
        binding = FragmentPaymentBinding.inflate(inflater, container, false)
        return binding.root

    }

    private fun getMobileRequest(): MobileRequest {
        val mobile = MobileRequest()
        mobile.setStore(STORE_ID) // Store ID
        mobile.setKey(KEY) // Authentication Key : The Authentication Key will be supplied by Telr as part of the Mobile API setup process after you request that this integration type is enabled for your account. This should not be stored permanently within the App.
        val app = App()
        app.setId("123456789") // Application installation ID
        app.setName("TelrSDK") // Application name
        app.setUser("123456") // Application user ID : Your reference for the customer/user that is running the App. This should relate to their account within your systems.
        app.setVersion("0.0.1") // Application version
        app.setSdk("123")
        mobile.setApp(app)
        val tran = Tran()
        tran.setTest("1") //1                        // Test mode : Test mode of zero indicates a live transaction. If this is set to any other value the transaction will be treated as a test.
        tran.setType("auth") /* Transaction type
                                                            'auth'   : Seek authorisation from the card issuer for the amount specified. If authorised, the funds will be reserved but will not be debited until such time as a corresponding capture command is made. This is sometimes known as pre-authorisation.
                                                            'sale'   : Immediate purchase request. This has the same effect as would be had by performing an auth transaction followed by a capture transaction for the full amount. No additional capture stage is required.
                                                            'verify' : Confirm that the card details given are valid. No funds are reserved or taken from the card.
                                                        */
        tran.setClazz("paypage") // Transaction class only 'paypage' is allowed on mobile, which means 'use the hosted payment page to capture and process the card details'
        tran.setCartid(
            BigInteger(
                128,
                Random()
            ).toString()
        ) //// Transaction cart ID : An example use of the cart ID field would be your own transaction or order reference.
        tran.setDescription("Test Mobile API") // Transaction description
        tran.setLanguage(binding.etLanguage.text.toString())
        tran.setCurrency(binding.etCurrency.text.toString()) // Transaction currency : Currency must be sent as a 3 character ISO code. A list of currency codes can be found at the end of this document. For voids or refunds, this must match the currency of the original transaction.
        tran.setAmount(binding.etAmount.text.toString()) // Transaction amount : The transaction amount must be sent in major units, for example 9 dollars 50 cents must be sent as 9.50 not 950. There must be no currency symbol, and no thousands separators. Thedecimal part must be separated using a dot.
        //        tran.setRef("040025801054");                                // (Optinal) Previous transaction reference : The previous transaction reference is required for any continuous authority transaction. It must contain the reference that was supplied in the response for the original transaction.

        //040023303844  //030023738912
        // tran.setFirstref("030023738912");             // (Optinal) Previous user transaction detail reference : The previous transaction reference is required for any continuous authority transaction. It must contain the reference that was supplied in the response for the original transaction.
        mobile.setTran(tran)
        val billing = Billing()
        val address = Address()
        address.setCity("Dubai") // City : the minimum required details for a transaction to be processed
        address.setCountry("AE") // Country : Country must be sent as a 2 character ISO code. A list of country codes can be found at the end of this document. the minimum required details for a transaction to be processed
        address.setRegion("Dubai") // Region
        address.setLine1("SIT GTower") // Street address – line 1: the minimum required details for a transaction to be processed
        //address.setLine2("SIT G=Towe");               // (Optinal)
        //address.setLine3("SIT G=Towe");               // (Optinal)
        //address.setZip("SIT G=Towe");                 // (Optinal)
        billing.setAddress(address)
        val name = Name()
        name.setFirst("Divya") // Forename : the minimum required details for a transaction to be processed
        name.setLast("Thampi") // Surname : the minimum required details for a transaction to be processed
        name.setTitle("Mrs") // Title
        billing.setName(name)
        billing.setEmail("[email protected]") //[email protected]//[email protected] : the minimum required details for a transaction to be processed.
        billing.setPhone("0551188269")
        mobile.setBilling(billing)
        return mobile
    }

    private fun setTransactionDetails(ref: String, last4: String) {
        val sharedPref: SharedPreferences? =
            context?.applicationContext?.getSharedPreferences("telr", Context.MODE_PRIVATE)
        val editor = sharedPref?.edit()
        editor?.putString("ref", ref)
        editor?.putString("last4", last4)
        editor?.apply()
    }

Now, below are my codes for Failed and Successful Transaction Activity:

Failed Activity:

    private TextView mTextView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_failedtransaction);
    }

    @SuppressLint("SetTextI18n")
    @Override
    protected void onStart() {
        super.onStart();
        Intent intent = getIntent();
        Object object = intent.getParcelableExtra(WebviewActivity.PAYMENT_RESPONSE);
        TextView textView = (TextView) findViewById(R.id.text_payment_result2);

        if (object instanceof StatusResponseFailed) {
            StatusResponseFailed status = (StatusResponseFailed) object;
            textView.setText(textView.getText() + " : " + status.getTrace());
            TextView txt_code = (TextView) findViewById(R.id.txt_code);
            txt_code.setText(" " + status.getTrace());
            if (status.getAuth() != null) {
                status.getAuth().getStatus();   // Authorisation status. A indicates an authorised transaction. H also indicates an authorised transaction, but where the transaction has been placed on hold. Any other value indicates that the request could not be processed.
                status.getAuth().getAvs();      /* Result of the AVS check:
                                            Y = AVS matched OK
                                            P = Partial match (for example, post-code only)
                                            N = AVS not matched
                                            X = AVS not checked
                                            E = Error, unable to check AVS */
                status.getAuth().getCode();     // If the transaction was authorised, this contains the authorisation code from the card issuer. Otherwise it contains a code indicating why the transaction could not be processed.
                status.getAuth().getMessage();  // The authorisation or processing error message.
                /**
                 * Commented by Divya on 06/08/2020.
                 */
                status.getAuth().getCa_valid();  // commented Divya
                status.getAuth().getCardfirst6();
                //  status.getAuth().getCard().getExpiry();
                status.getAuth().getCardcode(); // Code to indicate the card type used in the transaction. See the code list at the end of the document for a list of card codes.
                status.getAuth().getCardlast4();// The last 4 digits of the card number used in the transaction. This is supplied for all payment types (including the Hosted Payment Page method) except for PayPal.
                status.getAuth().getCvv();      /* Result of the CVV check:
                                           Y = CVV matched OK
                                           N = CVV not matched
                                           X = CVV not checked
                                           E = Error, unable to check CVV */
                status.getAuth().getTranref(); //The payment gateway transaction reference allocated to this request.
                status.getAuth().getAvs();     /* Result of the AVS check:
                                           Y = AVS matched OK
                                           P = Partial match (for example, post-code only)
                                           N = AVS not matched
                                           X = AVS not checked
                                           E = Error, unable to check AVS */


//                status.getAuth().getCard().getCountry(); // /
//
//                status.getAuth().getCard().getExpiry().getMonth();
//                status.getAuth().getCard().getExpiry().getYear();
            }
        } else if (object instanceof String) {
            String errorMessage = (String) object;
            textView.setText(textView.getText() + " : " + errorMessage);
        }
    }

    public void closeWindow(View view) {
        this.finish();
    }

And Success Activity:

 private TextView mTextView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_successtransaction);
    }

    @Override
    protected void onStart() {
        super.onStart();
        Intent intent = getIntent();
        StatusResponse status = (StatusResponse) intent.getParcelableExtra(WebviewActivity.PAYMENT_RESPONSE);

        TextView textView = (TextView)findViewById(R.id.text_payment_result);
        TextView txt_code=(TextView)findViewById(R.id.txt_code);
        txt_code.setText("Code : "+intent.getStringExtra("Code"));
        textView.setText(textView.getText() +" : " + status.getTrace());
      //  Log.e("CODEZZZ",":"+ TelrSharedPreference.getInstance(this).getDataFromPreference("Code"));

        if(status.getAuth()!= null) {
            status.getAuth().getStatus();   // Authorisation status. A indicates an authorised transaction. H also indicates an authorised transaction, but where the transaction has been placed on hold. Any other value indicates that the request could not be processed.
            status.getAuth().getAvs();      /* Result of the AVS check:
                                            Y = AVS matched OK
                                            P = Partial match (for example, post-code only)
                                            N = AVS not matched
                                            X = AVS not checked
                                            E = Error, unable to check AVS */
            status.getAuth().getCode();     // If the transaction was authorised, this contains the authorisation code from the card issuer. Otherwise it contains a code indicating why the transaction could not be processed.
            status.getAuth().getMessage();  // The authorisation or processing error message.
            status.getAuth().getCa_valid();
            status.getAuth().getCardcode(); // Code to indicate the card type used in the transaction. See the code list at the end of the document for a list of card codes.
            status.getAuth().getCardlast4();// The last 4 digits of the card number used in the transaction. This is supplied for all payment types (including the Hosted Payment Page method) except for PayPal.
            status.getAuth().getCvv();      /* Result of the CVV check:
                                           Y = CVV matched OK
                                           N = CVV not matched
                                           X = CVV not checked
                                           E = Error, unable to check CVV */
            status.getAuth().getTranref(); //The payment gateway transaction reference allocated to this request.
            status.getAuth().getCard().getFirst6(); // The first 6 digits of the card number used in the transaction, only for version 2 is submitted in Tran -> Version
            status.getAuth().getCard().getCountry();

            status.getAuth().getCard().getExpiry().getMonth();
            status.getAuth().getCard().getExpiry().getYear();
        }
    }

    public void closeWindow(View view){
        this.finish();
    }

I have been looking for solutions but am unable to do so. Any sort of help would be highly appreciated.

Upvotes: 2

Views: 607

Answers (0)

Related Questions