-
Notifications
You must be signed in to change notification settings - Fork 182
/
PaymentsUtil.java
291 lines (253 loc) · 10.9 KB
/
PaymentsUtil.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
/*
* Copyright 2020 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.android.gms.samples.wallet.util;
import android.app.Activity;
import com.google.android.gms.samples.wallet.Constants;
import com.google.android.gms.wallet.PaymentsClient;
import com.google.android.gms.wallet.Wallet;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.Optional;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
/**
* Contains helper static methods for dealing with the Payments API.
*
* <p>Many of the parameters used in the code are optional and are set here merely to call out their
* existence. Please consult the documentation to learn more and feel free to remove ones not
* relevant to your implementation.
*/
public class PaymentsUtil {
public static final BigDecimal CENTS_IN_A_UNIT = new BigDecimal(100d);
/**
* Create a Google Pay API base request object with properties used in all requests.
*
* @return Google Pay API base request object.
* @throws JSONException
*/
private static JSONObject getBaseRequest() throws JSONException {
return new JSONObject().put("apiVersion", 2).put("apiVersionMinor", 0);
}
/**
* Creates an instance of {@link PaymentsClient} for use in an {@link Activity} using the
* environment and theme set in {@link Constants}.
*
* @param activity is the caller's activity.
*/
public static PaymentsClient createPaymentsClient(Activity activity) {
Wallet.WalletOptions walletOptions =
new Wallet.WalletOptions.Builder().setEnvironment(Constants.PAYMENTS_ENVIRONMENT).build();
return Wallet.getPaymentsClient(activity, walletOptions);
}
/**
* Gateway Integration: Identify your gateway and your app's gateway merchant identifier.
*
* <p>The Google Pay API response will return an encrypted payment method capable of being charged
* by a supported gateway after payer authorization.
*
* <p>TODO: Check with your gateway on the parameters to pass and modify them in Constants.java.
*
* @return Payment data tokenization for the CARD payment method.
* @throws JSONException
* @see <a href=
* "https://developers.google.com/pay/api/android/reference/object#PaymentMethodTokenizationSpecification">PaymentMethodTokenizationSpecification</a>
*/
private static JSONObject getGatewayTokenizationSpecification() throws JSONException {
return new JSONObject() {{
put("type", "PAYMENT_GATEWAY");
put("parameters", new JSONObject() {{
put("gateway", "example");
put("gatewayMerchantId", "exampleGatewayMerchantId");
}});
}};
}
/**
* {@code DIRECT} Integration: Decrypt a response directly on your servers. This configuration has
* additional data security requirements from Google and additional PCI DSS compliance complexity.
*
* <p>Please refer to the documentation for more information about {@code DIRECT} integration. The
* type of integration you use depends on your payment processor.
*
* @return Payment data tokenization for the CARD payment method.
* @throws JSONException
* @see <a
* href="https://developers.google.com/pay/api/android/reference/object#PaymentMethodTokenizationSpecification">PaymentMethodTokenizationSpecification</a>
*/
private static JSONObject getDirectTokenizationSpecification()
throws JSONException, RuntimeException {
if (Constants.DIRECT_TOKENIZATION_PARAMETERS.isEmpty()
|| Constants.DIRECT_TOKENIZATION_PUBLIC_KEY.isEmpty()
|| Constants.DIRECT_TOKENIZATION_PUBLIC_KEY == null
|| Constants.DIRECT_TOKENIZATION_PUBLIC_KEY == "REPLACE_ME") {
throw new RuntimeException(
"Please edit the Constants.java file to add protocol version & public key.");
}
JSONObject tokenizationSpecification = new JSONObject();
tokenizationSpecification.put("type", "DIRECT");
JSONObject parameters = new JSONObject(Constants.DIRECT_TOKENIZATION_PARAMETERS);
tokenizationSpecification.put("parameters", parameters);
return tokenizationSpecification;
}
/**
* Card networks supported by your app and your gateway.
*
* <p>TODO: Confirm card networks supported by your app and gateway & update in Constants.java.
*
* @return Allowed card networks
* @see <a
* href="https://developers.google.com/pay/api/android/reference/object#CardParameters">CardParameters</a>
*/
private static JSONArray getAllowedCardNetworks() {
return new JSONArray(Constants.SUPPORTED_NETWORKS);
}
/**
* Card authentication methods supported by your app and your gateway.
*
* <p>TODO: Confirm your processor supports Android device tokens on your supported card networks
* and make updates in Constants.java.
*
* @return Allowed card authentication methods.
* @see <a
* href="https://developers.google.com/pay/api/android/reference/object#CardParameters">CardParameters</a>
*/
private static JSONArray getAllowedCardAuthMethods() {
return new JSONArray(Constants.SUPPORTED_METHODS);
}
/**
* Describe your app's support for the CARD payment method.
*
* <p>The provided properties are applicable to both an IsReadyToPayRequest and a
* PaymentDataRequest.
*
* @return A CARD PaymentMethod object describing accepted cards.
* @throws JSONException
* @see <a
* href="https://developers.google.com/pay/api/android/reference/object#PaymentMethod">PaymentMethod</a>
*/
private static JSONObject getBaseCardPaymentMethod() throws JSONException {
JSONObject cardPaymentMethod = new JSONObject();
cardPaymentMethod.put("type", "CARD");
JSONObject parameters = new JSONObject();
parameters.put("allowedAuthMethods", getAllowedCardAuthMethods());
parameters.put("allowedCardNetworks", getAllowedCardNetworks());
// Optionally, you can add billing address/phone number associated with a CARD payment method.
parameters.put("billingAddressRequired", true);
JSONObject billingAddressParameters = new JSONObject();
billingAddressParameters.put("format", "FULL");
parameters.put("billingAddressParameters", billingAddressParameters);
cardPaymentMethod.put("parameters", parameters);
return cardPaymentMethod;
}
/**
* Describe the expected returned payment data for the CARD payment method
*
* @return A CARD PaymentMethod describing accepted cards and optional fields.
* @throws JSONException
* @see <a
* href="https://developers.google.com/pay/api/android/reference/object#PaymentMethod">PaymentMethod</a>
*/
private static JSONObject getCardPaymentMethod() throws JSONException {
JSONObject cardPaymentMethod = getBaseCardPaymentMethod();
cardPaymentMethod.put("tokenizationSpecification", getGatewayTokenizationSpecification());
return cardPaymentMethod;
}
/**
* An object describing accepted forms of payment by your app, used to determine a viewer's
* readiness to pay.
*
* @return API version and payment methods supported by the app.
* @see <a
* href="https://developers.google.com/pay/api/android/reference/object#IsReadyToPayRequest">IsReadyToPayRequest</a>
*/
public static Optional<JSONObject> getIsReadyToPayRequest() {
try {
JSONObject isReadyToPayRequest = getBaseRequest();
isReadyToPayRequest.put(
"allowedPaymentMethods", new JSONArray().put(getBaseCardPaymentMethod()));
return Optional.of(isReadyToPayRequest);
} catch (JSONException e) {
return Optional.empty();
}
}
/**
* Provide Google Pay API with a payment amount, currency, and amount status.
*
* @return information about the requested payment.
* @throws JSONException
* @see <a
* href="https://developers.google.com/pay/api/android/reference/object#TransactionInfo">TransactionInfo</a>
*/
private static JSONObject getTransactionInfo(String price) throws JSONException {
JSONObject transactionInfo = new JSONObject();
transactionInfo.put("totalPrice", price);
transactionInfo.put("totalPriceStatus", "FINAL");
transactionInfo.put("countryCode", Constants.COUNTRY_CODE);
transactionInfo.put("currencyCode", Constants.CURRENCY_CODE);
transactionInfo.put("checkoutOption", "COMPLETE_IMMEDIATE_PURCHASE");
return transactionInfo;
}
/**
* Information about the merchant requesting payment information
*
* @return Information about the merchant.
* @throws JSONException
* @see <a
* href="https://developers.google.com/pay/api/android/reference/object#MerchantInfo">MerchantInfo</a>
*/
private static JSONObject getMerchantInfo() throws JSONException {
return new JSONObject().put("merchantName", "Example Merchant");
}
/**
* An object describing information requested in a Google Pay payment sheet
*
* @return Payment data expected by your app.
* @see <a
* href="https://developers.google.com/pay/api/android/reference/object#PaymentDataRequest">PaymentDataRequest</a>
*/
public static Optional<JSONObject> getPaymentDataRequest(long priceCents) {
final String price = PaymentsUtil.centsToString(priceCents);
try {
JSONObject paymentDataRequest = PaymentsUtil.getBaseRequest();
paymentDataRequest.put(
"allowedPaymentMethods", new JSONArray().put(PaymentsUtil.getCardPaymentMethod()));
paymentDataRequest.put("transactionInfo", PaymentsUtil.getTransactionInfo(price));
paymentDataRequest.put("merchantInfo", PaymentsUtil.getMerchantInfo());
/* An optional shipping address requirement is a top-level property of the PaymentDataRequest
JSON object. */
paymentDataRequest.put("shippingAddressRequired", true);
JSONObject shippingAddressParameters = new JSONObject();
shippingAddressParameters.put("phoneNumberRequired", false);
JSONArray allowedCountryCodes = new JSONArray(Constants.SHIPPING_SUPPORTED_COUNTRIES);
shippingAddressParameters.put("allowedCountryCodes", allowedCountryCodes);
paymentDataRequest.put("shippingAddressParameters", shippingAddressParameters);
return Optional.of(paymentDataRequest);
} catch (JSONException e) {
return Optional.empty();
}
}
/**
* Converts cents to a string format accepted by {@link PaymentsUtil#getPaymentDataRequest}.
*
* @param cents value of the price in cents.
*/
public static String centsToString(long cents) {
return new BigDecimal(cents)
.divide(CENTS_IN_A_UNIT, RoundingMode.HALF_EVEN)
.setScale(2, RoundingMode.HALF_EVEN)
.toString();
}
}