-
Notifications
You must be signed in to change notification settings - Fork 20
/
class-wc-gateway-checkout-com-google-pay.php
396 lines (341 loc) · 16.5 KB
/
class-wc-gateway-checkout-com-google-pay.php
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
<?php
class WC_Gateway_Checkout_Com_Google_Pay extends WC_Payment_Gateway
{
/**
* WC_Gateway_Checkout_Com_Google_Pay constructor.
*/
public function __construct()
{
$this->id = 'wc_checkout_com_google_pay';
$this->method_title = __("Checkout.com", 'wc_checkout_com');
$this->method_description = __("The Checkout.com extension allows shop owners to process online payments through the <a href=\"https://www.checkout.com\">Checkout.com Payment Gateway.</a>", 'wc_checkout_com');
$this->title = __("Google Pay", 'wc_checkout_com');
$this->has_fields = true;
$this->supports = array( 'products', 'refunds');
$this->init_form_fields();
$this->init_settings();
// Turn these settings into variables we can use
foreach ( $this->settings as $setting_key => $value ) {
$this->$setting_key = $value;
}
add_action( 'woocommerce_update_options_payment_gateways_' . $this->id, array( $this, 'process_admin_options' ) );
// Generate token
add_action( 'woocommerce_api_wc_checkoutcom_googlepay_token', array( $this, 'generate_token' ) );
}
/**
* Show module configuration in backend
*
* @return string|void
*/
public function init_form_fields()
{
$this->form_fields = WC_Checkoutcom_Cards_Settings::google_settings();
$this->form_fields = array_merge( $this->form_fields, array(
'screen_button' => array(
'id' => 'screen_button',
'type' => 'screen_button',
'title' => __( 'Other Settings', 'wc_checkout_com' ),
)
));
}
/**
* @param $key
* @param $value
*/
public function generate_screen_button_html( $key, $value )
{
WC_Checkoutcom_Admin::generate_links($key, $value);
}
/**
* Show frames js on checkout page
*/
public function payment_fields()
{
global $woocommerce;
$core_settings = get_option('woocommerce_wc_checkout_com_cards_settings');
$environment = $core_settings['ckocom_environment'] == 'sandbox' ? true : false;
$currencyCode = get_woocommerce_currency();
$totalPrice = $woocommerce->cart->total;
$generate_token_url = str_replace( 'https:', 'http:', add_query_arg( 'wc-api', 'wc_checkoutcom_googlepay_token', home_url( '/' ) ) );
if(!empty($this->get_option( 'description' ))){
echo $this->get_option( 'description' );
}
?>
<input type="hidden" id="cko-google-signature" name="cko-google-signature" value="" />
<input type="hidden" id="cko-google-protocolVersion" name="cko-google-protocolVersion" value="" />
<input type="hidden" id="cko-google-signedMessage" name="cko-google-signedMessage" value="" />
<script>
googlePayUiController = (function () {
var DOMStrings = {
buttonId: 'ckocom_googlePay',
buttonClass: 'google-pay-button',
googleButtonArea: 'method_wc_checkout_com_google_pay',
buttonArea: '.form-row.place-order',
placeOrder: '#place_order',
paymentOptionLabel: '#dt_method_checkoutcomgooglepay > label:nth-child(2)',
iconSpacer: 'cko-wallet-icon-spacer',
token: 'google-cko-card-token',
paymentMethodName: 'wc_checkout_com_google_pay'
}
return {
hideDefaultPlaceOrder: function () {
jQuery("input[name='payment_method']").change(function(e){
jQuery(this).val() == DOMStrings.paymentMethodName ? jQuery(DOMStrings.placeOrder).hide() : jQuery(DOMStrings.placeOrder).show();
})
},
addGooglePayButton: function (type) {
// Create the Google Pay Button.
var button = document.createElement('button');
button.id = DOMStrings.buttonId;
// Add button class based on the user configuration.
button.className = DOMStrings.buttonClass + " " + type
// Append the Google Pay button to the GooglePay area.
jQuery('#payment').append(button);
// Hide Google Pay button
jQuery('#ckocom_googlePay').hide();
// On page load if Google Pay is selected, show the button.
if(jQuery('#payment_method_wc_checkout_com_google_pay').is(':checked')){
// Disable place order button.
jQuery('#place_order').hide();
// Show Google Pay button.
jQuery('#ckocom_googlePay').show();
}
},
addIconSpacer: function () {
jQuery(DOMStrings.paymentOptionLabel).append("<div class='" + iconSpacer + "'></div>")
},
getElements: function () {
return {
googlePayButtonId: jQuery(DOMStrings.buttonId),
googlePayButtonClass: jQuery(DOMStrings.buttonClass),
placeOrder: jQuery(DOMStrings.defaultPlaceOrder),
buttonArea: jQuery(DOMStrings.buttonArea),
};
},
getSelectors: function () {
return {
googlePayButtonId: DOMStrings.buttonId,
googlePayButtonClass: DOMStrings.buttonClass,
placeOrder: DOMStrings.defaultPlaceOrder,
buttonArea: DOMStrings.buttonArea,
token: DOMStrings.token,
};
}
}
})();
googlePayTransactionController = (function (googlePayUiController) {
var environment = '<?php echo $environment ?>' == false ? "PRODUCTION" : "TEST";
var publicKey = '<?php echo $core_settings['ckocom_pk'] ?>';
var merchantId = '<?php echo $this->get_option( 'ckocom_google_merchant_id' ) ?>';
var currencyCode = '<?php echo $currencyCode ?>';
var totalPrice = '<?php echo $totalPrice ?>';
var buttonType = '<?php echo $this->get_option( 'ckocom_google_style' ) ?>';
var generateTokenPath = '<?php echo $generate_token_url; ?>';
var allowedPaymentMethods = ['CARD', 'TOKENIZED_CARD'];
var allowedCardNetworks = ["AMEX", "DISCOVER", "JCB", "MASTERCARD", "VISA"];
var _setupClickListeners = function () {
jQuery(document).on('click', '#' + googlePayUiController.getSelectors().googlePayButtonId, function (e) {
e.preventDefault();
_startPaymentDataRequest();
});
}
var _getGooglePaymentDataConfiguration = function () {
return {
merchantId: merchantId,
paymentMethodTokenizationParameters: {
tokenizationType: 'PAYMENT_GATEWAY',
parameters: {
'gateway': 'checkoutltd',
'gatewayMerchantId': publicKey
}
},
allowedPaymentMethods: allowedPaymentMethods,
cardRequirements: {
allowedCardNetworks: allowedCardNetworks
}
};
}
var _getGoogleTransactionInfo = function () {
return {
currencyCode: currencyCode,
totalPriceStatus: 'FINAL',
totalPrice: totalPrice
};
}
var _getGooglePaymentsClient = function () {
return (new google.payments.api.PaymentsClient({ environment: environment }));
}
var _generateCheckoutToken = function (token, callback) {
var data = JSON.parse(token.paymentMethodToken.token);
jQuery.ajax({
type: 'POST',
url : generateTokenPath,
data: {
token: {
protocolVersion: data.protocolVersion,
signature: data.signature,
signedMessage: data.signedMessage
}
},
success: function (outcome) {
callback(outcome);
},
error: function (err) {
console.log(err);
}
});
}
var _startPaymentDataRequest = function () {
var paymentDataRequest = _getGooglePaymentDataConfiguration();
paymentDataRequest.transactionInfo = _getGoogleTransactionInfo();
var paymentsClient = _getGooglePaymentsClient();
paymentsClient.loadPaymentData(paymentDataRequest)
.then(function (paymentData) {
document.getElementById('cko-google-signature').value = JSON.parse(paymentData.paymentMethodToken.token).signature;
document.getElementById('cko-google-protocolVersion').value = JSON.parse(paymentData.paymentMethodToken.token).protocolVersion;
document.getElementById('cko-google-signedMessage').value = JSON.parse(paymentData.paymentMethodToken.token).signedMessage;
jQuery('#place_order').prop("disabled",false);
jQuery('#place_order').trigger('click');
})
.catch(function (err) {
console.error(err);
});
}
return {
init: function () {
_setupClickListeners();
googlePayUiController.hideDefaultPlaceOrder();
googlePayUiController.addGooglePayButton(buttonType);
}
}
})(googlePayUiController);
// Initialise Google Pay.
jQuery( document ).ready(function() {
googlePayTransactionController.init();
});
// Check if Google Pay method is checked.
if ( jQuery( '#payment_method_wc_checkout_com_google_pay' ).is( ':checked' ) ) {
// Disable place order button.
jQuery( '#place_order' ).prop( "disabled", true );
jQuery( '#place_order' ).hide();
jQuery( '#ckocom_googlePay' ).show();
} else {
// Enable place order button if not Google Pay.
jQuery( '#place_order' ).prop( "disabled", false );
jQuery( '#place_order' ).show();
jQuery( '#ckocom_googlePay' ).hide();
}
// On payment radio button click.
jQuery( "input[name='payment_method']" ).click( function () {
// Check if payment method is Google Pay.
if ( 'wc_checkout_com_google_pay' === this.value ) {
// Show Google Pay button.
jQuery( '#ckocom_googlePay' ).show();
// Disable place order button.
jQuery( '#place_order' ).prop( "disabled", true );
} else if ( 'wc_checkout_com_apple_pay' === this.value ) {
jQuery( '#ckocom_googlePay' ).hide();
jQuery( document ).ready( function () {
jQuery( "#place_order" ).hide();
} );
} else {
// Hide Google Pay button.
jQuery( '#ckocom_googlePay' ).hide();
// Enable place order button.
jQuery( '#place_order' ).prop( "disabled", false );
}
} )
</script>
<?php
}
/**
* Process payment with Google Pay.
*
* @param int $order_id
* @return array
*/
public function process_payment( $order_id )
{
if (!session_id()) session_start();
global $woocommerce;
$order = new WC_Order( $order_id );
// create google token from google payment data
$google_token = WC_Checkoutcom_Api_request::generate_google_token();
// Check if google token is not empty
if( empty( $google_token['token'] ) ) {
WC_Checkoutcom_Utility::wc_add_notice_self(__('There was an issue completing the payment.', 'wc_checkout_com'), 'error');
return;
}
// Create payment with google token
$result = (array) (new WC_Checkoutcom_Api_request)->create_payment($order, $google_token);
// Redirect to apm if redirection url is available.
if ( isset( $result['3d'] ) && ! empty( $result['3d'] ) ) {
return array(
'result' => 'success',
'redirect' => $result['3d'],
);
}
// check if result has error and return error message
if (isset($result['error']) && !empty($result['error'])) {
WC_Checkoutcom_Utility::wc_add_notice_self(__($result['error']), 'error');
return;
}
// Set action id as woo transaction id
update_post_meta($order_id, '_transaction_id', $result['action_id']);
update_post_meta($order_id, '_cko_payment_id', $result['id']);
// Get cko auth status configured in admin
$status = WC_Admin_Settings::get_option('ckocom_order_authorised', 'on-hold');
$message = __("Checkout.com Payment Authorised " ."</br>". " Action ID : {$result['action_id']} ", 'wc_checkout_com');
// check if payment was flagged
if ($result['risk']['flagged']) {
// Get cko auth status configured in admin
$status = WC_Admin_Settings::get_option('ckocom_order_flagged', 'flagged');
$message = __("Checkout.com Payment Flagged " ."</br>". " Action ID : {$result['action_id']} ", 'wc_checkout_com');
}
// add notes for the order and update status
$order->add_order_note($message);
$order->update_status($status);
// Reduce stock levels
wc_reduce_stock_levels( $order_id );
// Remove cart
$woocommerce->cart->empty_cart();
// Return thank you page
return array(
'result' => 'success',
'redirect' => $this->get_return_url( $order )
);
}
/**
* @param int $order_id
* @param null $amount
* @param string $reason
* @return bool|WP_Error
*/
public function process_refund($order_id, $amount = null, $reason = '')
{
$order = wc_get_order( $order_id );
$result = (array) WC_Checkoutcom_Api_request::refund_payment($order_id, $order);
// check if result has error and return error message
if (isset($result['error']) && !empty($result['error'])) {
WC_Checkoutcom_Utility::wc_add_notice_self(__($result['error']), 'error');
return false;
}
// Set action id as woo transaction id
update_post_meta($order_id, '_transaction_id', $result['action_id']);
// Get cko auth status configured in admin
$status = WC_Admin_Settings::get_option('ckocom_order_refunded', 'refunded');
$message = __("Checkout.com Payment refunded " ."</br>". " Action ID : {$result['action_id']} ", 'wc_checkout_com');
if(isset($_SESSION['cko-refund-is-less'])){
if($_SESSION['cko-refund-is-less']){
$status = WC_Admin_Settings::get_option('ckocom_order_captured', 'processing');
$order->add_order_note( __("Checkout.com Payment Partially refunded " ."</br>". " Action ID : {$result['action_id']}", 'wc_checkout_com') );
unset($_SESSION['cko-refund-is-less']);
return true;
}
}
// add notes for the order and update status
$order->add_order_note($message);
$order->update_status($status);
return true;
}
}