forked from aladrach/craft-apple-pay
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path_mobile-pay.html
443 lines (294 loc) · 9.25 KB
/
_mobile-pay.html
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
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
{# Use it like this where you want the button:
{% include 'checkout/_mobile-pay' %}
<div id="payment-request-button">
</div>
Stripe allows you to style the button as well.
#}
{% set statesByAbbreviation = {} %}
{% set statesByName = [] %}
{% for state in craft.commerce.states.allStates if state.countryId == 233 %}
{% set statesByAbbreviation = statesByAbbreviation|merge({(state.abbreviation):(state.id) }) %}
{% set statesByName = statesByName|merge({(state.name):(state.id) }) %}
{% endfor %}
<script src="https://js.stripe.com/v3/"></script>
<form method="POST" id="finalize-payment">
<input type="hidden" name="action" value="commerce/payments/pay"/>
{{ redirectInput('/checkout/success?number='~cart.number) }}
{{ csrfInput() }}
</form>
{% set publishableKey = '' %}
{% for method in craft.commerce.gateways.allCustomerEnabledGateways %}
{# Replace 'method.id' value with whatever the ID of your Apple Pay/Stripe method is. This can be simplified if you only have one payment method. #}
{% if method.id == 2 %}
{% set publishableKey = method.settings.publishableKey %}
{% endif %}
{% endfor %}
<script>
function parseName(fullName) {
var parts = fullName.toString().split(/\s+/);
var name = Object();
name.firstName = parts.slice(0, -1).join(" ");
name.lastName = parts.pop();
return name;
}
var stripe = Stripe('{{ publishableKey }}');
var paymentRequest = stripe.paymentRequest({
country: 'US',
currency: 'usd',
total: {
label: '{{ siteName }}',
amount: {{ cart.totalPrice|round(2) * 100 }},
},
requestShipping: true,
requestPayerName: true,
requestPayerEmail: true,
requestPayerPhone: true,
});
var elements = stripe.elements();
var prButton = elements.create('paymentRequestButton', {
paymentRequest: paymentRequest,
});
// Check the availability of the Payment Request API first.
paymentRequest.canMakePayment().then(function(result) {
if (result) {
prButton.mount('#payment-request-button');
// if you need to show or do anything else here to make the button work.
// we show a special - OR - to separate mobile pay from the rest of the checkout similar to Shopify
//$("#or-hr-seperator").css("display", "block");
} else {
document.getElementById('payment-request-button').style.display = 'none';
}
});
// complete payment
paymentRequest.on('token', function(ev) {
// Send the token to your server to charge it!
//console.log(ev);
var statesByName = {{ statesByName|json_encode|raw}}
var statesByAbbr = {{ statesByAbbreviation|json_encode|raw}}
// Map result fields to Craft fields
var theState = ev.shippingAddress.region;
if (theState.length == 2) {
var stateId = statesByAbbr[theState];
} else {
var stateId = statesByName[theState];
}
// setup the JSON
var payerName = window.parseName(ev.payerName);
//console.log(payerName);
var contactUpdate = [
{ name: "{{ craft.app.config.general.csrfTokenName|e('js') }}",
value: "{{ craft.app.request.csrfToken|e('js') }}"
},
{
name: "action",
value: "commerce/cart/update-cart"
},
{
name: "email",
value: ev.payerEmail
},
{
name: "orderNumber",
value: "{{ cart.number }}"
},
{
name: "billingAddressSameAsShipping",
value: "1"
},
{
name: "gatewayId",
value: "2"
},
{
name: "paymentMethod",
value: "2"
},
{
name: "shippingAddress[firstName]",
value: payerName.firstName
},
{
name: "shippingAddress[lastName]",
value: payerName.lastName
},
{
name: "shippingAddress[address1]",
value: ev.shippingAddress.addressLine[0]
},
{
name: "shippingAddress[address2]",
value: ev.shippingAddress.addressLine[1]
},
{
name: "shippingAddress[city]",
value: ev.shippingAddress.city
},
{
name: "shippingAddress[stateValue]",
value: stateId
},
{
name: "shippingAddress[zipCode]",
value: ev.shippingAddress.postalCode
},
{
name: "shippingAddress[phone]",
value: ev.payerPhone
},
{
name: "shippingAddress[countryId]",
value: "233"
}
];
var stripeToken = ev.token.id;
$.ajax({
type: 'post',
url: '',
data: contactUpdate,
dataType: 'json',
headers: {'Content-Type': 'application/x-www-form-urlencoded'},
success: function(response) {
if (response.success) {
//console.log('updated! Trying payment...');
// cart was updated, now make the payment
$('#finalize-payment').append($('<input type="hidden" name="email">').val(ev.payerEmail));
$('#finalize-payment').append($('<input type="hidden" name="orderNumber">').val('{{ cart.number }}'));
$('#finalize-payment').append($('<input type="hidden" name="gatewayId">').val(2));
$('#finalize-payment').append($('<input type="hidden" name="stripeToken">').val(stripeToken));
// make the payment
ev.complete('success');
$('#finalize-payment').submit();
} else {
ev.complete('fail');
}
}
});
});
paymentRequest.on('shippingaddresschange', function(ev) {
if (ev.shippingAddress.country !== 'US') {
ev.updateWith({status: 'invalid_shipping_address'});
} else {
// Perform server-side request to fetch shipping options
// update the cart to get the data
//console.log(ev);
var statesByName = {{ statesByName|json_encode|raw}}
var statesByAbbr = {{ statesByAbbreviation|json_encode|raw}}
// Map result fields to Craft fields
var theState = ev.shippingAddress.region;
if (theState.length == 2) {
var stateId = statesByAbbr[theState];
} else {
var stateId = statesByName[theState];
}
// setup the JSON
var contactUpdate = [
{ name: "{{ craft.app.config.general.csrfTokenName|e('js') }}",
value: "{{ craft.app.request.csrfToken|e('js') }}"
},
{
name: "action",
value: "commerce/cart/update-cart"
},
{
name: "email",
value: "{{ cart.email }}"
},
{
name: "orderNumber",
value: "{{ cart.number }}"
},
{
name: "billingAddressSameAsShipping",
value: "1"
},
{
name: "gatewayId",
value: "2"
},
{
name: "shippingAddress[firstName]",
value: 'Customer'
},
{
name: "shippingAddress[lastName]",
value: 'Last Name'
},
{
name: "shippingAddress[city]",
value: ev.shippingAddress.city
},
{
name: "shippingAddress[stateValue]",
value: stateId
},
{
name: "shippingAddress[zipCode]",
value: ev.shippingAddress.postalCode
},
/*
{
name: "shippingAddress[phone]",
value: ev.shippingAddress.phoneNumber
},
*/
{
name: "shippingAddress[countryId]",
value: "233"
}
/*
{
name: "stripeToken",
value: ev.token.id
}*/
];
// console.log('updating cart');
// console.log(contactUpdate);
$.ajax({
type: 'post',
url: '',
data: contactUpdate,
dataType: 'json',
headers: {'Content-Type': 'application/x-www-form-urlencoded'},
success: function(response) {
//console.log(response);
var shippingLabels = [];
{% for i in craft.commerce.shippingMethods.allShippingMethods %}
shippingLabels['{{i.handle }}'] = '{{ i.name }}';
{% endfor %}
if (response.success) {
//console.log(response);
var shippingMethod = [ { id: response.cart.shippingMethodId,
label: shippingLabels[response.cart.shippingMethod],
amount: Math.round(response.cart.totalShippingCost * 100)
}
]
ev.updateWith({
status: 'success',
displayItems: [
{
label: 'Item Subtotal',
amount: Math.round(response.cart.itemSubtotal * 100)
},
{
label: 'Shipping',
amount: Math.round(response.cart.totalShippingCost * 100)
},
{
label: 'Taxes',
amount: Math.round(response.cart.totalTax * 100)
},
],
total: {
label: '{{ siteName }}',
amount: Math.round(response.cart.totalPrice * 100)
},
shippingOptions: shippingMethod
});
} else {
//console.log(repsonse);
}
}
});
}
});
</script>