首页 > 解决方案 > 将收据发送到电子邮件 android stripe

问题描述

我在我的 android 应用程序上使用 stripe 来收款。我希望能够在用户成功购买商品后向他们保存在数据库(Firebase)中的电子邮件发送收据。我确实查看了文档以了解如何去做,但我有点卡住了。我注意到我应该将此添加到我的服务器`receipt_email:'jenny.rosen@example.com',但我只是想知道如何告诉它发送到从数据库(Firebase)保存的电子邮件。

//Server set up

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_************************************************************");
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;
};
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,
  receipt_email: 'jenny.rosen@example.com',

  });
  res.send({
    clientSecret: paymentIntent.client_secret
  });
});
app.get("/greet", async (req, res) => {
 res.send('Good to go');
});
const PORT= process.env.PORT || 5001;
app.listen(PORT, () => console.log('Node server listening on port $(PORT)'));


//PaymentPage.java

 private void startCheckout() {

        
        Intent intent = getIntent();
        final String t = intent.getStringExtra("days");

        int in = Integer.valueOf(t);




        double amount=in*100;
        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);





        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();
    }

标签: androidfirebasestripe-payments

解决方案


我如何告诉它发送到从数据库中保存的电子邮件

receipt_email在创建或更新它时设置了 PaymentIntent(https://stripe.com/docs/api/payment_intents/create#create_payment_intent-receipt_email)。

receipt_email在实时模式下,当 PaymentIntent 得到确认并转换为 时,Stripe 会自动向客户发送电子邮件至 中指定的电子邮件地址status: succeeded


推荐阅读