-
Notifications
You must be signed in to change notification settings - Fork 67
/
class-wc-payment-gateway-wcpay.php
346 lines (299 loc) · 10.7 KB
/
class-wc-payment-gateway-wcpay.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
<?php
/**
* Class WC_Payment_Gateway_WCPay
*
* @package WooCommerce\Payments
*/
if ( ! defined( 'ABSPATH' ) ) {
exit; // Exit if accessed directly.
}
/**
* Gateway class for WooCommerce Payments
*/
class WC_Payment_Gateway_WCPay extends WC_Payment_Gateway_CC {
/**
* Internal ID of the payment gateway.
*
* @type string
*/
const GATEWAY_ID = 'woocommerce_payments';
/**
* Client for making requests to the WooCommerce Payments API
*
* @var WC_Payments_API_Client
*/
private $payments_api_client;
/**
* Is test mode active?
*
* @var bool
*/
public $testmode;
/**
* API access publishable key
*
* @var string
*/
public $publishable_key;
/**
* Returns the URL of the configuration screen for this gateway, for use in internal links.
*
* @return string URL of the configuration screen for this gateway
*/
public static function get_settings_url() {
return admin_url( 'admin.php?page=wc-settings&tab=checkout§ion=' . self::GATEWAY_ID );
}
/**
* WC_Payment_Gateway_WCPay constructor.
*
* @param WC_Payments_API_Client $payments_api_client - WooCommerce Payments API client.
*/
public function __construct( WC_Payments_API_Client $payments_api_client ) {
$this->payments_api_client = $payments_api_client;
$this->id = self::GATEWAY_ID;
$this->icon = ''; // TODO: icon.
$this->has_fields = true;
$this->method_title = __( 'WooCommerce Payments', 'woocommerce-payments' );
$this->method_description = __( 'Accept payments via credit card.', 'woocommerce-payments' );
$this->supports = array(
'products',
'refunds',
);
// Define setting fields.
$this->form_fields = array(
'enabled' => array(
'title' => __( 'Enable/Disable', 'woocommerce-payments' ),
'label' => __( 'Enable WooCommerce Payments', 'woocommerce-payments' ),
'type' => 'checkbox',
'description' => '',
'default' => 'no',
),
'title' => array(
'title' => __( 'Title', 'woocommerce-payments' ),
'type' => 'text',
'description' => __( 'This controls the title which the user sees during checkout.', 'woocommerce-payments' ),
'default' => __( 'Credit Card', 'woocommerce-payments' ),
'desc_tip' => true,
),
'description' => array(
'title' => __( 'Description', 'woocommerce-payments' ),
'type' => 'text',
'description' => __( 'This controls the description which the user sees during checkout.', 'woocommerce-payments' ),
'default' => '',
'desc_tip' => true,
),
'stripe_account_id' => array(
'title' => __( 'Stripe Account ID', 'woocommerce-payments' ),
'type' => 'text',
'description' => __( 'Get your account ID from your Stripe account.', 'woocommerce-payments' ),
'default' => '',
'desc_tip' => true,
),
'testmode' => array(
'title' => __( 'Test mode', 'woocommerce-payments' ),
'label' => __( 'Enable Test Mode', 'woocommerce-payments' ),
'type' => 'checkbox',
'description' => __( 'Place the payment gateway in test mode using test API keys.', 'woocommerce-payments' ),
'default' => 'yes',
'desc_tip' => true,
),
'test_publishable_key' => array(
'title' => __( 'Test Publishable Key', 'woocommerce-payments' ),
'type' => 'password',
'description' => __( 'Get your API keys from your Stripe account.', 'woocommerce-payments' ),
'default' => '',
'desc_tip' => true,
),
'publishable_key' => array(
'title' => __( 'Live Publishable Key', 'woocommerce-payments' ),
'type' => 'password',
'description' => __( 'Get your API keys from your Stripe account.', 'woocommerce-payments' ),
'default' => '',
'desc_tip' => true,
),
);
// Load the settings.
$this->init_settings();
// Extract values we want to use in this class from the settings.
$this->title = $this->get_option( 'title' );
$this->description = $this->get_option( 'description' );
$this->testmode = ( ! empty( $this->settings['testmode'] ) && 'yes' === $this->settings['testmode'] ) ? true : false;
$this->publishable_key = ! empty( $this->settings['publishable_key'] ) ? $this->settings['publishable_key'] : '';
if ( $this->testmode ) {
$this->publishable_key = ! empty( $this->settings['test_publishable_key'] ) ? $this->settings['test_publishable_key'] : '';
}
add_action( 'woocommerce_update_options_payment_gateways_' . $this->id, array( $this, 'process_admin_options' ) );
}
/**
* Renders the Credit Card input fields needed to get the user's payment information on the checkout page.
*
* We also add the JavaScript which drives the UI.
*/
public function payment_fields() {
// Add JavaScript for the payment form.
$js_config = array(
'publishableKey' => $this->publishable_key,
'accountId' => $this->get_option( 'stripe_account_id' ),
);
// Register Stripe's JavaScript using the same ID as the Stripe Gateway plugin. This prevents this JS being
// loaded twice in the event a site has both plugins enabled. We still run the risk of different plugins
// loading different versions however.
wp_register_script(
'stripe',
'https://js.stripe.com/v3/',
array(),
'3.0',
true
);
wp_register_script(
'wc-payment-checkout',
plugins_url( 'assets/js/wc-payment-checkout.js', WCPAY_PLUGIN_FILE ),
array( 'stripe', 'wc-checkout' ),
filemtime( WCPAY_ABSPATH . 'assets/js/wc-payment-checkout.js' ),
true
);
wp_localize_script( 'wc-payment-checkout', 'wc_payment_config', $js_config );
wp_enqueue_script( 'wc-payment-checkout' );
wp_enqueue_style(
'wc-payment-checkout',
plugins_url( 'assets/css/wc-payment-checkout.css', WCPAY_PLUGIN_FILE ),
array(),
filemtime( WCPAY_ABSPATH . 'assets/css/wc-payment-checkout.css' )
);
// Output the form HTML.
?>
<fieldset>
<?php if ( ! empty( $this->get_description() ) ) : ?>
<legend><?php echo wp_kses_post( $this->get_description() ); ?></legend>
<?php endif; ?>
<div id="wc-payment-card-element"></div>
<div id="wc-payment-errors" role="alert"></div>
<input id="wc-payment-method" type="hidden" name="wc-payment-method" />
</fieldset>
<?php
}
/**
* Process the payment for a given order.
*
* @param int $order_id Order ID to process the payment for.
*
* @return array|null
*/
public function process_payment( $order_id ) {
$order = wc_get_order( $order_id );
try {
$amount = $order->get_total();
$transaction_id = '';
if ( $amount > 0 ) {
// Get the payment method from the request (generated when the user entered their card details).
$payment_method = $this->get_payment_method_from_request();
// Create intention, try to confirm it & capture the charge (if 3DS is not required).
$intent = $this->payments_api_client->create_and_confirm_intention(
round( (float) $amount * 100 ),
'usd',
$payment_method
);
// TODO: We're not handling *all* sorts of things here. For example, redirecting to a 3DS auth flow.
$transaction_id = $intent->get_id();
$note = sprintf(
/* translators: %1: the successfully charged amount, %2: transaction ID of the payment */
__( 'A payment of %1$s was successfully charged using WooCommerce Payments (Transaction #%2$s)', 'woocommerce-payments' ),
wc_price( $amount ),
$transaction_id
);
$order->add_order_note( $note );
$order->update_meta_data( '_charge_id', $intent->get_charge_id() );
$order->save();
}
$order->payment_complete( $transaction_id );
wc_reduce_stock_levels( $order_id );
WC()->cart->empty_cart();
return array(
'result' => 'success',
'redirect' => $this->get_return_url( $order ),
);
} catch ( Exception $e ) {
// TODO: Create or wire-up a logger for writing messages to the server filesystem.
// TODO: Create plugin specific exceptions so that we can be smarter about what we create notices for.
wc_add_notice( $e->getMessage(), 'error' );
$order->update_status( 'failed' );
return array(
'result' => 'fail',
'redirect' => '',
);
}
}
/**
* Extract the payment method from the request's POST variables
*
* @return string
* @throws Exception - If no payment method is found.
*/
private function get_payment_method_from_request() {
// phpcs:disable WordPress.Security.NonceVerification.NoNonceVerification
if ( ! isset( $_POST['wc-payment-method'] ) ) {
// If no payment method is set then stop here with an error.
throw new Exception( __( 'Payment method not found.', 'woocommerce-payments' ) );
}
$payment_method = wc_clean( $_POST['wc-payment-method'] ); //phpcs:ignore WordPress.Security.ValidatedSanitizedInput.MissingUnslash
// phpcs:enable WordPress.Security.NonceVerification.NoNonceVerification
return $payment_method;
}
/**
* Can the order be refunded?
*
* @param WC_Order $order Order object.
* @return bool
*/
public function can_refund_order( $order ) {
return $order && $order->get_meta( '_charge_id', true );
}
/**
* Refund a charge.
*
* @param int $order_id - the Order ID to process the refund for.
* @param float $amount - the amount to refund.
* @param string $reason - the reason for refunding.
*
* @return bool|WP_Error - Whether the refund went through, or an error.
*/
public function process_refund( $order_id, $amount = null, $reason = '' ) {
$order = wc_get_order( $order_id );
if ( ! $order ) {
return false;
}
$charge_id = $order->get_meta( '_charge_id', true );
if ( is_null( $amount ) ) {
$refund = $this->payments_api_client->refund_charge( $charge_id );
} else {
$refund = $this->payments_api_client->refund_charge( $charge_id, round( (float) $amount * 100 ) );
}
if ( is_wp_error( $refund ) ) {
// TODO log error.
$note = sprintf(
/* translators: %1: the successfully charged amount, %2: error message */
__( 'A refund of %1$s failed to complete: %2$s', 'woocommerce-payments' ),
wc_price( $amount ),
$refund->get_error_message()
);
$order->add_order_note( $note );
return $refund;
}
if ( empty( $reason ) ) {
$note = sprintf(
/* translators: %1: the successfully charged amount */
__( 'A refund of %1$s was successfully processed using WooCommerce Payments.', 'woocommerce-payments' ),
wc_price( $amount )
);
} else {
$note = sprintf(
/* translators: %1: the successfully charged amount, %2: reason */
__( 'A refund of %1$s was successfully processed using WooCommerce Payments. Reason: %2$s', 'woocommerce-payments' ),
wc_price( $amount ),
$reason
);
}
$order->add_order_note( $note );
return true;
}
}