-
Notifications
You must be signed in to change notification settings - Fork 629
/
PaymentSessionActivity.java
303 lines (274 loc) · 13.1 KB
/
PaymentSessionActivity.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
package com.stripe.example.activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.content.LocalBroadcastManager;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.ProgressBar;
import android.widget.TextView;
import com.stripe.android.CustomerSession;
import com.stripe.android.PaymentSession;
import com.stripe.android.PaymentSessionConfig;
import com.stripe.android.PaymentSessionData;
import com.stripe.android.StripeError;
import com.stripe.android.model.Address;
import com.stripe.android.model.Customer;
import com.stripe.android.model.CustomerSource;
import com.stripe.android.model.ShippingInformation;
import com.stripe.android.model.ShippingMethod;
import com.stripe.android.model.Source;
import com.stripe.android.model.SourceCardData;
import com.stripe.android.view.ShippingInfoWidget;
import com.stripe.example.R;
import com.stripe.example.controller.ErrorDialogHandler;
import com.stripe.example.service.ExampleEphemeralKeyProvider;
import java.util.ArrayList;
import java.util.Currency;
import java.util.Locale;
import static com.stripe.android.PayWithGoogleUtils.getPriceString;
import static com.stripe.android.view.PaymentFlowExtras.EVENT_SHIPPING_INFO_PROCESSED;
import static com.stripe.android.view.PaymentFlowExtras.EVENT_SHIPPING_INFO_SUBMITTED;
import static com.stripe.android.view.PaymentFlowExtras.EXTRA_DEFAULT_SHIPPING_METHOD;
import static com.stripe.android.view.PaymentFlowExtras.EXTRA_IS_SHIPPING_INFO_VALID;
import static com.stripe.android.view.PaymentFlowExtras.EXTRA_SHIPPING_INFO_DATA;
import static com.stripe.android.view.PaymentFlowExtras.EXTRA_VALID_SHIPPING_METHODS;
/**
* An example activity that handles working with a {@link com.stripe.android.PaymentSession}, allowing you to
* collect information needed to request payment for the current customer.
*/
public class PaymentSessionActivity extends AppCompatActivity {
private BroadcastReceiver mBroadcastReceiver;
private Customer mCustomer;
private ErrorDialogHandler mErrorDialogHandler;
private PaymentSession mPaymentSession;
private ProgressBar mProgressBar;
private TextView mResultTextView;
private TextView mResultTitleTextView;
private Button mSelectPaymentButton;
private Button mSelectShippingButton;
private PaymentSessionData mPaymentSessionData;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_payment_session);
mProgressBar = findViewById(R.id.customer_progress_bar);
mProgressBar.setVisibility(View.VISIBLE);
mSelectPaymentButton = findViewById(R.id.btn_select_payment_method_aps);
mSelectPaymentButton.setEnabled(false);
mSelectShippingButton = findViewById(R.id.btn_start_payment_flow);
mSelectShippingButton.setEnabled(false);
mErrorDialogHandler = new ErrorDialogHandler(getSupportFragmentManager());
mResultTitleTextView = findViewById(R.id.tv_payment_session_data_title);
mResultTextView = findViewById(R.id.tv_payment_session_data);
setupCustomerSession(); // CustomerSession only needs to be initialized once per app.
mBroadcastReceiver = new BroadcastReceiver() {
@Override
public void onReceive(@NonNull Context context, @NonNull Intent intent) {
ShippingInformation shippingInformation = intent
.getParcelableExtra(EXTRA_SHIPPING_INFO_DATA);
Intent shippingInfoProcessedIntent = new Intent(EVENT_SHIPPING_INFO_PROCESSED);
if (!isValidShippingInfo(shippingInformation)) {
shippingInfoProcessedIntent.putExtra(EXTRA_IS_SHIPPING_INFO_VALID, false);
} else {
ArrayList<ShippingMethod> shippingMethods = createSampleShippingMethods();
shippingInfoProcessedIntent.putExtra(EXTRA_IS_SHIPPING_INFO_VALID, true);
shippingInfoProcessedIntent.putParcelableArrayListExtra(
EXTRA_VALID_SHIPPING_METHODS, shippingMethods);
shippingInfoProcessedIntent.putExtra(EXTRA_DEFAULT_SHIPPING_METHOD,
shippingMethods.get(1));
}
LocalBroadcastManager.getInstance(PaymentSessionActivity.this)
.sendBroadcast(shippingInfoProcessedIntent);
}
private boolean isValidShippingInfo(@NonNull ShippingInformation shippingInfo) {
return shippingInfo.getAddress() != null &&
Locale.US.getCountry().equals(shippingInfo.getAddress().getCountry());
}
};
LocalBroadcastManager.getInstance(this).registerReceiver(mBroadcastReceiver,
new IntentFilter(EVENT_SHIPPING_INFO_SUBMITTED));
mSelectPaymentButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
mPaymentSession.presentPaymentMethodSelection();
}
});
mSelectShippingButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
mPaymentSession.presentShippingFlow();
}
});
}
private void setupCustomerSession() {
CustomerSession.initCustomerSession(
new ExampleEphemeralKeyProvider(
new ExampleEphemeralKeyProvider.ProgressListener() {
@Override
public void onStringResponse(String string) {
if (string.startsWith("Error: ")) {
mErrorDialogHandler.show(string);
}
}
}));
CustomerSession.getInstance().retrieveCurrentCustomer(
new CustomerSession.CustomerRetrievalListener() {
@Override
public void onCustomerRetrieved(@NonNull Customer customer) {
mCustomer = customer;
mProgressBar.setVisibility(View.INVISIBLE);
setupPaymentSession();
}
@Override
public void onError(int httpCode, @Nullable String errorMessage,
@Nullable StripeError stripeError) {
mCustomer = null;
mSelectPaymentButton.setEnabled(false);
mSelectShippingButton.setEnabled(false);
mErrorDialogHandler.show(errorMessage);
mProgressBar.setVisibility(View.INVISIBLE);
}
});
}
private void setupPaymentSession() {
mPaymentSession = new PaymentSession(this);
boolean paymentSessionInitialized = mPaymentSession.init(new PaymentSessionListenerImpl(this), new PaymentSessionConfig.Builder()
.setPrepopulatedShippingInfo(getExampleShippingInfo())
.setHiddenShippingInfoFields(ShippingInfoWidget.PHONE_FIELD, ShippingInfoWidget.CITY_FIELD)
.build());
if (paymentSessionInitialized) {
mSelectPaymentButton.setEnabled(true);
mSelectShippingButton.setEnabled(true);
mPaymentSession.setCartTotal(2000L);
}
}
private void checkForCustomerUpdates() {
mProgressBar.setVisibility(View.VISIBLE);
CustomerSession.getInstance().retrieveCurrentCustomer(
new CustomerSession.CustomerRetrievalListener() {
@Override
public void onCustomerRetrieved(@NonNull Customer customer) {
mCustomer = customer;
mProgressBar.setVisibility(View.INVISIBLE);
if (mPaymentSessionData != null) {
mResultTitleTextView.setVisibility(View.VISIBLE);
mResultTextView.setText(formatStringResults(mPaymentSessionData));
}
}
@Override
public void onError(int httpCode, @Nullable String errorMessage,
@Nullable StripeError stripeError) {
mProgressBar.setVisibility(View.INVISIBLE);
}
});
}
@NonNull
private String formatStringResults(@NonNull PaymentSessionData data) {
Currency currency = Currency.getInstance("USD");
StringBuilder stringBuilder = new StringBuilder();
if (data.getSelectedPaymentMethodId() != null && mCustomer != null) {
CustomerSource source = mCustomer.getSourceById(data.getSelectedPaymentMethodId());
if (source != null) {
Source cardSource = source.asSource();
stringBuilder.append("Payment Info:\n");
if (cardSource != null) {
SourceCardData scd = (SourceCardData) cardSource.getSourceTypeModel();
stringBuilder.append(scd.getBrand())
.append(" ending in ")
.append(scd.getLast4());
} else {
stringBuilder.append('\n').append(source.toJson().toString()).append('\n');
}
String isOrNot = data.isPaymentReadyToCharge() ? " IS " : " IS NOT ";
stringBuilder.append(isOrNot).append("ready to charge.\n\n");
}
}
if (data.getShippingInformation() != null) {
stringBuilder.append("Shipping Info: \n");
stringBuilder.append(data.getShippingInformation());
stringBuilder.append("\n\n");
}
if (data.getShippingMethod() != null) {
stringBuilder.append("Shipping Method: \n");
stringBuilder.append(data.getShippingMethod()).append('\n');
if (data.getShippingTotal() > 0) {
stringBuilder.append("Shipping total: ")
.append(getPriceString(data.getShippingTotal(), currency));
}
}
return stringBuilder.toString();
}
@NonNull
private ArrayList<ShippingMethod> createSampleShippingMethods() {
final ArrayList<ShippingMethod> shippingMethods = new ArrayList<>();
shippingMethods.add(new ShippingMethod("UPS Ground", "ups-ground",
"Arrives in 3-5 days", 0, "USD"));
shippingMethods.add(new ShippingMethod("FedEx", "fedex",
"Arrives tomorrow", 599, "USD"));
return shippingMethods;
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
mPaymentSession.handlePaymentData(requestCode, resultCode, data);
}
@Override
protected void onDestroy() {
super.onDestroy();
mPaymentSession.onDestroy();
LocalBroadcastManager.getInstance(this).unregisterReceiver(mBroadcastReceiver);
}
@NonNull
private ShippingInformation getExampleShippingInfo() {
final Address address = new Address.Builder()
.setCity("San Francisco")
.setCountry("US")
.setLine1("123 Market St")
.setLine2("#345")
.setPostalCode("94107")
.setState("CA")
.build();
return new ShippingInformation(address, "Fake Name", "(555) 555-5555");
}
private void onPaymentSessionDataChanged(@NonNull PaymentSessionData data) {
mPaymentSessionData = data;
checkForCustomerUpdates();
}
private static final class PaymentSessionListenerImpl
extends PaymentSession.ActivityPaymentSessionListener<PaymentSessionActivity> {
private PaymentSessionListenerImpl(@NonNull PaymentSessionActivity activity) {
super(activity);
}
@Override
public void onCommunicatingStateChanged(boolean isCommunicating) {
final PaymentSessionActivity activity = getListenerActivity();
if (activity == null) {
return;
}
activity.mProgressBar
.setVisibility(isCommunicating ? View.VISIBLE : View.INVISIBLE);
}
@Override
public void onError(int errorCode, @Nullable String errorMessage) {
final PaymentSessionActivity activity = getListenerActivity();
if (activity == null) {
return;
}
activity.mErrorDialogHandler.show(errorMessage);
}
@Override
public void onPaymentSessionDataChanged(@NonNull PaymentSessionData data) {
final PaymentSessionActivity activity = getListenerActivity();
if (activity == null) {
return;
}
activity.onPaymentSessionDataChanged(data);
}
}
}