Skip to content
This repository has been archived by the owner on Aug 8, 2022. It is now read-only.

The payment appears to be successful even if it has not been fulfilled #5

Open
xDeltaReload opened this issue Mar 12, 2021 · 0 comments

Comments

@xDeltaReload
Copy link

xDeltaReload commented Mar 12, 2021

Hello!
I used the code here for my application in Kotlin. I would like to know if there is any method by which I could listen to what errors the application receives back, because checkoutSummary.text = "Thank you for your payment" happens even if there are not enough funds on the card or other errors occur.

I would like something to happen when the payment is successful, and when something else happens about the payment, something else happens. In my code, regardless of the result, my code does the same thing ...

I don't know if I did something wrong or if there isn't something implemented to listen to possible problems or maybe even who knows, a bug ....
I hope you can help me solve this problem ... Thanks in advance

My whole fragment(simplified)
`class MemBuyFragment : Fragment() {

private lateinit var paymentSession: PaymentSession
private lateinit var selectedPaymentMethod: PaymentMethod
private val stripe: Stripe by lazy {
    Stripe(
        requireContext(),
        PaymentConfiguration.getInstance(requireContext()).publishableKey
    )
}
private val PUBLISHABLE_KEY = "xxxx"



override fun onCreateView(
    inflater: LayoutInflater, container: ViewGroup?,
    savedInstanceState: Bundle?
): View? {
    // Inflate the layout for this fragment
    return inflater.inflate(R.layout.fragment_mem_buy, container, false)
}

override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
    super.onViewCreated(view, savedInstanceState)

        startProgress("Loading...")

        ....

        buyBtn.setOnClickListener {
                try {
                    confirmPayment(selectedPaymentMethod.id!!)
             
                } catch (e: UninitializedPropertyAccessException) {
                    errorPaymentTV.text = "Select a payment method!"
                    errorPaymentTV.visibility = View.VISIBLE
                    return@setOnClickListener
                }


        }
        paymentMethodTV.setOnClickListener {
            // Create the customer session and kick start the payment flow
            paymentSession.presentPaymentMethodSelection()
        }


        .... loading user data....
}



private fun checkForPermission() {

		... location permission...
}


private fun setupPaymentSession() {
    PaymentConfiguration.init(requireContext(), PUBLISHABLE_KEY)
    // Setup Customer Session
    CustomerSession.initCustomerSession(requireContext(), FirebaseEphemeralKeyProvider())
    // Setup a payment session
    paymentSession = PaymentSession(
        this, PaymentSessionConfig.Builder()
            .setShippingInfoRequired(false)
            .setShippingMethodsRequired(false)
            .setBillingAddressFields(BillingAddressFields.None)
            .setShouldShowGooglePay(false)
            .setCanDeletePaymentMethods(true)
            .build()
    )

    paymentSession.init(
        object : PaymentSession.PaymentSessionListener {
            override fun onPaymentSessionDataChanged(data: PaymentSessionData) {

                if (data.isPaymentReadyToCharge) {
                    buyBtn.visibility = View.VISIBLE
                    Log.d("PaymentSession", "Ready to charge");
                    errorPaymentTV.visibility = View.GONE
                    buyBtn.isEnabled = true

                    data.paymentMethod?.let {
                        // Log.d("PaymentSession", "PaymentMethod $it selected")
                        paymentMethodTV.text =
                            "Payment method selected!"
                        selectedPaymentMethod = it
                    }
                }

            }

            override fun onCommunicatingStateChanged(isCommunicating: Boolean) {
                Log.d("PaymentSession", "isCommunicating $isCommunicating")
            }

            override fun onError(errorCode: Int, errorMessage: String) {
                Log.e("PaymentSession", "onError: $errorCode, $errorMessage")
            }
        }
    )

}

private fun confirmPayment(paymentMethodId: String) {
    startProgress("Processing the payment...")
    buyBtn.isEnabled = false

    val paymentCollection = Firebase.firestore.collection("stripe_customers").document(data.uid).collection("payments")

    // Add a new document with a generated ID
        paymentCollection.add(
            hashMapOf(
                "amount" to 5000,
                "currency" to "ron"
            )
        )

        .addOnSuccessListener { documentReference ->
            paymentView.visibility = View.GONE

            Log.d("payment", "DocumentSnapshot added with ID: ${documentReference.id}")
            documentReference.addSnapshotListener { snapshot, e ->
                if (e != null) {
                    Log.w("payment", "Listen failed.", e)
                    paymentView.visibility = View.VISIBLE
                    errorPaymentTV.text = "error $e"
                    errorPaymentTV.visibility = View.VISIBLE
                    return@addSnapshotListener
                }

                if (snapshot != null && snapshot.exists()) {
                    Log.d("payment", "Current data: ${snapshot.data}")
                    val clientSecret = snapshot.data?.get("client_secret")
                    Log.d("payment", "Create paymentIntent returns $clientSecret")
                    clientSecret?.let {
                        stripe.confirmPayment(this, ConfirmPaymentIntentParams.createWithPaymentMethodId(paymentMethodId, (it as String)))

                       ...save user theUserPaid = true in database...

                        val ref = FirebaseDatabase.getInstance().reference.child("users").child(data.uid)
                        ref.child("userStatus").setValue(3)

                        Toast.makeText(requireContext(), "Succesful payment!!!!", Toast.LENGTH_LONG).show()

		    val intent = Intent(requireContext(), MainActivity()::class.java)
		   startActivity(intent)
                        activity?.finish()
                    }
                } else {
                    Log.e("payment", "Current payment intent : null")
                    buyBtn.isEnabled = true
                }
            }
        }
        .addOnFailureListener {
            hideProgress()
            paymentView.visibility = View.VISIBLE
            Log.w("payment", "Error adding document", e)
            errorPaymentTV.text = "Error $e"
            buyBtn.isEnabled = true
        }
}

override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
    super.onActivityResult(requestCode, resultCode, data)

    if (requestCode == 101) {
        checkForPermission()
    }

    paymentSession.handlePaymentData(requestCode, resultCode, data ?: Intent())
	
    buyBtn.visibility = View.VISIBLE

}


private fun startProgress(message: String) {

    paymentView.visibility = View.GONE

    loadingView.visibility = View.VISIBLE
    loadingTV.text = message

}

private fun hideProgress() {

    loadingView.visibility = View.GONE
}

private fun openSettings() {
    val intent = Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS)
    val uri: Uri = Uri.fromParts("package", activity?.packageName, null)
    intent.data = uri
    startActivityForResult(intent, 101)
}

}`

Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant