This repository was archived by the owner on Nov 20, 2025. It is now read-only.
forked from naoufal/react-native-payments
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathReactNativePaymentsModule.java
More file actions
371 lines (303 loc) · 16.1 KB
/
ReactNativePaymentsModule.java
File metadata and controls
371 lines (303 loc) · 16.1 KB
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
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
package com.reactnativepayments;
import android.view.WindowManager;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.annotation.NonNull;
import android.app.Fragment;
import android.app.FragmentManager;
import android.support.annotation.RequiresPermission;
import android.util.Log;
import com.facebook.react.bridge.Callback;
import com.facebook.react.bridge.ReactBridge;
import com.facebook.react.bridge.ReadableArray;
import com.facebook.react.bridge.ReadableMapKeySetIterator;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.common.api.BooleanResult;
import com.google.android.gms.common.api.ResultCallback;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.identity.intents.model.UserAddress;
import com.google.android.gms.wallet.*;
import com.facebook.react.bridge.ActivityEventListener;
import com.facebook.react.bridge.BaseActivityEventListener;
import com.facebook.react.bridge.ReactApplicationContext;
import com.facebook.react.bridge.ReactContextBaseJavaModule;
import com.facebook.react.bridge.ReactMethod;
import com.facebook.react.bridge.ReadableMap;
import com.facebook.react.bridge.WritableNativeArray;
import com.facebook.react.bridge.WritableNativeMap;
import com.facebook.react.modules.core.DeviceEventManagerModule;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class ReactNativePaymentsModule extends ReactContextBaseJavaModule implements GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener {
private static final int LOAD_MASKED_WALLET_REQUEST_CODE = 88;
private static final int LOAD_FULL_WALLET_REQUEST_CODE = 89;
// Google API Client
private GoogleApiClient mGoogleApiClient = null;
// Callbacks
private static Callback mShowSuccessCallback = null;
private static Callback mShowErrorCallback = null;
private static Callback mGetFullWalletSuccessCallback= null;
private static Callback mGetFullWalletErrorCallback = null;
public static final String REACT_CLASS = "ReactNativePayments";
private static ReactApplicationContext reactContext = null;
private final ActivityEventListener mActivityEventListener = new BaseActivityEventListener() {
@Override
public void onActivityResult(Activity activity, int requestCode, int resultCode, Intent data) {
// retrieve the error code, if available
int errorCode = -1;
if (data != null) {
errorCode = data.getIntExtra(WalletConstants.EXTRA_ERROR_CODE, -1);
}
switch (requestCode) {
case LOAD_MASKED_WALLET_REQUEST_CODE:
switch (resultCode) {
case Activity.RESULT_OK:
if (data != null) {
MaskedWallet maskedWallet =
data.getParcelableExtra(WalletConstants.EXTRA_MASKED_WALLET);
Log.i(REACT_CLASS, "ANDROID PAY SUCCESS" + maskedWallet.getEmail());
Log.i(REACT_CLASS, "ANDROID PAY SUCCESS" + buildAddressFromUserAddress(maskedWallet.getBuyerBillingAddress()));
UserAddress userAddress = maskedWallet.getBuyerShippingAddress();
WritableNativeMap shippingAddress = userAddress != null
? buildAddressFromUserAddress(userAddress)
: null;
// TODO: Move into function
WritableNativeMap paymentDetails = new WritableNativeMap();
paymentDetails.putString("paymentDescription", maskedWallet.getPaymentDescriptions()[0]);
paymentDetails.putString("payerEmail", maskedWallet.getEmail());
paymentDetails.putMap("shippingAddress", shippingAddress);
paymentDetails.putString("googleTransactionId", maskedWallet.getGoogleTransactionId());
sendEvent(reactContext, "NativePayments:onuseraccept", paymentDetails);
}
break;
case Activity.RESULT_CANCELED:
sendEvent(reactContext, "NativePayments:onuserdismiss", null);
break;
default:
Log.i(REACT_CLASS, "ANDROID PAY ERROR? " + errorCode);
mShowErrorCallback.invoke(errorCode);
break;
}
break;
case LOAD_FULL_WALLET_REQUEST_CODE:
if (resultCode == Activity.RESULT_OK && data != null) {
FullWallet fullWallet = data.getParcelableExtra(WalletConstants.EXTRA_FULL_WALLET);
String tokenJSON = fullWallet.getPaymentMethodToken().getToken();
Log.i(REACT_CLASS, "FULL WALLET SUCCESS" + tokenJSON);
mGetFullWalletSuccessCallback.invoke(tokenJSON);
} else {
Log.i(REACT_CLASS, "FULL WALLET FAILURE");
mGetFullWalletErrorCallback.invoke();
}
case WalletConstants.RESULT_ERROR:activity.getWindow().clearFlags(WindowManager.LayoutParams.FLAG_SECURE);
// handleError(errorCode);
break;
default:
super.onActivityResult(requestCode, resultCode, data);
break;
}
}
};
public ReactNativePaymentsModule(ReactApplicationContext context) {
// Pass in the context to the constructor and save it so you can emit events
// https://facebook.github.io/react-native/docs/native-modules-android.html#the-toast-module
super(context);
reactContext = context;
reactContext.addActivityEventListener(mActivityEventListener);
}
@Override
public String getName() {
// Tell React the name of the module
// https://facebook.github.io/react-native/docs/native-modules-android.html#the-toast-module
return REACT_CLASS;
}
// Public Methods
// ---------------------------------------------------------------------------------------------
@ReactMethod
public void getSupportedGateways(Callback errorCallback, Callback successCallback) {
WritableNativeArray supportedGateways = new WritableNativeArray();
successCallback.invoke(supportedGateways);
}
@ReactMethod
public void canMakePayments(ReadableMap paymentMethodData, Callback errorCallback, Callback successCallback) {
final Callback callback = successCallback;
IsReadyToPayRequest req = IsReadyToPayRequest.newBuilder()
.addAllowedCardNetwork(WalletConstants.CardNetwork.MASTERCARD)
.addAllowedCardNetwork(WalletConstants.CardNetwork.VISA)
.build();
int environment = getEnvironmentFromPaymentMethodData(paymentMethodData);
if (mGoogleApiClient == null) {
buildGoogleApiClient(getCurrentActivity(), environment);
}
Wallet.Payments.isReadyToPay(mGoogleApiClient, req)
.setResultCallback(new ResultCallback<BooleanResult>() {
@Override
public void onResult(@NonNull BooleanResult booleanResult) {
callback.invoke(booleanResult.getValue());
}
});
}
@ReactMethod
public void abort(Callback errorCallback, Callback successCallback) {
Log.i(REACT_CLASS, "ANDROID PAY ABORT" + getCurrentActivity().toString());
successCallback.invoke();
}
@ReactMethod
public void show(
ReadableMap paymentMethodData,
ReadableMap details,
ReadableMap options,
Callback errorCallback,
Callback successCallback
) {
mShowSuccessCallback = successCallback;
mShowErrorCallback = errorCallback;
Log.i(REACT_CLASS, "ANDROID PAY SHOW" + options);
Boolean shouldRequestShipping = options.hasKey("requestShipping") && options.getBoolean("requestShipping")
|| options.hasKey("requestPayerName") && options.getBoolean("requestPayerName")
|| options.hasKey("requestPayerPhone") && options.getBoolean("requestPayerPhone");
Boolean shouldRequestPayerPhone = options.hasKey("requestPayerPhone") && options.getBoolean("requestPayerPhone");
final PaymentMethodTokenizationParameters parameters = buildTokenizationParametersFromPaymentMethodData(paymentMethodData);
// TODO: clean up MaskedWalletRequest
ReadableMap total = details.getMap("total").getMap("amount");
final MaskedWalletRequest maskedWalletRequest = MaskedWalletRequest.newBuilder()
.setPaymentMethodTokenizationParameters(parameters)
.setPhoneNumberRequired(shouldRequestPayerPhone)
.setShippingAddressRequired(shouldRequestShipping)
.setEstimatedTotalPrice(total.getString("value"))
.setCurrencyCode(total.getString("currency"))
.build();
int environment = getEnvironmentFromPaymentMethodData(paymentMethodData);
if (mGoogleApiClient == null) {
buildGoogleApiClient(getCurrentActivity(), environment);
}
Wallet.Payments.loadMaskedWallet(mGoogleApiClient, maskedWalletRequest, LOAD_MASKED_WALLET_REQUEST_CODE);
}
@ReactMethod
public void getFullWalletAndroid(
String googleTransactionId,
ReadableMap paymentMethodData,
ReadableMap details,
Callback errorCallback,
Callback successCallback
) {
mGetFullWalletSuccessCallback = successCallback;
mGetFullWalletErrorCallback = errorCallback;
ReadableMap total = details.getMap("total").getMap("amount");
Log.i(REACT_CLASS, "ANDROID PAY getFullWalletAndroid" + details.getMap("total").getMap("amount"));
FullWalletRequest fullWalletRequest = FullWalletRequest.newBuilder()
.setGoogleTransactionId(googleTransactionId)
.setCart(Cart.newBuilder()
.setCurrencyCode(total.getString("currency"))
.setTotalPrice(total.getString("value"))
.setLineItems(buildLineItems(details.getArray("displayItems")))
.build())
.build();
int environment = getEnvironmentFromPaymentMethodData(paymentMethodData);
if (mGoogleApiClient == null) {
buildGoogleApiClient(getCurrentActivity(), environment);
}
Wallet.Payments.loadFullWallet(mGoogleApiClient, fullWalletRequest, LOAD_FULL_WALLET_REQUEST_CODE);
}
// Private Method
// ---------------------------------------------------------------------------------------------
private static PaymentMethodTokenizationParameters buildTokenizationParametersFromPaymentMethodData(ReadableMap paymentMethodData) {
ReadableMap tokenizationParameters = paymentMethodData.getMap("paymentMethodTokenizationParameters");
String tokenizationType = tokenizationParameters.getString("tokenizationType");
if (tokenizationType.equals("GATEWAY_TOKEN")) {
ReadableMap parameters = tokenizationParameters.getMap("parameters");
PaymentMethodTokenizationParameters.Builder parametersBuilder = PaymentMethodTokenizationParameters.newBuilder()
.setPaymentMethodTokenizationType(PaymentMethodTokenizationType.PAYMENT_GATEWAY)
.addParameter("gateway", parameters.getString("gateway"));
ReadableMapKeySetIterator iterator = parameters.keySetIterator();
while (iterator.hasNextKey()) {
String key = iterator.nextKey();
parametersBuilder.addParameter(key, parameters.getString(key));
}
return parametersBuilder.build();
} else {
String publicKey = tokenizationParameters.getMap("parameters").getString("publicKey");
return PaymentMethodTokenizationParameters.newBuilder()
.setPaymentMethodTokenizationType(PaymentMethodTokenizationType.NETWORK_TOKEN)
.addParameter("publicKey", publicKey)
.build();
}
}
private static List buildLineItems(ReadableArray displayItems) {
List<LineItem> list = new ArrayList<LineItem>();
for (int i = 0; i < (displayItems.size() - 1); i++) {
ReadableMap displayItem = displayItems.getMap(i);
ReadableMap amount = displayItem.getMap("amount");
list.add(LineItem.newBuilder()
.setCurrencyCode(amount.getString("currency"))
.setDescription(displayItem.getString("label"))
.setQuantity("1")
.setUnitPrice(amount.getString("value"))
.setTotalPrice(amount.getString("value"))
.build());
}
Log.i(REACT_CLASS, "ANDROID PAY getFullWalletAndroid" + list);
return list;
}
private static WritableNativeMap buildAddressFromUserAddress(UserAddress userAddress) {
WritableNativeMap address = new WritableNativeMap();
address.putString("recipient", userAddress.getName());
address.putString("organization", userAddress.getCompanyName());
address.putString("addressLine", userAddress.getAddress1());
address.putString("city", userAddress.getLocality());
address.putString("region", userAddress.getAdministrativeArea());
address.putString("country", userAddress.getCountryCode());
address.putString("postalCode", userAddress.getPostalCode());
address.putString("phone", userAddress.getPhoneNumber());
address.putNull("languageCode");
address.putString("sortingCode", userAddress.getSortingCode());
address.putString("dependentLocality", userAddress.getLocality());
return address;
}
private void sendEvent(
ReactApplicationContext reactContext,
String eventName,
@Nullable WritableNativeMap params
) {
reactContext
.getJSModule(DeviceEventManagerModule.RCTDeviceEventEmitter.class)
.emit(eventName, params);
}
private int getEnvironmentFromPaymentMethodData(ReadableMap paymentMethodData) {
return paymentMethodData.hasKey("environment") && paymentMethodData.getString("environment").equals("TEST")
? WalletConstants.ENVIRONMENT_TEST
: WalletConstants.ENVIRONMENT_PRODUCTION;
}
// Google API Client
// ---------------------------------------------------------------------------------------------
private void buildGoogleApiClient(Activity currentActivity, int environment) {
mGoogleApiClient = new GoogleApiClient.Builder(currentActivity)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(Wallet.API, new Wallet.WalletOptions.Builder()
.setEnvironment(environment)
.setTheme(WalletConstants.THEME_LIGHT)
.build())
.build();
mGoogleApiClient.connect();
}
@Override
public void onConnected(Bundle connectionHint) {
// mLastLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
}
@Override
public void onConnectionFailed(ConnectionResult result) {
// Refer to Google Play documentation for what errors can be logged
Log.i(REACT_CLASS, "Connection failed: ConnectionResult.getErrorCode() = " + result.getErrorCode());
}
@Override
public void onConnectionSuspended(int cause) {
// Attempts to reconnect if a disconnect occurs
Log.i(REACT_CLASS, "Connection suspended");
mGoogleApiClient.connect();
}
}