class-wc-stripe-order-handler.php
12.7 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
372
373
374
375
376
377
378
379
380
<?php
if ( ! defined( 'ABSPATH' ) ) {
exit;
}
/**
* Handles and process orders from asyncronous flows.
*
* @since 4.0.0
*/
class WC_Stripe_Order_Handler extends WC_Stripe_Payment_Gateway {
private static $_this;
/**
* Constructor.
*
* @since 4.0.0
* @version 4.0.0
*/
public function __construct() {
self::$_this = $this;
add_action( 'wp', [ $this, 'maybe_process_redirect_order' ] );
add_action( 'woocommerce_order_status_processing', [ $this, 'capture_payment' ] );
add_action( 'woocommerce_order_status_completed', [ $this, 'capture_payment' ] );
add_action( 'woocommerce_order_status_cancelled', [ $this, 'cancel_payment' ] );
add_action( 'woocommerce_order_status_refunded', [ $this, 'cancel_payment' ] );
add_filter( 'woocommerce_tracks_event_properties', [ $this, 'woocommerce_tracks_event_properties' ], 10, 2 );
}
/**
* Public access to instance object.
*
* @since 4.0.0
* @version 4.0.0
*/
public static function get_instance() {
return self::$_this;
}
/**
* Processes payments.
* Note at this time the original source has already been
* saved to a customer card (if applicable) from process_payment.
*
* @since 4.0.0
* @since 4.1.8 Add $previous_error parameter.
* @param int $order_id
* @param bool $retry
* @param mix $previous_error Any error message from previous request.
*/
public function process_redirect_payment( $order_id, $retry = true, $previous_error = false ) {
try {
$source = isset( $_GET['source'] ) ? wc_clean( wp_unslash( $_GET['source'] ) ) : '';
if ( empty( $source ) ) {
return;
}
if ( empty( $order_id ) ) {
return;
}
$order = wc_get_order( $order_id );
if ( ! is_object( $order ) ) {
return;
}
if ( $order->has_status( [ 'processing', 'completed', 'on-hold' ] ) ) {
return;
}
// Result from Stripe API request.
$response = null;
// This will throw exception if not valid.
$this->validate_minimum_order_amount( $order );
WC_Stripe_Logger::log( "Info: (Redirect) Begin processing payment for order $order_id for the amount of {$order->get_total()}" );
/**
* First check if the source is chargeable at this time. If not,
* webhook will take care of it later.
*/
$source_info = WC_Stripe_API::retrieve( 'sources/' . $source );
if ( ! empty( $source_info->error ) ) {
throw new WC_Stripe_Exception( print_r( $source_info, true ), $source_info->error->message );
}
if ( 'failed' === $source_info->status || 'canceled' === $source_info->status ) {
throw new WC_Stripe_Exception( print_r( $source_info, true ), __( 'Unable to process this payment, please try again or use alternative method.', 'woocommerce-gateway-stripe' ) );
}
// If already consumed, then ignore request.
if ( 'consumed' === $source_info->status ) {
return;
}
// If not chargeable, then ignore request.
if ( 'chargeable' !== $source_info->status ) {
return;
}
// Prep source object.
$prepared_source = $this->prepare_order_source( $order );
$prepared_source->status = 'chargeable';
/*
* If we're doing a retry and source is chargeable, we need to pass
* a different idempotency key and retry for success.
*/
if ( $this->need_update_idempotency_key( $prepared_source, $previous_error ) ) {
add_filter( 'wc_stripe_idempotency_key', [ $this, 'change_idempotency_key' ], 10, 2 );
}
// Make the request.
$response = WC_Stripe_API::request( $this->generate_payment_request( $order, $prepared_source ), 'charges', 'POST', true );
$headers = $response['headers'];
$response = $response['body'];
if ( ! empty( $response->error ) ) {
// Customer param wrong? The user may have been deleted on stripe's end. Remove customer_id. Can be retried without.
if ( $this->is_no_such_customer_error( $response->error ) ) {
delete_user_option( $order->get_customer_id(), '_stripe_customer_id' );
$order->delete_meta_data( '_stripe_customer_id' );
$order->save();
}
if ( $this->is_no_such_token_error( $response->error ) && $prepared_source->token_id ) {
// Source param wrong? The CARD may have been deleted on stripe's end. Remove token and show message.
$wc_token = WC_Payment_Tokens::get( $prepared_source->token_id );
$wc_token->delete();
$localized_message = __( 'This card is no longer available and has been removed.', 'woocommerce-gateway-stripe' );
$order->add_order_note( $localized_message );
throw new WC_Stripe_Exception( print_r( $response, true ), $localized_message );
}
// We want to retry.
if ( $this->is_retryable_error( $response->error ) ) {
if ( $retry ) {
// Don't do anymore retries after this.
if ( 5 <= $this->retry_interval ) {
return $this->process_redirect_payment( $order_id, false, $response->error );
}
sleep( $this->retry_interval );
$this->retry_interval++;
return $this->process_redirect_payment( $order_id, true, $response->error );
} else {
$localized_message = __( 'Sorry, we are unable to process your payment at this time. Please retry later.', 'woocommerce-gateway-stripe' );
$order->add_order_note( $localized_message );
throw new WC_Stripe_Exception( print_r( $response, true ), $localized_message );
}
}
$localized_messages = WC_Stripe_Helper::get_localized_messages();
if ( 'card_error' === $response->error->type ) {
$message = isset( $localized_messages[ $response->error->code ] ) ? $localized_messages[ $response->error->code ] : $response->error->message;
} else {
$message = isset( $localized_messages[ $response->error->type ] ) ? $localized_messages[ $response->error->type ] : $response->error->message;
}
throw new WC_Stripe_Exception( print_r( $response, true ), $message );
}
// To prevent double processing the order on WC side.
if ( ! $this->is_original_request( $headers ) ) {
return;
}
do_action( 'wc_gateway_stripe_process_redirect_payment', $response, $order );
$this->process_response( $response, $order );
} catch ( WC_Stripe_Exception $e ) {
WC_Stripe_Logger::log( 'Error: ' . $e->getMessage() );
do_action( 'wc_gateway_stripe_process_redirect_payment_error', $e, $order );
/* translators: error message */
$order->update_status( 'failed', sprintf( __( 'Stripe payment failed: %s', 'woocommerce-gateway-stripe' ), $e->getLocalizedMessage() ) );
wc_add_notice( $e->getLocalizedMessage(), 'error' );
wp_safe_redirect( wc_get_checkout_url() );
exit;
}
}
/**
* Processes the orders that are redirected.
*
* @since 4.0.0
* @version 4.0.0
*/
public function maybe_process_redirect_order() {
if ( ! is_order_received_page() || empty( $_GET['client_secret'] ) || empty( $_GET['source'] ) ) {
return;
}
$order_id = isset( $_GET['order_id'] ) ? wc_clean( wp_unslash( $_GET['order_id'] ) ) : '';
$this->process_redirect_payment( $order_id );
}
/**
* Capture payment when the order is changed from on-hold to complete or processing.
*
* @since 3.1.0
* @version 4.0.0
* @param int $order_id
* @return stdClass|void Result of payment capture.
*/
public function capture_payment( $order_id ) {
$order = wc_get_order( $order_id );
if ( 'stripe' === $order->get_payment_method() ) {
$charge = $order->get_transaction_id();
$captured = $order->get_meta( '_stripe_charge_captured', true );
$is_stripe_captured = false;
if ( $charge && 'no' === $captured ) {
$order_total = $order->get_total();
if ( 0 < $order->get_total_refunded() ) {
$order_total = $order_total - $order->get_total_refunded();
}
$intent = $this->get_intent_from_order( $order );
if ( $intent ) {
// If the order has a Payment Intent, then the Intent itself must be captured, not the Charge
if ( ! empty( $intent->error ) ) {
/* translators: error message */
$order->add_order_note( sprintf( __( 'Unable to capture charge! %s', 'woocommerce-gateway-stripe' ), $intent->error->message ) );
} elseif ( 'requires_capture' === $intent->status ) {
$level3_data = $this->get_level3_data_from_order( $order );
$result = WC_Stripe_API::request_with_level3_data(
[
'amount' => WC_Stripe_Helper::get_stripe_amount( $order_total ),
'expand[]' => 'charges.data.balance_transaction',
],
'payment_intents/' . $intent->id . '/capture',
$level3_data,
$order
);
if ( ! empty( $result->error ) ) {
/* translators: error message */
$order->update_status( 'failed', sprintf( __( 'Unable to capture charge! %s', 'woocommerce-gateway-stripe' ), $result->error->message ) );
} else {
$is_stripe_captured = true;
$result = end( $result->charges->data );
}
} elseif ( 'succeeded' === $intent->status ) {
$is_stripe_captured = true;
}
} else {
// The order doesn't have a Payment Intent, fall back to capturing the Charge directly
// First retrieve charge to see if it has been captured.
$result = WC_Stripe_API::retrieve( 'charges/' . $charge );
if ( ! empty( $result->error ) ) {
/* translators: error message */
$order->add_order_note( sprintf( __( 'Unable to capture charge! %s', 'woocommerce-gateway-stripe' ), $result->error->message ) );
} elseif ( false === $result->captured ) {
$level3_data = $this->get_level3_data_from_order( $order );
$result = WC_Stripe_API::request_with_level3_data(
[
'amount' => WC_Stripe_Helper::get_stripe_amount( $order_total ),
'expand[]' => 'balance_transaction',
],
'charges/' . $charge . '/capture',
$level3_data,
$order
);
if ( ! empty( $result->error ) ) {
/* translators: error message */
$order->update_status( 'failed', sprintf( __( 'Unable to capture charge! %s', 'woocommerce-gateway-stripe' ), $result->error->message ) );
} else {
$is_stripe_captured = true;
}
} elseif ( true === $result->captured ) {
$is_stripe_captured = true;
}
}
if ( $is_stripe_captured ) {
/* translators: transaction id */
$order->add_order_note( sprintf( __( 'Stripe charge complete (Charge ID: %s)', 'woocommerce-gateway-stripe' ), $result->id ) );
$order->update_meta_data( '_stripe_charge_captured', 'yes' );
// Store other data such as fees
$order->set_transaction_id( $result->id );
if ( is_callable( [ $order, 'save' ] ) ) {
$order->save();
}
$this->update_fees( $order, $result->balance_transaction->id );
}
// This hook fires when admin manually changes order status to processing or completed.
do_action( 'woocommerce_stripe_process_manual_capture', $order, $result );
return $result;
}
}
}
/**
* Cancel pre-auth on refund/cancellation.
*
* @since 3.1.0
* @version 4.2.2
* @param int $order_id
*/
public function cancel_payment( $order_id ) {
$order = wc_get_order( $order_id );
if ( 'stripe' === $order->get_payment_method() ) {
$captured = $order->get_meta( '_stripe_charge_captured', true );
if ( 'no' === $captured ) {
$this->process_refund( $order_id );
}
// This hook fires when admin manually changes order status to cancel.
do_action( 'woocommerce_stripe_process_manual_cancel', $order );
}
}
/**
* Filter. Adds additional meta data to Tracks events.
* Note that this filter is only called if WC_Site_Tracking::is_tracking_enabled.
*
* @since 4.5.1
* @param array Properties to be appended to.
* @param string Event name, e.g. orders_edit_status_change.
*/
public function woocommerce_tracks_event_properties( $properties, $prefixed_event_name ) {
// Not the desired event? Bail.
if ( 'wcadmin_orders_edit_status_change' != $prefixed_event_name ) {
return $properties;
}
// Properties not an array? Bail.
if ( ! is_array( $properties ) ) {
return $properties;
}
// No payment_method in properties? Bail.
if ( ! array_key_exists( 'payment_method', $properties ) ) {
return $properties;
}
// Not stripe? Bail.
if ( 'stripe' != $properties['payment_method'] ) {
return $properties;
}
// Due diligence done. Collect the metadata.
$is_live = true;
$stripe_settings = get_option( 'woocommerce_stripe_settings', [] );
if ( array_key_exists( 'testmode', $stripe_settings ) ) {
$is_live = 'no' === $stripe_settings['testmode'];
}
$properties['admin_email'] = get_option( 'admin_email' );
$properties['is_live'] = $is_live;
$properties['woocommerce_gateway_stripe_version'] = WC_STRIPE_VERSION;
$properties['woocommerce_default_country'] = get_option( 'woocommerce_default_country' );
return $properties;
}
}
new WC_Stripe_Order_Handler();