-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsmartcoin_gateway.php
473 lines (427 loc) · 17.7 KB
/
smartcoin_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
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
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
<?php
require_once('lib/smartcoin-php/lib/Smartcoin.php');
class Smartcoin extends WC_Payment_Gateway {
protected $GATEWAY_NAME = "Smartcoin";
protected $use_test_api = true;
protected $order = null;
protected $transaction_id = null;
protected $transaction_error_message = null;
public function __construct() {
$this->id = 'Smartcoin';
$this->has_fields = true;
$this->init_form_fields();
$this->init_settings();
$this->supports = array(
'refunds'
);
$this->title = $this->get_option( 'title' );;
$this->description = '';
$this->icon = '';
$this->show_radio_button = strcmp($this->get_option('sc_show_radio_button'),'yes') == 0;
$this->use_test_api = strcmp($this->get_option('sc_debug'),'yes') == 0;
$this->test_api_key = $this->get_option('sc_test_api_key');
$this->test_api_secret = $this->get_option('sc_test_api_secret');
$this->live_api_key = $this->get_option('sc_live_api_key');
$this->live_api_secret = $this->get_option('sc_live_api_secret');
$this->api_key = $this->use_test_api ? $this->test_api_key : $this->live_api_key;
$this->api_secret = $this->use_test_api ? $this->test_api_secret : $this->live_api_secret;
$this->allowInstallments = strcmp($this->get_option('sc_allow_installments'),'yes') == 0;
$this->numberOfInstallments = $this->get_option('sc_number_of_installments');
$this->sc_track_debug = strcmp($this->get_option('sc_track_debug'),'yes') == 0;
add_action('woocommerce_update_options_payment_gateways_' . $this->id, array($this, 'process_admin_options'));
add_action('admin_notices', array(&$this, 'check_ssl'));
add_action('woocommerce_api_smartcoin', array($this,'smartcoin_webhook_handler'));
add_action('woocommerce_thankyou_' . $this->id, array( $this, 'thankyou_page' ) );
add_action( 'woocommerce_email_before_order_table', array( $this, 'add_order_email_instructions' ), 10, 3 );
update_option('sc_show_radio_button', $this->get_option('sc_show_radio_button'));
update_option('sc_debug', $this->get_option('sc_debug'));
update_option('sc_test_api_key', $this->test_api_key);
update_option('sc_live_api_key', $this->live_api_key);
update_option('sc_track_debug', $this->get_option('sc_track_debug'));
}
public function check_ssl() {
if(!$this->use_test_api && get_option('woocommerce_force_ssl_checkout') == 'no' && $this->enabled == 'yes') {
echo __('<div class="error"><p>Smartcoin test API is disable and force SSL option is disable. Please enable SSL and ensure your server has valid SSL certificate.</p></div>','woothemes');
}
}
public function init_form_fields() {
$this->form_fields = array(
'enabled' => array(
'type' => 'checkbox',
'title' => __('Enable/Disable', 'smartcoin-woo'),
'label' => __('Enable Smartcoin Credit Card Payment', 'smartcoin-woo'),
'default' => 'yes'
),
'sc_debug' => array(
'type' => 'checkbox',
'title' => __('Test mode (sandbox)', 'smartcoin-woo'),
'label' => __('Turn on the test mode', 'smartcoin-woo'),
'default' => 'yes'
),
'sc_show_radio_button' => array(
'type' => 'checkbox',
'title' => __('Show Radio Button', 'smartcoin-woo'),
'label' => __('If you are using just Smartcoin as payment method, disable this option', 'smartcoin-woo'),
'default' => 'yes'
),
'title' => array(
'title' => __( 'Title', 'smartcoin-woo' ),
'type' => 'text',
'description' => __( 'This controls the title which the user sees during checkout.', 'smartcoin-woo' ),
'default' => __( 'Credit Card and Bank Slip', 'smartcoin-woo' ),
'desc_tip' => true
),
'sc_test_api_key' => array(
'type' => 'text',
'title' => __('Test API Key', 'smartcoin-woo'),
'default' => __('','smartcoin-woo')
),
'sc_test_api_secret' => array(
'type' => 'password',
'title' => __('Test API Secret', 'smartcoin-woo'),
'default' => __('','smartcoin-woo')
),
'sc_live_api_key' => array(
'type' => 'text',
'title' => __('Live API Key', 'smartcoin-woo'),
'default' => __('','smartcoin-woo')
),
'sc_live_api_secret' => array(
'type' => 'password',
'title' => __('Live API Secret', 'smartcoin-woo'),
'default' => __('','smartcoin-woo')
),
'sc_allow_installments' => array(
'type' => 'checkbox',
'title' => __('Allow Installments', 'smartcoin-woo'),
'default' => __('yes','smartcoin-woo')
),
'sc_number_of_installments' => array(
'type' => 'number',
'title' => __('Number max of installments', 'smartcoin-woo'),
'default' => __(6,'smartcoin-woo')
),
'sc_webhook_url' => array(
'type' => 'text',
'title' => __('Webhook URL to receive Charge updates', 'smartcoin-woo'),
'label' => __('Inclue this url in Smart Manage -> Menu -> Settings -> Webhooks', 'smartcoin-woo'),
'default' => ($this->get_wc_request_url() . '&rand=' . $this->generateRandomString(20))
),
'sc_track_debug' => array(
'type' => 'checkbox',
'title' => __('Enable/Disable', 'smartcoin-woo'),
'label' => __('Enable debug mode that will create log in WooCommerce -> System Status -> Log', 'smartcoin-woo'),
'default' => 'no'
)
);
}
protected function generateRandomString($length = 10) {
$characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
$charactersLength = strlen($characters);
$randomString = '';
for ($i = 0; $i < $length; $i++) {
$randomString .= $characters[rand(0, $charactersLength - 1)];
}
return $randomString;
}
protected function get_wc_request_url() {
global $woocommerce;
return $woocommerce->api_request_url(get_class($this));
}
public function payment_fields() {
include_once('templates/payment_form.php');
}
public function process_payment( $order_id ) {
global $woocommerce;
$this->order = new WC_Order( $order_id );
if ($this->smartcoin_processing()) {
$this->complete_order();
$result = array(
'result' => 'success',
'redirect' => $this->get_return_url($this->order)
);
return $result;
}
else{
$this->mark_as_failed_payment();
}
}
protected function smartcoin_processing() {
global $woocommerce;
try {
$data = $this->get_params();
\Smartcoin\Smartcoin::api_key($this->api_key);
\Smartcoin\Smartcoin::api_secret($this->api_secret);
if($data['smartcoin_payment_method_type'] == 'credit_card'){
if($data['installments'] == '')
$data['installments'] = 1;
$logger = new WC_Logger();
$logger->add( 'Smartcoin', 'Amount: ' . $data['amount'] );
$logger->add( 'Smartcoin', 'Tokne: ' . $data['token'] );
$logger->add( 'Smartcoin', 'Installments: ' . $data['installments'] );
$charge = \Smartcoin\Charge::create(array(
'amount' => $data['amount'],
'currency' => 'brl',
'card' => $data['token'],
'description' => $data['description'],
'reference' => $data['reference'],
'installment' => $data['installments']
));
if($charge->paid){
$this->charge = $charge;
$this->transaction_id = $charge['id'];
return true;
}else {
$error_message = ' Desculpe, mas não conseguimos processar o seu cartão. Por favor, tente novamente com outro cartão de crédito.';
$this->transaction_error_message = $error_message;
wc_add_notice( __('Payment error:', 'smartcoin-woo') . $error_message, 'error' );
return;
}
}else {
$charge = \Smartcoin\Charge::create(array(
'amount' => $data['amount'],
'currency' => 'brl',
'type' => 'bank_slip',
'description' => $data['description'],
'reference' => $data['reference']
));
$this->charge = $charge;
$this->transaction_id = $charge['id'];
return true;
}
} catch(\Smartcoin\Error $e) {
$body = $e->get_json_body();
$err = $body['error'];
error_log('Smartcoin Error:' . $err['message'] . "\n");
$this->transaction_error_message = 'Smartcoin Error:' . $err['message'] . "\n";
wc_add_notice( __('Payment error:', 'smartcoin-woo') . $err['message'], 'error' );
return;
}
}
protected function get_params() {
if ($this->order AND $this->order != null) {
return array(
"smartcoin_payment_method_type" => $_POST['smartcoin_payment_method'],
"amount" => $this->order->get_total() * 100,
"currency" => strtolower(get_woocommerce_currency()),
"token" => $_POST['smartcoin_token'],
"installments" => $_POST['smartcoin_installments'],
"description" => sprintf("Pagamento para %s", $this->order->billing_email),
"reference" => $this->order->id,
"card" => array(
"name" => sprintf("%s %s", $this->order->billing_first_name, $this->order->billing_last_name),
"address_line1" => $this->order->billing_address_1,
"address_line2" => $this->order->billing_address_2,
"address_zip" => $this->order->billing_postcode,
"address_state" => $this->order->billing_state,
"address_country" => $this->order->billing_country
)
);
}
return false;
}
protected function complete_order() {
global $woocommerce;
if ($this->order->status == 'completed')
return;
$fee = 0;
foreach ($this->charge->fees as $fee){
$fee += $fee->amount;
}
$fee = $fee / 100.0;
$status = ($this->charge->paid ? 'Pago' : 'Pendente');
$processed = gmdate('d-m-Y h:i:s',$this->charge->created);
$mode = (strcmp($this->get_option('sc_debug'),'yes') == 0 ? 'test' : 'live' );
$type = ($this->charge->type == 'credit_card' ? 'Cartão de Crédito' : 'Boleto Bancário');
update_post_meta( $this->order->id, 'charge_type', $this->charge->type);
update_post_meta( $this->order->id, 'charge_id', $this->charge->id);
if($this->charge->type == 'credit_card'){
$this->order->payment_complete($this->transaction_id);
$this->order->add_order_note(
sprintf(
"Smartcoin Transaction Details: \n
Tipo: %s
Smartcoin ID: %s
Amount: R$ %.2f
Status: %s
Processed on: %s
Currency: BRL
Credit card: %s (Exp.: %s/%s)
Installments: %s
Processing Fee: R$ %.2f
Mode: %s
",
$type,
$this->charge->id,
$this->charge->amount / 100.0,
$status,
$processed,
$this->charge->card->type,
$this->charge->card->exp_month,
$this->charge->card->exp_year,
$this->charge->installments,
$fee,
$mode
)
);
}
else {
update_post_meta( $this->order->id, 'bank_slip_number', $this->charge->bank_slip->bar_code);
update_post_meta( $this->order->id, 'bank_slip_link', $this->charge->bank_slip->link);
$this->order->update_status('on-hold', __('Pending payment', 'smartcoin-woo'));
$this->msg['message'] = "Thank you for shopping with us. Right now your payment staus is pending, We will keep you posted regarding the status of your order through e-mail";
$this->msg['class'] = 'woocommerce_message woocommerce_message_info';
$this->order->add_order_note(
sprintf(
"Smartcoin Transaction Details: \n
Tipo: %s
Smartcoin ID: %s
Amount: R$ %.2f
Status: %s
Processed on: %s
Currency: BRL
Processing Fee: R$ %.2f
Mode: %s
",
$type,
$this->charge->id,
$this->charge->amount / 100.0,
$status,
$processed,
$fee,
$mode
)
);
}
$woocommerce->cart->empty_cart();
unset($_SESSION['order_awaiting_payment']);
}
protected function mark_as_failed_payment() {
$this->order->add_order_note(
sprintf(
"O Pagamento com Cartão Falhou com a seguinte mensagem: '%s'",
$this->transaction_error_message
)
);
}
/**
* Process refund
*
* Overriding refund method
*
* @access public
* @param int $order_id
* @param float $amount
* @param string $reason
* @return mixed True or False based on success, or WP_Error
*/
public function process_refund($order_id, $amount = null, $reason = '') {
$this->order = new WC_Order($order_id);
$this->transaction_id = $this->order->get_transaction_id();
if (!$this->transaction_id) {
return new WP_Error( 'scwc_refund_error',
sprintf(
__( '%s Credit Card Refund failed because the Transaction ID is missing.', 'smartcoin-woo' ),
get_class( $this )
)
);
}
try {
$refund_data = array();
// If the amount is set, refund that amount, otherwise the entire amount is refunded
if($amount){
$refund_data['amount'] = $amount * 100;
}
// If a reason is provided, add it to the Smartcoin metadata for the refund
// if($reason){
// $refund_data['metadata']['reason'] = $reason;
// }
\Smartcoin\Smartcoin::api_key($this->api_key);
\Smartcoin\Smartcoin::api_secret($this->api_secret);
$ch = \Smartcoin\Charge::retrieve($this->transaction_id);
// Send the refund to the Smartcoin API
$ch->refund($refund_data);
return $ch->to_json();
} catch(\Smartcoin\RequestError $e) {
$body = $e->get_json_body();
$err = $body['error'];
$this->transaction_error_message = $err['message'];
$this->order->add_order_note(
sprintf(
__( '%s Credit Card Refund Failed with message: "%s"', 'smartcoin-woo' ),
get_class( $this ),
$this->transaction_error_message
)
);
return new WP_Error( 'scwc_refund_error', $this->transaction_error_message );
} catch(\Smartcoin\Error $e) {
$body = $e->get_json_body();
$err = $body['error'];
$this->transaction_error_message = $err['message'];
$this->order->add_order_note(
sprintf(
__( '%s Credit Card Refund Failed with message: "%s"', 'smartcoin-woo' ),
get_class( $this ),
$this->transaction_error_message
)
);
return new WP_Error( 'scwc_refund_error', $this->transaction_error_message );
} catch(Exception $e) {
return new WP_Error( 'scwc_refund_error', $e->getMessage());
}
return false;
}
public function smartcoin_webhook_handler() {
global $woocommerce;
$input = @file_get_contents("php://input");
$event_json = json_decode($input,true);
if($event_json && $event_json['object'] == 'event') {
if($event_json['type'] == 'charge.updated') {
global $wpdb;
$charge_id = $event_json['data']['id'];
$order_id = $wpdb->get_var( $wpdb->prepare( "SELECT post_id FROM $wpdb->postmeta WHERE meta_key = 'charge_id' AND meta_value = '%s'", $charge_id ) );
if($order_id) {
if($event_json['data']['type'] == 'bank_slip' && !$event_json['data']['paid']) {
$order = new WC_Order( $order_id );
$order->add_order_note( __( 'Paid successfully.', 'smartcoin-woo' ) );
// Changing the order for processing and reduces the stock.
$order->payment_complete();
}
}
}
}
http_response_code(200);
exit();
}
public function thankyou_page($order_id) {
$order = new WC_Order( $order_id );
$charge_type = get_post_meta( $order->id, 'charge_type', true);
if( $charge_type == 'bank_slip'){
woocommerce_get_template('thankyou.php',
array( 'bank_slip_number' => get_post_meta( $order->id, 'bank_slip_number', true),
'bank_slip_link' => get_post_meta( $order->id, 'bank_slip_link', true),
'charge_type' => $charge_type),
'woocommerce/smartcoin-woo/',
(plugin_dir_path( __FILE__ ) . 'templates/')
);
}
}
public function add_order_email_instructions($order, $sent_to_admin, $plain_text = false) {
if(!$sent_to_admin){
$charge_type = get_post_meta( $order->id, 'charge_type', true);
if( $charge_type == 'bank_slip'){
woocommerce_get_template('email_thankyou.php',
array( 'bank_slip_number' => get_post_meta( $order->id, 'bank_slip_number', true),
'bank_slip_link' => get_post_meta( $order->id, 'bank_slip_link', true),
'charge_type' => $charge_type),
'woocommerce/smartcoin-woo/',
(plugin_dir_path( __FILE__ ) . 'templates/')
);
}
}
}
}
function smartcoin_add_credit_card_gateway_class( $methods ) {
$methods[] = 'Smartcoin';
return $methods;
}