· 6 years ago · Jan 23, 2020, 08:50 AM
1 MediaType mediaType = MediaType.get("application/json; charset=utf-8");
2 String json = "{"
3 + "\"currency\":\"usd\","
4 + "\"items\":["
5 + "{\"id\":\"photo_subscription\"}"
6 + "]"
7 + "}";
8 RequestBody body = RequestBody.create(json, mediaType);
9 Request request = new Request.Builder()
10 .url(BACKEND_URL + "create-payment-intent.php")
11 .post(body)
12 .build();
13 httpClient.newCall(request)
14 .enqueue(new PayCallback(this));
15
16 Log.d("CHINMAY","body"+body);
17
18 // Hook up the pay button to the card widget and stripe instance
19 Button payButton = findViewById(R.id.payButton);
20 payButton.setOnClickListener((View view) -> {
21 CardInputWidget cardInputWidget = findViewById(R.id.cardInputWidget);
22
23
24 PaymentMethodCreateParams params = cardInputWidget.getPaymentMethodCreateParams();
25 if (params != null) {
26
27 Log.d("CHINMAY","Passing Data in Params "+params.getTypeCode());
28 Log.d("CHINMAY","Data in Params "+params);
29
30 ConfirmPaymentIntentParams confirmParams = ConfirmPaymentIntentParams
31 .createWithPaymentMethodCreateParams(params, paymentIntentClientSecret);
32 stripe.confirmPayment(this, confirmParams);
33
34
35
36 }else{
37
38 Log.d("CHINMAY","Passing ");
39
40
41 }
42
43
44 });
45 }
46
47 private void displayAlert(@NonNull String title,
48 @Nullable String message,
49 boolean restartDemo) {
50 AlertDialog.Builder builder = new AlertDialog.Builder(this)
51 .setTitle(title)
52 .setMessage(message);
53 if (restartDemo) {
54 builder.setPositiveButton("Restart demo",
55 (DialogInterface dialog, int index) -> {
56 CardInputWidget cardInputWidget = findViewById(R.id.cardInputWidget);
57 cardInputWidget.clear();
58 startCheckout();
59 });
60 } else {
61 builder.setPositiveButton("Ok", null);
62 }
63 builder.create().show();
64 }
65
66 @Override
67 protected void onActivityResult(int requestCode, int resultCode, Intent data) {
68 super.onActivityResult(requestCode, resultCode, data);
69
70 // Handle the result of stripe.confirmPayment
71 stripe.onPaymentResult(requestCode, data, new PaymentResultCallback(this));
72 }
73
74 private void onPaymentSuccess(@NonNull final Response response) throws IOException {
75 Gson gson = new Gson();
76 Type type = new TypeToken<Map<String, String>>(){}.getType();
77 Map<String, String> responseMap = gson.fromJson(
78 Objects.requireNonNull(response.body()).string(),
79 type
80 );
81
82 // The response from the server includes the Stripe publishable key and
83 // PaymentIntent details.
84 // For added security, our sample app gets the publishable key from the server
85
86 String stripePublishableKey = responseMap.get("publishableKey");
87 paymentIntentClientSecret = responseMap.get("clientSecret");
88
89 // Configure the SDK with your Stripe publishable key so that it can make requests to the Stripe API
90 stripe = new Stripe(
91 getApplicationContext(),
92 Objects.requireNonNull(stripePublishableKey)
93 );
94 }
95
96 private static final class PayCallback implements Callback {
97 @NonNull private final WeakReference<StripePaymentActivity> activityRef;
98
99 PayCallback(@NonNull StripePaymentActivity activity) {
100 activityRef = new WeakReference<>(activity);
101 }
102
103 @Override
104 public void onFailure(@NonNull Call call, @NonNull IOException e) {
105 final StripePaymentActivity activity = activityRef.get();
106 if (activity == null) {
107 return;
108 }
109
110 activity.runOnUiThread(() ->
111
112 Log.d("CHINMAY","Error "+e.toString()));
113
114 // Toast.makeText(activity, "Error: " + e.toString(), Toast.LENGTH_LONG).show());
115 }
116
117
118
119 @Override
120 public void onResponse(@NotNull Call call, @NotNull okhttp3.Response response) throws IOException {
121 final StripePaymentActivity activity = activityRef.get();
122 if (activity == null) {
123 return;
124 }
125
126 if (!response.isSuccessful()) {
127 activity.runOnUiThread(() ->
128 Log.d("CHINMAY","Error "+response.toString()));
129// Toast.makeText(activity, "Error: " + response.toString(), Toast.LENGTH_LONG).show());
130 } else {
131 activity.onPaymentSuccess( response);
132 }
133
134 }
135 }
136
137 private static final class PaymentResultCallback
138 implements ApiResultCallback<PaymentIntentResult> {
139 @NonNull private final WeakReference<StripePaymentActivity> activityRef;
140
141 PaymentResultCallback(@NonNull StripePaymentActivity activity) {
142 activityRef = new WeakReference<>(activity);
143 }
144
145 @Override
146 public void onSuccess(@NonNull PaymentIntentResult result) {
147 final StripePaymentActivity activity = activityRef.get();
148 if (activity == null) {
149 return;
150 }
151
152 PaymentIntent paymentIntent = result.getIntent();
153 PaymentIntent.Status status = paymentIntent.getStatus();
154 if (status == PaymentIntent.Status.Succeeded) {
155 // Payment completed successfully
156 Gson gson = new GsonBuilder().setPrettyPrinting().create();
157 activity.displayAlert(
158 "Payment completed",
159 gson.toJson(paymentIntent),
160 true
161 );
162 } else if (status == PaymentIntent.Status.RequiresPaymentMethod) {
163 // Payment failed – allow retrying using a different payment method
164 activity.displayAlert(
165 "Payment failed",
166 Objects.requireNonNull(paymentIntent.getLastPaymentError()).getMessage(),
167 false
168 );
169 }
170 }
171
172 @Override
173 public void onError(@NonNull Exception e) {
174 final StripePaymentActivity activity = activityRef.get();
175 if (activity == null) {
176 return;
177 }
178
179 // Payment request failed – allow retrying using the same payment method
180 activity.displayAlert("Error", e.toString(), false);
181 }
182 }