iOS Development

ios – Node Js error Can not learn property ‘cut back’ of undefined with SwiftUI

I’ve node js server hosted into Glitch and I’m utilizing specific model . I additionally added the packages for Stripe and cros . I’m making HTTP request kind IOS app which is developed into swiftUI (Buying cart app). I’ve added the stripe into my SwiftUI undertaking. I’m following this tutorial https://www.youtube.com/watch?v=De7EL_1jv0c. Right here is the glitch server hyperlink https://glitch.com/ to host the node js server . I utilizing the general public key throughout the request to trade the key key. The issue is I’ve having this error into Glitch server console ..

(node:1314) UnhandledPromiseRejectionWarning: TypeError: Can not learn property ‘cut back’ of undefined
at calculateOrderAmount (/app/server.js:11:23)

Tis perform produce the error saying the cut back not be learn . This perform calculating the full .

const calculateOrderAmount = gadgets => {

  const complete = gadgets.cut back((earlier, present) => {
    return earlier.value + present.value
  })
  return complete * 100;
};

Right here is the node js server code ..

const specific = require("specific");
const app = specific();
// That is your check secret API key.
const stripe = require("stripe")("your public key kind stripe");

app.use(specific.static("public"));
app.use(specific.json());

const calculateOrderAmount = gadgets => {
  
  const complete = gadgets.cut back((earlier, present) => {
    return earlier.value + present.value
  })
  return complete * 100;
};

app.publish("/create-payment-intent", async (req, res) => {
  const { gadgets } = req.physique;

  // Create a PaymentIntent with the order quantity and foreign money
  const paymentIntent = await stripe.paymentIntents.create({
    quantity: calculateOrderAmount(gadgets),
    foreign money: "gbp",
    // Within the newest model of the API, specifying the `automatic_payment_methods` parameter is non-compulsory as a result of Stripe allows its performance by default.
    automatic_payment_methods: {
      enabled: true,
    },
  });

 res.ship({
    clientSecret: paymentIntent.client_secret,
  });
});

app.hear(8080, () => console.log("Node server listening on port 8080!"));

Right here is my Swiftui foremost.app code ..

import SwiftUI
import Firebase
import Stripe

@foremost
struct DemoEcommerceApp: App {
    @StateObject var viewModel = AuthViewModel()
    @StateObject var order = Order()

    init() {
        FirebaseApp.configure()
        StripeAPI.defaultPublishableKey = "Stripe public key"
    }
    var physique: some Scene {
        WindowGroup {
           ContentViewOne()
                .environmentObject(viewModel)
                .environmentObject(order)
        }
    }
}

Right here is the product.

 @Revealed var merchandise = [Product]()

Json.

// MARK: - Product
struct Product: Codable, Hashable, Identifiable {
    let id: Int
    let title: String
    var value, amount, complete: Int
    let discountPercentage: Double
    let discountedPrice: Int
    let thumbnail: String
}

Right here is my non-public perform to begin making fee ..

extension OrderView {

    non-public func startCheckout(completion: @escaping (String?) -> Void) {

        let url = URL(string: "https://rogue-quartz-ounce.glitch.me/create-payment-intent")!

        var request = URLRequest(url: url)
        request.httpMethod = "POST"
        request.setValue("utility/json", forHTTPHeaderField: "Content material-Kind")
        request.httpBody = strive! JSONEncoder().encode(order.merchandise)

        URLSession.shared.dataTask(with: request) { knowledge, response, error in

            guard let knowledge = knowledge, error == nil,
                  (response as? HTTPURLResponse)?.statusCode == 200
            else {
                completion(nil)
                print(error?.localizedDescription)
                return
            }

            let checkoutIntentResponse = strive? JSONDecoder().decode(CheckoutIntentResponse.self, from: knowledge)
            completion(checkoutIntentResponse?.clientSecret)

        }.resume()

    }
}

Right here is my pay perform ..

extension OrderView {

    non-public func pay() {

        guard let clientSecret = PaymentConfig.shared.paymentIntentClientSecret else {
            return
        }

        let paymentIntentParams = STPPaymentIntentParams(clientSecret: clientSecret)
        paymentIntentParams.paymentMethodParams = paymentMethodParams

        paymentGatewayController.submitPayment(intent: paymentIntentParams) { standing, intent, error in

            change standing {
                case .failed:
                    message = "Failed"
                case .canceled:
                    message = "Cancelled"
                case .succeeded:
                    message = "Your fee has been efficiently accomplished!"
            }

        }
    }
}

Right here is the API response code ..

import Basis


struct CheckoutIntentResponse: Decodable {
    let clientSecret: String
}

Right here is the singleton class ..

import Basis

class PaymentConfig {

    var paymentIntentClientSecret: String?
    static var shared: PaymentConfig = PaymentConfig()

    non-public init() { }
}

Right here is the gateway controller ..

import Basis
import UIKit
import Stripe

class PaymentGatewayController: UIViewController {


    func submitPayment (intent : STPPaymentIntentParams, completion: @escaping (STPPaymentHandlerActionStatus, STPPaymentIntent?, NSError?) -> Void) {
        let paymentHandler = STPPaymentHandler.shared()
        paymentHandler.confirmPayment(intent, with: self) { (standing, intent, error) in
            completion(standing, intent, error)
        }
    }
}

extension PaymentGatewayController: STPAuthenticationContext {
    func authenticationPresentingViewController() -> UIViewController {
        return self
    }
}

Right here is the swiftui view code ..

@State non-public var message: String = ""
    @State non-public var isSuccess: Bool = false
    @State non-public var paymentMethodParams: STPPaymentMethodParams?
    let paymentGatewayController = PaymentGatewayController()

       var physique: some View {

        NavigationStack {
            
            Listing {
                Part {
// Stripe Credit score Card TextField Right here
             STPPaymentCardTextField.Representable.init(paymentMethodParams:        $paymentMethodParams)
                    } header: {
                        Textual content("Cost Data")
                    }
                    HStack {
                        Spacer()
                        Button("Pay") {
                            startCheckout { clientSecret in

                                PaymentConfig.shared.paymentIntentClientSecret = clientSecret
                                self.pay()
                            }

                        }.buttonStyle(.plain)
                        Spacer()
                    }

                }
                HStack {
                    Textual content(message)
                        .font(.headline)
                }
}
}
}

Credit: www.ismmailgsm.com

Leave a Reply

Your email address will not be published. Required fields are marked *

Back to top button