This repository has been archived by the owner on Feb 20, 2024. It is now read-only.
forked from conekta/ct-woocommerce-plugin
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathconekta_cash_gateway.php
executable file
·412 lines (366 loc) · 16 KB
/
conekta_cash_gateway.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
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
<?php
if (!class_exists('Conekta')) {
require_once("lib/conekta-php/lib/Conekta.php");
}
/*
* Title : Conekta Payment extension for WooCommerce
* Author : Conekta.io
* Url : https://wordpress.org/plugins/conekta-woocommerce
*/
class WC_Conekta_Cash_Gateway extends WC_Conekta_Plugin
{
protected $GATEWAY_NAME = "WC_Conekta_Cash_Gateway";
protected $use_sandbox_api = true;
protected $order = null;
protected $transaction_id = null;
protected $transaction_error_message = null;
protected $conekta_test_api_key = '';
protected $conekta_live_api_key = '';
protected $publishable_key = '';
/**
* @var string
*/
public $id;
public $method_title;
public $has_fields;
public $title;
public $icon;
public $test_api_key;
public $live_api_key;
public $secret_key;
public $lang_options;
public function __construct()
{
$this->id = 'conektaoxxopay';
$this->method_title = __( 'Conekta Oxxo Pay', 'woocommerce' );
$this->has_fields = true;
$this->ckpg_init_form_fields();
$this->init_settings();
$this->title = $this->settings['title'];
$this->description = '';
$this->icon = $this->settings['alternate_imageurl'] ?
$this->settings['alternate_imageurl'] :
WP_PLUGIN_URL . "/" . plugin_basename( dirname(__FILE__)) . '/images/oxxopay.png';
$this->use_sandbox_api = strcmp($this->settings['debug'], 'yes') == 0;
$this->test_api_key = $this->settings['test_api_key'];
$this->live_api_key = $this->settings['live_api_key'];
$this->secret_key = $this->use_sandbox_api ?
$this->test_api_key :
$this->live_api_key;
$this->lang_options = parent::ckpg_set_locale_options()->ckpg_get_lang_options();
if (empty($this->secret_key)){
$this->enabled = false;
}
add_action(
'woocommerce_update_options_payment_gateways_' . $this->id ,
array($this, 'process_admin_options')
);
add_action(
'woocommerce_thankyou_' . $this->id,
array($this, 'ckpg_thankyou_page')
);
add_action(
'woocommerce_email_before_order_table',
array($this, 'ckpg_email_instructions')
);
add_action(
'woocommerce_email_before_order_table',
array($this, 'ckpg_email_reference')
);
add_action(
'woocommerce_api_' . strtolower(get_class($this)),
array($this, 'ckpg_webhook_handler')
);
}
/**
* Updates the status of the order.
* Webhook needs to be added to Conekta account tusitio.com/wc-api/WC_Conekta_Cash_Gateway
*/
public function ckpg_webhook_handler()
{
header('HTTP/1.1 200 OK');
$body = @file_get_contents('php://input');
$event = json_decode($body, true);
// Respondiendo a eventos "ping"
if (isset($event['type']) && $event['type'] === 'webhook_ping') {
header('Content-Type: application/json');
echo json_encode(['message' => 'OK']);
exit; // Salir de la función después de manejar el evento ping
}
$conekta_order = $event['data']['object'];
$charge = $conekta_order['charges']['data'][0];
$order_id = $conekta_order['metadata']['reference_id'];
$order = new WC_Order($order_id);
// paid orders
if ($event['type'] === "order.paid"
&& $charge['payment_method']['type'] === "oxxo") {
$paid_at = date("Y-m-d", $charge['paid_at']);
update_post_meta($order->get_id(), 'conekta-paid-at', $paid_at);
$order->payment_complete();
$order->add_order_note(sprintf("Payment completed in Oxxo and notification of payment received"));
parent::ckpg_offline_payment_notification($order_id, $conekta_order['customer_info']['name']);
}
// expired orders
if ( ($event['type'] === "order.expired" || $event['type'] ==="order.canceled")
&& $charge['payment_method']['type'] === "oxxo") {
$order->update_status('cancelled', 'Order expired in Conekta.');
}
}
public function ckpg_init_form_fields()
{
$this->form_fields = array(
'enabled' => array(
'type' => 'checkbox',
'title' => __('Enable/Disable', 'woothemes'),
'label' => __('Enable Conekta Oxxo Pay Payment', 'woothemes'),
'default' => 'yes'
),
'debug' => array(
'type' => 'checkbox',
'title' => __('Testing', 'woothemes'),
'label' => __('Turn on testing', 'woothemes'),
'default' => 'no'
),
'title' => array(
'type' => 'text',
'title' => __('Title', 'woothemes'),
'description' => __('This controls the title which the user sees during checkout.', 'woothemes'),
'default' => __('Conekta Pago en Efectivo en Oxxo Pay', 'woothemes')
),
'test_api_key' => array(
'type' => 'password',
'title' => __('Conekta API Test Private key', 'woothemes'),
'default' => __('', 'woothemes')
),
'live_api_key' => array(
'type' => 'password',
'title' => __('Conekta API Live Private key', 'woothemes'),
'default' => __('', 'woothemes')
),
'expiration_days' => array(
'type' => 'text',
'title' => __('Expiration time (in days) for the reference', 'woothemes'),
'default' => __('30', 'woothemes')
),
'alternate_imageurl' => array(
'type' => 'text',
'title' => __('Alternate Image to display on checkout, use fullly qualified url, served via https', 'woothemes'),
'default' => __('', 'woothemes')
),
'description' => array(
'title' => __( 'Description', 'woocommerce' ),
'type' => 'textarea',
'description' => __('Payment method description that the customer will see on your checkout.', 'woocommerce'),
'default' =>__('Por favor realiza el pago en el OXXO más cercano utilizando la referencia que se encuentra a continuación.', 'woocommerce' ),
'desc_tip' => true,
),
'instructions' => array(
'title' => __( 'Instructions', 'woocommerce' ),
'type' => 'textarea',
'description' => __('Instructions that will be added to the thank you page and emails.', 'woocommerce'),
'default' =>__('Por favor realiza el pago en el OXXO más cercano utilizando la referencia que se encuentra a continuación.', 'woocommerce'),
'desc_tip' => true,
),
);
}
/**
* Output for the order received page.
*
* @param string $order_id
*/
// this echo's may were safe of validation, because there are proveided by os
function ckpg_thankyou_page($order_id) {
$order = new WC_Order( $order_id );
echo '<p style="font-size: 30px"><strong>'.__('Referencia').':</strong> ' . esc_html( get_post_meta( $order->get_id(), 'conekta-referencia', true ) ). '</p>';
echo '<p>OXXO cobrará una comisión adicional al momento de realizar el pago.</p>';
echo '<p>INSTRUCCIONES:'. esc_html($this->settings['instructions']) .'</p>';
}
/**
* Add content to the WC emails.
*
* @access public
* @param WC_Order $order
*/
function ckpg_email_reference($order) {
if (get_post_meta( $order->get_id(), 'conekta-referencia', true ) != null)
{
echo '<p style="font-size: 30px"><strong>'.__('Referencia').':</strong> ' . esc_html(get_post_meta( $order->get_id(), 'conekta-referencia', true )). '</p>';
echo '<p>OXXO cobrará una comisión adicional al momento de realizar el pago.</p>';
echo '<p>INSTRUCCIONES:'. esc_html($this->settings['instructions']) .'</p>';
}
}
/**
* Add content to the WC emails.
*
* @access public
* @param WC_Order $order
* @param bool $sent_to_admin
* @param bool $plain_text
*/
public function ckpg_email_instructions( $order, $sent_to_admin = false, $plain_text = false ) {
if (get_post_meta( $order->get_id(), '_payment_method', true ) === $this->id){
$instructions = $this->form_fields['instructions'];
if ( $instructions && 'on-hold' === $order->get_status() ) {
echo wpautop( wptexturize( esc_html($instructions['default'] ) ) ). PHP_EOL;
}
}
}
public function ckpg_admin_options()
{
include_once('templates/cash_admin.php');
}
public function payment_fields()
{
include_once('templates/cash.php');
}
protected function ckpg_send_to_conekta()
{
global $woocommerce;
include_once('conekta_gateway_helper.php');
\Conekta\Conekta::setApiKey($this->secret_key);
\Conekta\Conekta::setApiVersion('2.0.0');
\Conekta\Conekta::setPlugin($this->name);
\Conekta\Conekta::setPluginVersion($this->version);
\Conekta\Conekta::setLocale('es');
$data = ckpg_get_request_data($this->order);
$amount = (int) $data['amount'];
$items = $this->order->get_items();
$taxes = $this->order->get_taxes();
$line_items = ckpg_build_line_items($items, parent::ckpg_get_version());
$discount_lines = ckpg_build_discount_lines($data);
$shipping_lines = ckpg_build_shipping_lines($data);
$shipping_contact = ckpg_build_shipping_contact($data);
$tax_lines = ckpg_build_tax_lines($taxes);
$customer_info = ckpg_build_customer_info($data);
$order_metadata = ckpg_build_order_metadata($data + array(
'plugin_conekta_version' => $this->version,
'woocommerce_version' => $woocommerce->version,
)
);
$order_details = array(
'currency' => $data['currency'],
'line_items' => $line_items,
'customer_info' => $customer_info,
'shipping_lines' => $shipping_lines,
'discount_lines' => $discount_lines,
'tax_lines' => $tax_lines
);
if (!empty($shipping_contact)) {
$order_details = array_merge($order_details, array('shipping_contact' => $shipping_contact));
}
if (!empty($order_metadata)) {
$order_details = array_merge($order_details, array('metadata' => $order_metadata));
}
$order_details = ckpg_check_balance($order_details, $amount);
try {
$conekta_order_id = esc_html(get_post_meta($this->order->get_id(), 'conekta-order-id', true));
if (!empty($conekta_order_id)) {
$order = \Conekta\Order::find($conekta_order_id);
$order->update($order_details);
} else {
$order = \Conekta\Order::create($order_details);
}
update_post_meta($this->order->get_id(), 'conekta-order-id', $order->id);
$expires_at = time() + ($this->settings['expiration_days'] * 86400);
$charge_details = array(
'payment_method' => array(
'type' => 'oxxo_cash',
'expires_at' => $expires_at
),
'amount' => $amount
);
$charge = $order->createCharge($charge_details);
$this->transaction_id = $charge->id;
update_post_meta($this->order->get_id(), 'conekta-id', $charge->id);
update_post_meta($this->order->get_id(), 'conekta-creado', $charge->created_at);
update_post_meta($this->order->get_id(), 'conekta-expira', $charge->payment_method->expires_at);
update_post_meta($this->order->get_id(), 'conekta-referencia', $charge->payment_method->reference);
return true;
} catch(\Conekta\Handler $e) {
$description = $e->getMessage();
global $wp_version;
if (version_compare($wp_version, '4.1', '>=')) {
wc_add_notice(__('Error: ', 'woothemes') . $description , $notice_type = 'error');
} else {
error_log('Gateway Error:' . $description . "\n");
$woocommerce->add_error(__('Error: ', 'woothemes') . $description);
}
return false;
}
}
public function process_payment($order_id)
{
global $woocommerce;
$this->order = new WC_Order($order_id);
if ($this->ckpg_send_to_conekta())
{
// Mark as on-hold (we're awaiting the notification of payment)
$this->order->update_status('on-hold', __( 'Awaiting the conekta OXXO payment', 'woocommerce' ));
// Remove cart
$woocommerce->cart->empty_cart();
unset($_SESSION['order_awaiting_payment']);
$result = array(
'result' => 'success',
'redirect' => $this->get_return_url($this->order)
);
return $result;
}
else
{
$this->ckpg_mark_as_failed_payment();
global $wp_version;
if (version_compare($wp_version, '4.1', '>=')) {
wc_add_notice(__('Transaction Error: Could not complete the payment', 'woothemes'), $notice_type = 'error');
} else {
$woocommerce->add_error(__('Transaction Error: Could not complete the payment'), 'woothemes');
}
}
}
protected function ckpg_mark_as_failed_payment()
{
$this->order->add_order_note(
sprintf(
"%s Oxxo Pay Payment Failed : '%s'",
$this->GATEWAY_NAME,
$this->transaction_error_message
)
);
}
protected function ckpg_complete_order()
{
global $woocommerce;
if ($this->order->get_status() == 'completed')
return;
$this->order->payment_complete();
$woocommerce->cart->empty_cart();
$this->order->add_order_note(
sprintf(
"%s payment completed with Transaction Id of '%s'",
$this->GATEWAY_NAME,
$this->transaction_id
)
);
unset($_SESSION['order_awaiting_payment']);
}
}
function ckpg_conekta_cash_order_status_completed($order_id = null)
{
global $woocommerce;
if (!$order_id){
$order_id = sanitize_text_field((string) $_POST['order_id']);
}
$data = get_post_meta( $order_id );
$total = $data['_order_total'][0] * 100;
$amount = floatval($_POST['amount']);
if(isset($amount))
{
$params['amount'] = round($amount);
}
}
function ckpg_conektacheckout_add_cash_gateway($methods)
{
array_push($methods, 'WC_Conekta_Cash_Gateway');
return $methods;
}
add_filter('woocommerce_payment_gateways', 'ckpg_conektacheckout_add_cash_gateway');
add_action('woocommerce_order_status_processing_to_completed', 'ckpg_conekta_cash_order_status_completed' );