forked from tonynguyenit18/paypal-RN-intergration
-
Notifications
You must be signed in to change notification settings - Fork 0
/
App.js
254 lines (220 loc) · 6.77 KB
/
App.js
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
import React, { useState } from 'react';
import {
Text,
View,
StyleSheet,
ActivityIndicator,
TouchableOpacity
} from 'react-native';
import { WebView } from 'react-native-webview';
import axios from "axios";
import qs from "qs";
import { decode, encode } from 'base-64'
const App = () => {
const [isWebViewLoading, SetIsWebViewLoading] = useState(false);
const [paypalUrl, setPaypalUrl] = useState('');
const [accessToken, setAccessToken] = useState("");
//Fix bug btoa
useEffect(() => {
if (!global.btoa) {
global.btoa = encode;
}
if (!global.atob) {
global.atob = decode;
}
}, [])
//When loading paypal page it refirects lots of times. This prop to control start loading only first time
const [shouldShowWebViewLoading, setShouldShowWebviewLoading] = useState(true)
/*---Paypal checkout section---*/
const buyBook = async () => {
//Check out https://developer.paypal.com/docs/integration/direct/payments/paypal-payments/# for more detail paypal checkout
const dataDetail = {
"intent": "sale",
"payer": {
"payment_method": "paypal"
},
"transactions": [{
"amount": {
"currency": "AUD",
"total": "26",
"details": {
"shipping": "6",
"subtotal": "20",
"shipping_discount": "0",
"insurance": "0",
"handling_fee": "0",
"tax": "0"
}
},
"description": "This is the payment transaction description",
"payment_options": {
"allowed_payment_method": "IMMEDIATE_PAY"
}, "item_list": {
"items": [{
"name": "Book",
"description": "Chasing After The Wind",
"quantity": "1",
"price": "20",
"tax": "0",
"sku": "product34",
"currency": "AUD"
}]
}
}],
"redirect_urls": {
"return_url": "https://example.com/",
"cancel_url": "https://example.com/"
}
}
const url = `https://api.sandbox.paypal.com/v1/oauth2/token`;
const data = {
grant_type: 'client_credentials'
};
const auth = {
username: "AVoei4BdvFtP_nB5Ulu0fN0L1FrW_he7DLx2A1Y6TUdOFVwrKed73my0bwlUeAXO0mFJZyAfZ5cGpWwz", //"your_paypal-app-client-ID",
password: "EBAPtB2_JPDoKsftonMYhsF7BWb1SIxCLD6IplXwNKRZEAgD1HOstsQr4Q7PVcT5vmXKcy7GTzY2rp2R" //"your-paypal-app-secret-ID
};
const options = {
method: 'post',
headers: {
'content-type': 'application/x-www-form-urlencoded',
'Access-Control-Allow-Credentials': true
},
//Make sure you use the qs.stringify for data
data: qs.stringify(data),
auth: auth,
url,
};
// Authorise with seller app information (clientId and secret key)
axios(options).then(response => {
setAccessToken(response.data.access_token)
//Resquest payal payment (It will load login page payment detail on the way)
axios.post(`https://api.sandbox.paypal.com/v1/payments/payment`, dataDetail,
{
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${response.data.access_token}`
}
}
)
.then(response => {
const { id, links } = response.data
const approvalUrl = links.find(data => data.rel == "approval_url").href
console.log("response", links)
setPaypalUrl(approvalUrl)
}).catch(err => {
console.log({ ...err })
})
}).catch(err => {
console.log(err)
})
};
/*---End Paypal checkout section---*/
onWebviewLoadStart = () => {
if (shouldShowWebViewLoading) {
SetIsWebViewLoading(true)
}
}
_onNavigationStateChange = (webViewState) => {
console.log("webViewState", webViewState)
//When the webViewState.title is empty this mean it's in process loading the first paypal page so there is no paypal's loading icon
//We show our loading icon then. After that we don't want to show our icon we need to set setShouldShowWebviewLoading to limit it
if (webViewState.title == "") {
//When the webview get here Don't need our loading anymore because there is one from paypal
setShouldShowWebviewLoading(false)
}
if (webViewState.url.includes('https://example.com/')) {
setPaypalUrl(null)
const urlArr = webViewState.url.split(/(=|&)/);
const paymentId = urlArr[2];
const payerId = urlArr[10];
axios.post(`https://api.sandbox.paypal.com/v1/payments/payment/${paymentId}/execute`, { payer_id: payerId },
{
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${accessToken}`
}
}
)
.then(response => {
setShouldShowWebviewLoading(true)
console.log(response)
}).catch(err => {
setShouldShowWebviewLoading(true)
console.log({ ...err })
})
}
}
return (
<React.Fragment>
<View style={styles.container}>
<Text>Paypal in React Native</Text>
<TouchableOpacity
activeOpacity={0.5}
onPress={buyBook}
style={
styles.btn
}>
<Text
style={{
fontSize: 22,
fontWeight: '400',
textAlign: 'center',
color: '#ffffff',
}}>
BUY NOW
</Text>
</TouchableOpacity>
</View>
{paypalUrl ? (
<View style={styles.webview}>
<WebView
style={{ height: "100%", width: "100%" }}
source={{ uri: paypalUrl }}
onNavigationStateChange={this._onNavigationStateChange}
javaScriptEnabled={true}
domStorageEnabled={true}
startInLoadingState={false}
onLoadStart={onWebviewLoadStart}
onLoadEnd={() => SetIsWebViewLoading(false)}
/>
</View>
) : null}
{isWebViewLoading ? (
<View style={{ ...StyleSheet.absoluteFill, justifyContent: "center", alignItems: "center", backgroundColor: "#ffffff" }}>
<ActivityIndicator size="small" color="#A02AE0" />
</View>
) : null}
</React.Fragment>
);
};
App.navigationOptions = {
title: 'App',
};
export default App;
const styles = StyleSheet.create({
container: {
width: '100%',
height: '100%',
justifyContent: "center",
alignItems: "center"
},
webview: {
width: '100%',
height: '100%',
position: 'absolute',
top: 0,
left: 0,
right: 0,
bottom: 0,
},
btn: {
paddingVertical: 5,
paddingHorizontal: 15,
borderRadius: 10,
backgroundColor: '#61E786',
justifyContent: 'center',
alignItems: 'center',
alignContent: 'center',
},
});