Quantcast
Channel: Active questions tagged paypal - Stack Overflow
Viewing all articles
Browse latest Browse all 478

Firebase Cloud Function for PayPal Payouts

$
0
0

I'm having an issue with my Firebase Cloud Function for processing PayPal payouts. Below is the sequence of events that happens when I execute my current code:

User presses the withdraw button.Buttons (PayPal) are disabled.The user sees a "Please wait while we process the transaction" loading screen.The balance flashes as $0.00 for a split second then goes back to the user's actual balance.The buttons light up again, and the "Please wait while we process the transaction" message is shown.The message disappears and the buttons are still enabled.A message "Payment Successful: Your payout has been successfully initiated!" is shown.At the same time, the buttons are disabled, and the balance is updated to $0.00.Issue:The buttons light up again halfway through the withdrawal process when the status changes to "PENDING" instead of staying disabled until the payout is either successful or fails.

Desired Flow:

User presses the withdraw button.Buttons (PayPal) are disabled and should only be re-enabled if the payout fails.User should see a "Please wait while we process the transaction" loading screen while the transaction is processing.Only when the payout is successful:The user should see a message that says "Payment Successful".Buttons should stay disabled.User's balance should be updated to $0.00.

Here is my current Cloud Function code:

exports.withdrawFunds = functions.https.onCall(async (data, context) => {    const { method, account, amount, userUID } = data;    if (!context.auth) {        throw new functions.https.HttpsError('unauthenticated', 'User must be authenticated.');    }    const PAYPAL_CLIENT_ID = 'YOUR_PAYPAL_CLIENT_ID';    const PAYPAL_SECRET = 'YOUR_PAYPAL_SECRET';    const PAYPAL_API = 'https://api.sandbox.paypal.com';    let recipientType = method === 'PayPal' ? "EMAIL" : "USER_HANDLE";    let recipientWallet = method === 'PayPal' ? "PAYPAL" : "Venmo";    let payoutRequest = {        sender_batch_header: {            email_subject: "You have a payment",        },        items: [{            recipient_type: recipientType,            amount: {                value: amount,                currency: "USD"            },            receiver: account,            note: "Thank you for using our service!",            sender_item_id: userUID,            recipient_wallet: recipientWallet        }]    };    try {        const authResponse = await axios({            url: `${PAYPAL_API}/v1/oauth2/token`,            method: 'post',            headers: {'Accept': 'application/json','Accept-Language': 'en_US',            },            auth: {                username: PAYPAL_CLIENT_ID,                password: PAYPAL_SECRET            },            params: {'grant_type': 'client_credentials'            }        });        const accessToken = authResponse.data.access_token;        const payoutResponse = await axios({            url: `${PAYPAL_API}/v1/payments/payouts`,            method: 'post',            headers: {'Content-Type': 'application/json','Authorization': `Bearer ${accessToken}`            },            data: payoutRequest        });        const payoutBatchId = payoutResponse.data.batch_header.payout_batch_id;        // Start checking the payout status periodically        setTimeout(() => checkPayoutStatus(userUID, payoutBatchId, accessToken), 5000);        return { success: true, batchId: payoutBatchId };    } catch (error) {        console.error('Error during payout:', error.response ? error.response.data : error.message);        throw new functions.https.HttpsError('internal', 'Unable to complete the withdrawal.');    }});async function checkPayoutStatus(userUID, payoutBatchId, accessToken) {    const PAYPAL_API = 'https://api.sandbox.paypal.com';    try {        const statusResponse = await axios({            url: `${PAYPAL_API}/v1/payments/payouts/${payoutBatchId}`,            method: 'get',            headers: {'Content-Type': 'application/json','Authorization': `Bearer ${accessToken}`            }        });        const batchStatus = statusResponse.data.batch_header.batch_status;        // Update Firestore with the new status        await admin.firestore().collection('playerBalances').doc(userUID).update({            status: batchStatus,            timestamp: admin.firestore.FieldValue.serverTimestamp()        });        // If status is still PENDING, check again after a delay        if (batchStatus === 'PENDING') {            setTimeout(() => checkPayoutStatus(userUID, payoutBatchId, accessToken), 5000); // Check again in 5 seconds        } else if (batchStatus === 'SUCCESS') {            await admin.firestore().collection('playerBalances').doc(userUID).update({                balance: 0,                status: "SUCCESS"            });        }    } catch (error) {        console.error('Error during payout status check:', error.response ? error.response.data : error.message);        // Retry in case of error        setTimeout(() => checkPayoutStatus(userUID, payoutBatchId, accessToken), 5000); // Retry in 5 seconds    }}

Here is my current iOS ViewController code:

import UIKitimport FirebaseAuthimport FirebaseFirestoreimport FirebaseFunctionsclass WinningsViewController: BaseViewController {    // UI Elements    var balanceLabel: UILabel!    var withdrawPaypalButton: UIButton!    // Firestore listener    var balanceListener: ListenerRegistration?    var statusListener: ListenerRegistration?    // Reference to the Cloud Functions    lazy var functions = Functions.functions()    override func viewDidLoad() {        super.viewDidLoad()        view.backgroundColor = UIColor { traitCollection in            switch traitCollection.userInterfaceStyle {            case .dark:                return UIColor(hex: "#02272D")            default:                return .white            }        }        title = "Winnings"        // Set up the UI        setupUI()        // Fetch and display the balance        setupBalanceListener()    }    deinit {        // Remove the Firestore listener when the view controller is deallocated        balanceListener?.remove()        statusListener?.remove()    }    func setupUI() {        // Balance Label        balanceLabel = UILabel()        balanceLabel.text = "Balance: $0.00"        balanceLabel.font = UIFont.boldSystemFont(ofSize: 24)        balanceLabel.textAlignment = .center        balanceLabel.translatesAutoresizingMaskIntoConstraints = false        view.addSubview(balanceLabel)        // Withdraw Paypal Button        withdrawPaypalButton = UIButton(type: .system)        withdrawPaypalButton.setTitle("Withdraw With PayPal", for: .normal)        withdrawPaypalButton.layer.cornerRadius = 10        withdrawPaypalButton.titleLabel?.font = UIFont.boldSystemFont(ofSize: 18)        withdrawPaypalButton.addTarget(self, action: #selector(withdrawPaypalButtonTapped), for: .touchUpInside)        withdrawPaypalButton.translatesAutoresizingMaskIntoConstraints = false        view.addSubview(withdrawPaypalButton)        // Constraints        NSLayoutConstraint.activate([            balanceLabel.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor, constant: 100),            balanceLabel.centerXAnchor.constraint(equalTo: view.centerXAnchor),            withdrawPaypalButton.topAnchor.constraint(equalTo: balanceLabel.bottomAnchor, constant: 50),            withdrawPaypalButton.centerXAnchor.constraint(equalTo: view.centerXAnchor),            withdrawPaypalButton.widthAnchor.constraint(equalToConstant: 250),            withdrawPaypalButton.heightAnchor.constraint(equalToConstant: 50)        ])        // Initially disable the buttons if the balance is $0        updateButtonState(balance: 0.0)    }    @objc func withdrawPaypalButtonTapped() {        let alertController = UIAlertController(title: "Withdraw with PayPal", message: "Please enter your PayPal email address", preferredStyle: .alert)        alertController.addTextField { textField in            textField.placeholder = "PayPal email"        }        let withdrawAction = UIAlertAction(title: "Withdraw", style: .default) { [weak self] _ in            guard let email = alertController.textFields?.first?.text, !email.isEmpty else {                print("No email entered")                return            }            self?.disableWithdrawButtons()            self?.showLoadingScreen()            self?.initiatePaypalPayout(recipientEmail: email)        }        let cancelAction = UIAlertAction(title: "Cancel", style: .cancel, handler: nil)        alertController.addAction(withdrawAction)        alertController.addAction(cancelAction)        present(alertController, animated: true, completion: nil)    }    func setupBalanceListener() {        guard let user = Auth.auth().currentUser else {            print("No user is logged in.")            return        }        let userUID = user.uid        let db = Firestore.firestore()        balanceListener = db.collection("playerBalances").document(userUID).addSnapshotListener { [weak self] (document, error) in            if let document = document, document.exists {                if let balance = document.data()?["balance"] as? Double {                    let numberFormatter = NumberFormatter()                    numberFormatter.numberStyle = .currency                    numberFormatter.maximumFractionDigits = 2                    numberFormatter.minimumFractionDigits = 2                    if let formattedBalance = numberFormatter.string(from: NSNumber(value: balance)) {                        self?.balanceLabel.text = "Balance: \(formattedBalance)"                    } else {                        self?.balanceLabel.text = "Balance: $0.00"                    }                    self?.updateButtonState(balance: balance)                } else {                    print("Error fetching balance: Balance field does not exist")                }            } else {                print("Error fetching balance: \(String(describing: error))")            }        }    }    func updateButtonState(balance: Double) {        let isEnabled = balance > 0.0        withdrawPaypalButton.isEnabled = isEnabled        let buttonBackgroundColor: UIColor = isEnabled ? UIColor { traitCollection in            switch traitCollection.userInterfaceStyle {            case .dark:                return UIColor(hex: "#00CC88")            default:                return UIColor(hex: "#00C897")            }        } : .lightGray        let buttonTitleColor: UIColor = isEnabled ? .systemBlue : .darkGray        withdrawPaypalButton.backgroundColor = buttonBackgroundColor        withdrawPaypalButton.setTitleColor(buttonTitleColor, for: .normal)    }    func disableWithdrawButtons() {        withdrawPaypalButton.isEnabled = false        withdrawPaypalButton.backgroundColor = .lightGray        withdrawPaypalButton.setTitleColor(.gray, for: .normal)    }    func enableWithdrawButtons() {        updateButtonState(balance: Double(balanceLabel.text?.components(separatedBy: CharacterSet.decimalDigits.inverted).joined() ?? "0") ?? 0)    }    func initiatePaypalPayout(recipientEmail: String) {        guard let user = Auth.auth().currentUser else {            print("No user is logged in.")            enableWithdrawButtons()            hideLoadingScreen()            return        }        let db = Firestore.firestore()        let userUID = user.uid        db.collection("playerBalances").document(userUID).getDocument { [weak self] (document, error) in            if let document = document, document.exists, let balance = document.data()?["balance"] as? Double {                let data: [String: Any] = ["method": "PayPal","account": recipientEmail,"amount": balance,"userUID": userUID                ]                self?.functions.httpsCallable("withdrawFunds").call(data) { result, error in                    if let error = error as NSError? {                        print("Error initiating PayPal payout: \(error.localizedDescription)")                        self?.showPaymentErrorAlert(error: error.localizedDescription)                        self?.enableWithdrawButtons()                        self?.hideLoadingScreen()                    } else {                        print("Result data: \(String(describing: result?.data))")                        if let resultData = result?.data as? [String: Any], let success = resultData["success"] as? Bool, success {                            print("PayPal payout initiated successfully: \(resultData)")                            self?.setupPayoutStatusListener(userUID: userUID)                        } else {                            let errorMessage = (result?.data as? [String: Any])?["message"] as? String ?? "Unexpected error occurred."                            print("Error message: \(errorMessage)")                            self?.showPaymentErrorAlert(error: errorMessage)                            self?.enableWithdrawButtons()                            self?.hideLoadingScreen()                        }                    }                }            } else {                print("Error fetching balance: \(String(describing: error))")                self?.enableWithdrawButtons()                self?.hideLoadingScreen()            }        }    }    func setupPayoutStatusListener(userUID: String) {        let db = Firestore.firestore()        statusListener = db.collection("playerBalances").document(userUID).addSnapshotListener { [weak self] documentSnapshot, error in            guard let self = self else { return }            guard let document = documentSnapshot, document.exists else {                print("Error fetching payout status: \(String(describing: error))")                self.enableWithdrawButtons()                self.hideLoadingScreen()                return            }            if let status = document.data()?["status"] as? String {                if status == "SUCCESS" {                    // Hide loading screen and show success message                    self.updateBalanceToZero()                    self.hideLoadingScreen()                    self.showPaymentSuccessAlert()                } else if status == "FAILURE" || status != "PENDING" {                    // Hide loading screen and show error message                    self.hideLoadingScreen()                    self.showPaymentErrorAlert(error: "Payout failed.")                    // Enable withdraw buttons                    self.enableWithdrawButtons()                } else {                    // Show loading screen for "PENDING" status                    self.showLoadingScreen()                }            }        }    }    func updateBalanceToZero() {        guard let user = Auth.auth().currentUser else {            return        }        let db = Firestore.firestore()        let userUID = user.uid        db.collection("playerBalances").document(userUID).updateData(["balance": 0]) { [weak self] error in            if let error = error {                print("Error updating balance to zero: \(error.localizedDescription)")                self?.showPaymentErrorAlert(error: error.localizedDescription)                self?.enableWithdrawButtons()                self?.hideLoadingScreen()            } else {                self?.balanceLabel.text = "Balance: $0.00"                self?.updateButtonState(balance: 0.0)            }        }    }    func showPaymentSuccessAlert() {        let alertController = UIAlertController(title: "Payment Successful", message: "Your payout has been successfully initiated!", preferredStyle: .alert)        let okAction = UIAlertAction(title: "OK", style: .default, handler: nil)        alertController.addAction(okAction)        present(alertController, animated: true, completion: nil)    }    func showPaymentErrorAlert(error: String) {        let alertController = UIAlertController(title: "Payment Error", message: "There was an error initiating your payout: \(error)", preferredStyle: .alert)        let okAction = UIAlertAction(title: "OK", style: .default, handler: nil)        alertController.addAction(okAction)        present(alertController, animated: true, completion: nil)    }    func showLoadingScreen() {        let alert = UIAlertController(title: nil, message: "Please wait while we process the transaction...", preferredStyle: .alert)        let loadingIndicator = UIActivityIndicatorView(frame: CGRect(x: 10, y: 5, width: 50, height: 50))        loadingIndicator.hidesWhenStopped = true        loadingIndicator.style = .medium        loadingIndicator.startAnimating()        alert.view.addSubview(loadingIndicator)        present(alert, animated: true, completion: nil)    }    func hideLoadingScreen() {        if let presentedViewController = presentedViewController, presentedViewController is UIAlertController {            presentedViewController.dismiss(animated: true, completion: nil)        }    }}

Viewing all articles
Browse latest Browse all 478

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>