Stephany.Star
Stephany.Star

Reputation: 49

How to change pricing on stripe

Hello I am using stripe for my android app to take payments. I noticed that when I make a payment the price is always charge $14.00 and I'm guessing that is the default pricing. But I wanted to change that to something else maybe like to 5 dollars or 1 dollar. Can anyone assist me with this? Thanks in advance

//Here is my code

        payButton = findViewById(R.id.payButton);
        firebaseUser = firebaseAuth.getInstance().getCurrentUser();
        cardInputWidget = findViewById(R.id.cardInputWidget);


        String uid = FirebaseAuth.getInstance().getCurrentUser().getUid();
        final DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference("card_information").child(uid);
        final DatabaseReference update = rootRef.child(uid);

        rootRef.addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(@NonNull DataSnapshot snapshot) {

                if(snapshot.exists()){

                        String cadmium=snapshot.child("card_number").getValue(String.class);
                        String cvc=snapshot.child("cvc").getValue(String.class);
                        Integer exp_month=snapshot.child("expiration_month").getValue(Integer.class);
                       Integer exp_year=snapshot.child("expiration_year").getValue(Integer.class);
                        String postal_code=snapshot.child("postal_code").getValue(String.class);

                            cardInputWidget.setCardNumber(cadmium);


                            cardInputWidget.setCvcCode(cvc);



                            cardInputWidget.setExpiryDate(exp_month, exp_year);







                }else{

                }









            }

            @Override
            public void onCancelled(@NonNull DatabaseError error) {

            }
        });




        // Configure the SDK with your Stripe publishable key so it can make requests to Stripe
        stripe = new Stripe(
                getApplicationContext(),
                Objects.requireNonNull("pk_test_51GzvqSI4qFEpgfxS15GlPnxcrL4Sb5CZsv5AWXGPW1ihpQBTB9OPSh9nnZxY2zY71bVacdmJQ4gRxKYmCw3SCVQo00KUZF8psk")
        );
        startCheckout();


//startCheckout();





}



    private void startCheckout() {

        //amount will calculate from .00 make sure multiply by 100
        //double amount=Double.parseDouble(mAmount.getText().toString())*1;
        Map<String,Object> payMap=new HashMap<>();
        Map<String,Object> itemMap=new HashMap<>();
        List<Map<String,Object>> itemList =new ArrayList<>();
        payMap.put("currency","usd");
        itemMap.put("id","photo_subscription");
        //itemMap.put("amount",amount);
        itemList.add(itemMap);
        payMap.put("items",itemList);
        String json = new Gson().toJson(payMap);
        //Log.i("TAG", "startCheckout: "+json);

        // Create a PaymentIntent by calling the sample server's /create-payment-intent endpoint.
        MediaType mediaType = MediaType.parse("application/json; charset=utf-8");
        /*
        String json = "{"
                + "\"currency\":\"usd\","
                + "\"items\":["
                + "{\"id\":\"photo_subscription\"}"
                + "]"
                + "}";

         */

        RequestBody body = RequestBody.create(mediaType,json);
        Request request = new Request.Builder()
                .url(BACKEND_URL + "create-payment-intent")
                .post(body)
                .build();
        httpClient.newCall(request)
                .enqueue(new PayCallback(this));




        // Hook up the pay button to the card widget and stripe instance
        //Button payButton = findViewById(R.id.payButton);
        payButton.setOnClickListener((View view) -> {
            //String get_card=cardInputWidget.getCard().getAddressZip();
            //Toast.makeText(PaymentPageActivity.this, get_card, Toast.LENGTH_SHORT).show();
            PaymentMethodCreateParams params = cardInputWidget.getPaymentMethodCreateParams();
            if (params != null) {
                Map<String, String> extraParams = new HashMap<>();
                extraParams.put("setup_future_usage", "off_session");

                ConfirmPaymentIntentParams confirmParams = ConfirmPaymentIntentParams
                        .createWithPaymentMethodCreateParams(params, paymentIntentClientSecret);
                stripe.confirmPayment(this, confirmParams);
            }
        });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        // Handle the result of stripe.confirmPayment
        stripe.onPaymentResult(requestCode, data, new PaymentResultCallback(this));
    }

    public void goback(View view) {
        onBackPressed();
    }

    private static final class PayCallback implements Callback {
        @NonNull private final WeakReference<PaymentPageActivity> activityRef;
        PayCallback(@NonNull PaymentPageActivity activity) {
            activityRef = new WeakReference<>(activity);
        }
        @Override
        public void onFailure(@NonNull Call call, @NonNull IOException e) {
            final PaymentPageActivity activity = activityRef.get();
            if (activity == null) {
                return;
            }
            activity.runOnUiThread(() ->
                    Toast.makeText(
                            activity, "Error: " + e.toString(), Toast.LENGTH_LONG
                    ).show()
            );
        }
        @Override
        public void onResponse(@NonNull Call call, @NonNull final Response response)
                throws IOException {
            final PaymentPageActivity activity = activityRef.get();
            if (activity == null) {
                return;
            }
            if (!response.isSuccessful()) {
                activity.runOnUiThread(() ->
                        Toast.makeText(
                                activity, "Error: " + response.toString(), Toast.LENGTH_LONG
                        ).show()
                );
            } else {
                activity.onPaymentSuccess(response);
            }
        }
    }

    private void onPaymentSuccess(@NonNull final Response response) throws IOException {
        Gson gson = new Gson();
        Type type = new TypeToken<Map<String, String>>(){}.getType();
        Map<String, String> responseMap = gson.fromJson(
                Objects.requireNonNull(response.body()).string(),
                type

        );
        paymentIntentClientSecret = responseMap.get("clientSecret");
    }
    private final class PaymentResultCallback
            implements ApiResultCallback<PaymentIntentResult> {
        @NonNull private final WeakReference<PaymentPageActivity> activityRef;
        PaymentResultCallback(@NonNull PaymentPageActivity activity) {
            activityRef = new WeakReference<>(activity);
        }
        @Override
        public void onSuccess(@NonNull PaymentIntentResult result) {
            final PaymentPageActivity activity = activityRef.get();
            if (activity == null) {
                return;
            }
            PaymentIntent paymentIntent = result.getIntent();
            PaymentIntent.Status status = paymentIntent.getStatus();
            if (status == PaymentIntent.Status.Succeeded) {
                // Payment completed successfully
                Gson gson = new GsonBuilder().setPrettyPrinting().create();
                activity.displayAlert(
                        "Payment completed",
                        gson.toJson(paymentIntent)
                );

                String uid = FirebaseAuth.getInstance().getCurrentUser().getUid();
                final DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference("Ads");
                final DatabaseReference update = rootRef.child(uid);


                final DatabaseReference rootRef1 = FirebaseDatabase.getInstance().getReference("card_information");
                final DatabaseReference update1 = rootRef1.child(uid);


update1.child("card_number").setValue(cardInputWidget.getCard().component1());
update1.child("cvc").setValue(cardInputWidget.getCard().component2());
update1.child("expiration_month").setValue(cardInputWidget.getCard().component3());
update1.child("expiration_year").setValue(cardInputWidget.getCard().component4());
update1.child("postal_code").setValue(cardInputWidget.getCard().getAddressZip());


                Intent intent = getIntent();

                Bundle extras = intent.getExtras();


                String get_key = extras.getString("id-key");

                update.child(get_key).child("status").setValue("Paid");



                Intent intent2=new Intent(PaymentPageActivity.this,ProfileActivity.class);
                startActivity(intent2);
            } else if (status == PaymentIntent.Status.RequiresPaymentMethod) {
                // Payment failed – allow retrying using a different payment method
                activity.displayAlert(
                        "Payment failed",
                        Objects.requireNonNull(paymentIntent.getLastPaymentError()).getMessage()
                );
            }
        }
        @Override
        public void onError(@NonNull Exception e) {
            final PaymentPageActivity activity = activityRef.get();
            if (activity == null) {
                return;
            }
            // Payment request failed – allow retrying using the same payment method
            activity.displayAlert("Error", e.toString());
        }
    }

    private void displayAlert(@NonNull String title,
                              @Nullable String message) {
        AlertDialog.Builder builder = new AlertDialog.Builder(this)
                .setTitle(title)
                .setMessage(message);
        builder.setPositiveButton("Ok", null);
        builder.create().show();
    }

    @Override
    public void onBackPressed() {
        onBackPressed();
    }
}


// Backend 

const express = require("express");
const app = express();
const { resolve } = require("path");
// This is your real test secret API key.
const stripe = require("stripe")("sk_test_****");
const customer = await stripe.customers.create();


app.use(express.static("."));
app.use(express.json());

//const calculateOrderAmount = items => {
  // Replace this constant with a calculation of the order's amount
  // Calculate the order total on the server to prevent
  // people from directly manipulating the amount on the client

 //console.log(items[0].amount)
 //return items[0].amount;

 

//};

const intent = await stripe.paymentIntents.create({
  amount: 500,
  currency: 'usd',
  customer: customer.id,
});


app.post("/create-payment-intent", async (req, res) => {
  const { items } = req.body;
  const { currency } = req.body;

  // Create a PaymentIntent with the order amount and currency
  const paymentIntent = await stripe.paymentIntents.create({
   amount: calculateOrderAmount(items),
    currency: currency
  });
  res.send({
    clientSecret: paymentIntent.client_secret
  });
});

app.get("/greet", async (req, res) => {
 res.send('hello it is working');
});
const PORT= process.env.PORT || 5001;
app.listen(PORT, () => console.log('Node server listening on port $(PORT)'));

Upvotes: 0

Views: 469

Answers (1)

hmunoz
hmunoz

Reputation: 3331

On Stripe, you control what amount you want to create a payment for, with the amount parameter on a PaymentIntent: https://stripe.com/docs/api/payment_intents/create#create_payment_intent-amount

Looks like right now your backend is creating a PaymentIntent for amount: 1400 which is $14.00.

You would have to modify your backend's /create_payment_intent endpoint and modify the amount there.

Ideally, you pass some order or product ID from your Android app to your backend, where your backend then maps an amount out of that product ID (and quantity, if applicable).

Upvotes: 1

Related Questions