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