Android 如何更改条带上的定价

Android 如何更改条带上的定价,android,stripe-payments,Android,Stripe Payments,您好,我正在使用stripe为我的android应用程序付款。我注意到当我付款时,价格总是14.00美元,我猜这是默认价格。但我想把它换成别的东西,比如5美元或1美元。有人能帮我吗?提前谢谢 //Here is my code payButton = findViewById(R.id.payButton); firebaseUser = firebaseAuth.getInstance().getCurrentUser(); cardInput

您好,我正在使用stripe为我的android应用程序付款。我注意到当我付款时,价格总是14.00美元,我猜这是默认价格。但我想把它换成别的东西,比如5美元或1美元。有人能帮我吗?提前谢谢

//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)'));
//这是我的代码
payButton=findViewById(R.id.payButton);
firebaseUser=firebaseAuth.getInstance().getCurrentUser();
cardInputWidget=findviewbyd(R.id.cardInputWidget);
字符串uid=FirebaseAuth.getInstance().getCurrentUser().getUid();
final DatabaseReference rootRef=FirebaseDatabase.getInstance().getReference(“卡片信息”).child(uid);
最终数据库引用更新=rootRef.child(uid);
rootRef.addValueEventListener(新的ValueEventListener(){
@凌驾
public void onDataChange(@NonNull DataSnapshot snapshot snapshot){
if(snapshot.exists()){
String=snapshot.child(“卡号”).getValue(String.class);
String cvc=snapshot.child(“cvc”).getValue(String.class);
整数exp\u month=snapshot.child(“expiration\u month”).getValue(Integer.class);
整数exp_year=snapshot.child(“到期年”).getValue(Integer.class);
String postal_code=snapshot.child(“postal_code”).getValue(String.class);
cardInputWidget.setCardNumber(镉);
cardInputWidget.setCvcCode(cvc);
setExpiryDate(exp\u月,exp\u年);
}否则{
}
}
@凌驾
已取消公共void(@NonNull DatabaseError){
}
});
//使用Stripe可发布密钥配置SDK,以便它可以请求Stripe
条纹=新条纹(
getApplicationContext(),
对象.要求完整(“pk_测试_51GzvqSI4qFEpgfxS15GlPnxcrL4Sb5CZsv5AWXGPW1ihpQBTB9OPSh9nnZxY2zY71bVacdmJQ4gRxKYmCw3SCVQo00KUZF8psk”)
);
startCheckout();
//startCheckout();
}
私有void startCheckout(){
//金额将从0.00开始计算确保乘以100
//double amount=double.parseDouble(mAmount.getText().toString())*1;
Map payMap=newhashmap();
Map itemMap=newhashmap();
List itemList=new ArrayList();
payMap.put(“货币”、“美元”);
itemMap.put(“id”、“照片订阅”);
//itemMap.put(“金额”,金额);
itemList.add(itemMap);
支付图。放置(“项目”,项目列表);
字符串json=new Gson().toJson(payMap);
//Log.i(“TAG”、“startCheckout:+json”);
//通过调用示例服务器的/Create payment intent端点来创建PaymentIntent。
MediaType MediaType=MediaType.parse(“application/json;charset=utf-8”);
/*
字符串json=“{”
+““货币”:“美元”
+“\”项目\:[”
+“{\'id\':\'photo\'u subscription\”}”
+ "]"
+ "}";
*/
RequestBody=RequestBody.create(mediaType,json);
Request Request=newrequest.Builder()
.url(后端_url+“创建支付意图”)
.职位(机构)
.build();
httpClient.newCall(请求)
.enqueue(新的PayCallback(本));
//将pay按钮连接到card小部件和stripe实例
//Button payButton=findViewById(R.id.payButton);
payButton.setOnClickListener((视图)->{
//字符串get_card=cardInputWidget.getCard().getAddressZip();
//Toast.makeText(PaymentPageActivity.this,get_card,Toast.LENGTH_SHORT).show();
PaymentMethodCreateParams params=cardInputWidget.getPaymentMethodCreateParams();
如果(参数!=null){
Map extraParams=newhashmap();
外部参数put(“设置未来使用”、“关闭会话”);
ConfirmPaymentIntentParams confirmParams=ConfirmPaymentIntentParams
.createWithPaymentMethodCreateParams(params,paymentIntentClientSecret);
条带。确认付款(本,确认参数);
}
});
}
@凌驾
受保护的void onActivityResult(int请求代码、int结果代码、意图数据){
super.onActivityResult(请求代码、结果代码、数据);
//处理stripe.confirmPayment的结果
stripe.onPaymentResult(请求代码、数据、新PaymentResultCallback(this));
}
公共作废戈巴克(视图){
onBackPressed();
}
私有静态最终类PayCallback实现回调{
@非空私有最终WeakReference activityRef;
PayCallback(@NonNull PaymentPageActivity活动){
activityRef=新的WeakReference(活动);
}
@凌驾
public void onFailure(@NonNull Call Call,@NonNull ioe异常){
final PaymentPageActivity=activityRef.get();
如果(活动==null){
返回;
}
activity.runOnUiThread(()->
Toast.makeText(
活动,“错误:+e.toString(),Toast.LENGTH\u LONG
).show()
);
}
@凌驾
公共void onResponse(@NonNull调用,@NonNull最终响应)
抛出IOException{
final PaymentPageActivity=activityRef.get();
如果(活动==null){
返回;
}
如果(!response.issusccessful()){
activity.runOnUiThread(()->
Toast.makeText(
活动,“错误:+response.toString(),Toast.LENGTH\u LONG
).show()