0

I am working on using cloud code to integrate Stripe payment in Parse.com and using Back4App for my android app. I am writing the cloud code in javascript and I'm having some issues displaying all my queried results from the checkout cart.

For now, I am just trying to retrieve each cartItem and print out its item name. But eventually, I am trying to update each item quantity in the database when the user has clicked buy.

For example:

  • user1 has cart items: item A with quantity 2 for $10 and item B with quantity 2 for $8.

  • user2 has cart items: itemA with quantity 2 for $10.

  • In the parse.com database, it shows item A with total orders as 4 and item B with total orders of 2.

I've already created my database in parse.com and have written the java code for my app but I'm failing to understand how to write cloud code and looping through each cart item.

I am sorry if the code is bad. I'm pretty much teaching myself how to program and javascript is completely new to me. If you could please point me in the right direction, I am sure I will figure the rest out. Thank you.

Right now, in my cart for user1 I have cartItems[steak, curry]. But when i run the cloud code, it is displaying only curry and not steak. I want it to display all the items in the cart

The way I have it set up is a button from CartActivity.java sends data over to paymentActivity.java. And inside paymentActivity.java is where I process the cloud code.

CartActivity.java

import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import java.util.ArrayList;

public class CartActivity extends AppCompatActivity {

    ArrayList<String> myCartItems;
    ArrayList<String> myCartItemQuantity;
    ArrayList<String> myCartItemPrice;

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

        displayCart();

    }

    private void displayCart() {
        // recieving data from MainActivity.class
        myCartItems = getIntent().getExtras().getStringArrayList("cartItems");
         myCartItemQuantity = getIntent().getExtras().getStringArrayList("itemQuantities");
        myCartItemPrice = getIntent().getExtras().getStringArrayList("itemPrices");

        Log.i("myCart ", "items: " + String.valueOf(myCartItems) + "\n" +
                "itemPrices: " + String.valueOf(myCartItemPrice) + "\n" +
                "itemQuantity: " + String.valueOf(myCartItemQuantity));

        LinearLayout linearLayoutVert = findViewById(R.id.linearLayout);
        for (int i = 0; i < myCartItems.size(); i++) {
            LinearLayout linearLayoutHor = new LinearLayout(getApplicationContext());
            linearLayoutHor.setOrientation(LinearLayout.HORIZONTAL);
            linearLayoutVert.addView(linearLayoutHor);

            TextView itemQuantity = new TextView(getApplicationContext());
            TextView item = new TextView(getApplicationContext());
            TextView itemPrice = new TextView(getApplicationContext());

            linearLayoutHor.addView(itemQuantity);
            linearLayoutHor.addView(item);
            linearLayoutHor.addView(itemPrice);

            itemQuantity.setText(myCartItemQuantity.get(i));
            item.setText(myCartItems.get(i));
            itemPrice.setText(myCartItemPrice.get(i));

            //ImageView Setup
            ImageView imageView = new ImageView(this);
            imageView.setImageResource(R.drawable.ic_trash);
            linearLayoutHor.addView(imageView);

        }
    }



public void toPaymentGateway(View view) {
        Intent paymentIntent = new Intent(getApplicationContext(), paymentActivity.class);
        paymentIntent.putExtra("cartItems", myCartItems);
        paymentIntent.putExtra("cartItemPrice", myCartItemPrice);
        paymentIntent.putExtra("cartItemQuantity", myCartItemQuantity);
        startActivity(paymentIntent);
    }

}

paymentActivity.java

package com.example.a1994m.doorstepsdelivery;

import android.app.ProgressDialog;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

import com.parse.FunctionCallback;
import com.parse.Parse;
import com.parse.ParseCloud;
import com.parse.ParseException;
import com.parse.ParseUser;
import com.stripe.android.Stripe;
import com.stripe.android.TokenCallback;
import com.stripe.android.model.Card;
import com.stripe.android.model.Token;

import java.util.ArrayList;
import java.util.HashMap;

import static com.example.a1994m.doorstepsdelivery.TestStripe.BACK4PAPP_API;
import static com.example.a1994m.doorstepsdelivery.TestStripe.CLIENT_KEY;

public class paymentActivity extends AppCompatActivity {

    ArrayList<String> myCartItems;
    ArrayList<String> myCartItemQuantity;
    ArrayList<String> myCartItemPrice ;
    ParseUser currentUser = ParseUser.getCurrentUser();

    public static final String PUBLISHABLE_KEY = "_________";
    public static final String APPLICATION_ID = "____________";
    public static final String CLIENT_KEY = "_____________";
    public static final String BACK4PAPP_API = "https://parseapi.back4app.com/";
    private Card card;
    private ProgressDialog progress;
    private Button purchase;

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

        // Connect to Your Back4app Account
        Parse.initialize(new Parse.Configuration.Builder(this)
                .applicationId(APPLICATION_ID)
                .clientKey(CLIENT_KEY)
                .server(BACK4PAPP_API).build());
        Parse.setLogLevel(Parse.LOG_LEVEL_VERBOSE);

//         Create a demo test credit Card
//         You can pass the payment form data to create a Real Credit card
//         But you need to implement youself.

        card = new Card(
                "344776435490016", //card number
                05, //expMonth
                2021,//expYear
                "216"//cvc
        );
        progress = new ProgressDialog(this);
        purchase = (Button) findViewById(R.id.purchase);
        purchase.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
//                buy();
                charge();
                Log.i("redirecting...", "BUTTON HAS BEEN CLICKED");
            }
        });

        // recieving data from CartActivity.class
         myCartItems = getIntent().getExtras().getStringArrayList("cartItems");
         myCartItemQuantity = getIntent().getExtras().getStringArrayList("cartItemQuantity");
         myCartItemPrice = getIntent().getExtras().getStringArrayList("cartItemPrice");

        Log.i("PaymentGateItems ", "items: " + String.valueOf(myCartItems) + "\n" +
                "itemPrices: " + String.valueOf(myCartItemPrice) + "\n" +
                "itemQuantity: " + String.valueOf(myCartItemQuantity));
    }

//    public void placeOrder(View view){
//
//        Intent stripeIntent = new Intent(getApplicationContext(), TestStripe.class);
//        startActivity(stripeIntent);
//    }

//    private void buy(){
//        boolean validation = card.validateCard();
//        if(validation){
//            startProgress("Validating Credit Card");
//            new Stripe(this).createToken(
//                    card,
//                    PUBLISHABLE_KEY,
//                    new TokenCallback() {
//                        @Override
//                        public void onError(Exception error) {
//                            Log.d("Stripe",error.toString());
//                        }
//
//                        @Override
//                        public void onSuccess(Token token) {
//                            finishProgress();
//                            charge(token);
//                        }
//                    });
//        } else if (!card.validateNumber()) {
//            Log.d("Stripe","The card number that you entered is invalid");
//        } else if (!card.validateExpiryDate()) {
//            Log.d("Stripe","The expiration date that you entered is invalid");
//        } else if (!card.validateCVC()) {
//            Log.d("Stripe","The CVC code that you entered is invalid");
//        } else {
//            Log.d("Stripe","The card details that you entered are invalid");
//        }
//    }

//    private void charge(Token cardToken){
//        HashMap<String, Object> params = new HashMap<String, Object>();
//
//        Log.i("items: ", String.valueOf(myCartItems));
//
//        params.put("quantity", myCartItemQuantity);
//        params.put("price", myCartItemPrice);
//        params.put("ItemName", myCartItems);
////        params.put("ItemName", "Pancake");
//        params.put("cardToken", cardToken.getId());
//        params.put("name",currentUser.getUsername());
////        params.put("name","Dominic Wong");
//        params.put("email",currentUser.getEmail());
////        params.put("email","dominwong4@gmail.com");
//        params.put("address","HIHI"); // needs input from billing address on card
//        params.put("zip","99999"); // needs input from billing address on card
//        params.put("city_state","CA"); // needs input from billing addresss on card
//        startProgress("Purchasing Item");
//        ParseCloud.callFunctionInBackground("purchaseItem", params, new FunctionCallback<Object>() {
//            public void done(Object response, ParseException e) {
//                finishProgress();
//                if (e == null) {
//                    Log.d("Cloud Response", "There were no exceptions! " + response.toString());
//                    Toast.makeText(getApplicationContext(),
//                            "Item Purchased Successfully ",
//                            Toast.LENGTH_LONG).show();
//                } else {
//                    Log.d("Cloud Response", "Exception: " + e);
//                    Toast.makeText(getApplicationContext(),
//                            e.getMessage().toString(),
//                            Toast.LENGTH_LONG).show();
//                }
//            }
//        });
//    }

    private void charge(){
        HashMap<String, Object> params = new HashMap<String, Object>();

        Log.i("items: ", String.valueOf(myCartItems));

        params.put("quantity", myCartItemQuantity);
        params.put("price", myCartItemPrice);
        params.put("ItemName", myCartItems);
//        params.put("ItemName", "Pancake");
//        params.put("cardToken", cardToken.getId());
        params.put("name",currentUser.getUsername());
//        params.put("name","Dominic Wong");
        params.put("email",currentUser.getEmail());
//        params.put("email","dominwong4@gmail.com");
        params.put("address","HIHI"); // needs input from billing address on card
        params.put("zip","99999"); // needs input from billing address on card
        params.put("city_state","CA"); // needs input from billing addresss on card
        startProgress("Purchasing Item");
        ParseCloud.callFunctionInBackground("purchaseItem", params, new FunctionCallback<Object>() {
            public void done(Object response, ParseException e) {
                finishProgress();
                if (e == null) {
                    Log.d("Cloud Response", "There were no exceptions! " + response.toString());
                    Toast.makeText(getApplicationContext(),
                            "Item Purchased Successfully ",
                            Toast.LENGTH_LONG).show();
                } else {
                    Log.d("Cloud Response", "Exception: " + e);
                    Toast.makeText(getApplicationContext(),
                            e.getMessage().toString(),
                            Toast.LENGTH_LONG).show();
                }
            }
        });
    }

    private void startProgress(String title){
        progress.setTitle(title);
        progress.setMessage("Please Wait");
        progress.show();
    }

    private void finishProgress(){
        progress.dismiss();
    }
}

Cloud Code:

var Stripe = require("stripe")("sk_test_rU8GCiz0tkNB02ZbcsXP3b2a");
Parse.Cloud.define("purchaseItem", function (request, response) {
    var item, order;
    var total = 0;

    var CartItems = request.params.ItemName;
    var CartPrice = request.params.price;
    var CartItemQuantity = request.params.quantity;

    var cartQuery = new Parse.Query('Item');

    for(var i=0; i<CartItems.length; i++){

        cartQuery.equalTo('ItemName', CartItems[i]);

        cartQuery.find()
            .then(function (results) {
                for (var result of results) {
                    response.success("got the items " + 
                    result.get("ItemName"));
                }
            })
            .catch(function (error) {
                response.error("could not get the items " + error);
            });
    }
});
  • Could you maybe put together a JSFiddle page that isn't working? I'd be happy to take a look, this just looks like an incomplete example, without enough information to go on. – clint Jan 26 '19 at 16:10
  • @clint Hi clint, i edited my post to try to make it more clearer. Does this help? I don't know how to use JsFiddle because I don't have any html or css too add – Bryan Nguyen Jan 26 '19 at 18:03

1 Answers1

1

You should only call response.success once. Subsequent calls will be ignored. You can try something like this.

cartQuery.find()
        .then(function (results) {
            var items = [];
            for (var result of results) {
                items.push(result.get("ItemName"));

            }
            response.success(JSON.stringify(items));
        })
        .catch(function (error) {
            response.error("could not get the items " + error);
        });

This will respond with the items in an array form. e.g ["steak", "curry"] You should then process this in the client side. e.g using JSONArray

James Falade
  • 189
  • 2
  • 5