-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdibs.php
489 lines (383 loc) · 15.5 KB
/
dibs.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
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
<?php
/*
Plugin Name: Jigoshop - Dibs Payment Gateway
Plugin URI: http://bazooka.se/
Description: Allows you to use Dibs payment gateway with the Jigoshop ecommerce plugin.
Version: 00.09
Author: Esbjörn Eriksson
Author URI: http://bazooka.se/
*/
/* Copyright 2012 Bazooka AB (email : [email protected])
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License, version 2, as
published by the Free Software Foundation.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
/* Add a custom payment class after Jigoshop has loaded */
add_action('plugins_loaded', 'jigoshop_dibspayment', 0);
function jigoshop_dibspayment()
{
if (!class_exists('jigoshop_payment_gateway'))
return; // if the Jigoshop payment gateway class is not available, do nothing
/**
* Add the gateway to JigoShop
**/
function add_dibspayment_gateway( $methods ) {
$methods[] = 'dibspayment';
return $methods;
}
add_filter( 'jigoshop_payment_gateways', 'add_dibspayment_gateway', 50 );
class dibspayment extends jigoshop_payment_gateway {
public function __construct() {
parent::__construct();
$this->id = 'dibspayment';
$this->icon = '';
$this->has_fields = false;
$this->enabled = Jigoshop_Base::get_options()->get_option('jigoshop_dibspayment_enabled');
$this->title = Jigoshop_Base::get_options()->get_option('jigoshop_dibspayment_title');
$this->merchant = Jigoshop_Base::get_options()->get_option('jigoshop_dibspayment_merchant');
$this->description = Jigoshop_Base::get_options()->get_option('jigoshop_dibspayment_description');
$this->testmode = Jigoshop_Base::get_options()->get_option('jigoshop_dibspayment_testmode');
$this->MAC_key = Jigoshop_Base::get_options()->get_option('jigoshop_dibspayment_key');
$this->instant = Jigoshop_Base::get_options()->get_option('jigoshop_dibspayment_instant');
$this->language = Jigoshop_Base::get_options()->get_option('jigoshop_dibspayment_language');
add_action('init', array(&$this, 'check_callback') );
add_action('valid-dibspayment-callback', array(&$this, 'successful_request') );
add_action('receipt_dibspayment', array(&$this, 'receipt_page'));
add_filter('jigoshop_thankyou_message', array(&$this, 'thankyou_message') );
}
/**
* Default Option settings for WordPress Settings API using the Jigoshop_Options class
*
* These will be installed on the Jigoshop_Options 'Payment Gateways' tab by the parent class 'jigoshop_payment_gateway'
*
*/
protected function get_default_options() {
$defaults = array();
// Define the Section name for the Jigoshop_Options
$defaults[] = array(
'name' => __('DIBS Payment Window', 'jigoshop'), 'type' => 'title',
'desc' => __('This is the new DIBS Payment Window for 2012. It works by sending the user to <a href="http://www.dibspayment.com/">DIBS</a> to enter their payment information.', 'jigoshop')
);
// List each option in order of appearance with details
$defaults[] = array(
'name' => __('Enable DIBS Payment Window','jigoshop'),
'desc' => '',
'tip' => '',
'id' => 'jigoshop_dibspayment_enabled',
'std' => 'no',
'type' => 'checkbox',
'choices' => array(
'no' => __('No', 'jigoshop'),
'yes' => __('Yes', 'jigoshop')
)
);
$defaults[] = array(
'name' => __('Method Title','jigoshop'),
'desc' => '',
'tip' => __('This controls the title which the user sees during checkout.','jigoshop'),
'id' => 'jigoshop_dibspayment_title',
'std' => __('DIBS','jigoshop'),
'type' => 'text'
);
$defaults[] = array(
'name' => __('Description','jigoshop'),
'desc' => '',
'tip' => __('This controls the description which the user sees during checkout.','jigoshop'),
'id' => 'jigoshop_dibspayment_description',
'std' => __("Pay via DIBS using credit card or bank transfer.", 'jigoshop'),
'type' => 'longtext'
);
$defaults[] = array(
'name' => __('DIBS Merchant ID','jigoshop'),
'desc' => '',
'tip' => __('Please enter your DIBS merchant id; this is needed in order to take payment!','jigoshop'),
'id' => 'jigoshop_dibspayment_merchant',
'std' => '',
'type' => 'text'
);
$defaults[] = array(
'name' => __('DIBS MAC Key','jigoshop'),
'desc' => '',
'tip' => __('Please enter your DIBS MAC key; this will further secure your payments.','jigoshop'),
'id' => 'jigoshop_dibspayment_key',
'std' => '',
'type' => 'longtext'
);
$defaults[] = array(
'name' => __('Enable test mode','jigoshop'),
'desc' => '',
'tip' => __('When test mode is enabled only DIBS specific test-cards are accepted.','jigoshop'),
'id' => 'jigoshop_dibspayment_testmode',
'std' => 'no',
'type' => 'checkbox',
'choices' => array(
'no' => __('No', 'jigoshop'),
'yes' => __('Yes', 'jigoshop')
)
);
$defaults[] = array(
'name' => __('Language','jigoshop'),
'desc' => '',
'tip' => __('Show Dibs Payment Window in this language. If set to WPML detect, it switches between the languages listed here, but if not found defaults to English.','jigoshop'),
'id' => 'jigoshop_dibspayment_language',
'std' => 'en',
'type' => 'select',
'choices' => array(
'detect_wpml' => __('Detect using WPML', 'jigoshop'),
'en_US' => __('English (US)', 'jigoshop'),
'en_GB' => __('English (GB)', 'jigoshop'),
'da_DK' => __('Danish', 'jigoshop'),
'sv_SE' => __('Swedish', 'jigoshop'),
'nb_NO' => __('Norwegian (Bokmål)', 'jigoshop'),
)
);
return $defaults;
}
/**
* There are no payment fields for dibs, but we want to show the description if set.
**/
function payment_fields() {
if ($jigoshop_dibspayment_description = Jigoshop_Base::get_options()->get_option('jigoshop_dibspayment_description')) echo wpautop(wptexturize($jigoshop_dibspayment_description));
}
/**
* Generate the dibs button link
**/
public function generate_form( $order_id ) {
$order = new jigoshop_order( $order_id );
$action_adr = 'https://sat1.dibspayment.com/dibspaymentwindow/entrypoint';
// filter redirect page
$checkout_redirect = apply_filters( 'jigoshop_get_checkout_redirect_page_id', jigoshop_get_page_id('thanks') );
// Define language
$lang = $this->language;
if ( $this->language == 'detect_wpml' ) {
$valid_wpml_languages = array('da','en','sv','nb');
if ( defined(ICL_LANGUAGE_CODE) && in_array(ICL_LANGUAGE_CODE, $valid_wpml_languages) ) {
$lang = ICL_LANGUAGE_CODE;
} else {
$lang = 'en';
}
}
$args =
array(
// Merchant
'merchant' => $this->merchant,
// Session
'language' => $lang,
// Order
'amount' => $order->order_total * 100,
'orderId' => $order_id,
'currency' => Jigoshop_Base::get_options()->get_option('jigoshop_currency'),
// URLs
'callbackUrl' => site_url('/jigoshop/dibscallback'),
'acceptReturnUrl' => get_permalink($checkout_redirect),
'cancelReturnUrl' => site_url('/jigoshop/dibscancel'),
// Custom
's_jigoshop_order_key' => $order->order_key,
);
if ( $this->instant ) {
$args['capturenow'] = 1;
}
if ( $this->testmode == 'yes' ) {
$args['test'] = 1;
}
// Calculate HMAC
if ( $this->MAC_key != '' ) {
$args['MAC'] = $this->dibs_calculate_mac($args);
}
$fields = '';
foreach ($args as $key => $value) {
$fields .= '<input type="hidden" name="'.esc_attr($key).'" value="'.esc_attr($value).'" />';
}
return '<form action="'.$action_adr.'" method="post" id="dibs_payment_form">
' . $fields . '
<input type="submit" class="button-alt" id="submit_dibs_payment_form" value="'.__('Pay via DIBS', 'jigoshop').'" /> <a class="button cancel" href="'.esc_url($order->get_cancel_order_url()).'">'.__('Cancel order & restore cart', 'jigoshop').'</a>
<script type="text/javascript">
jQuery(function(){
jQuery("body").block(
{
message: "<img src=\"'.jigoshop::assets_url().'/assets/images/ajax-loader.gif\" alt=\"Redirecting...\" />'.__('Thank you for your order. We are now redirecting you to DIBS to make payment.', 'jigoshop').'",
overlayCSS:
{
background: "#fff",
opacity: 0.6
},
css: {
padding: 20,
textAlign: "center",
color: "#555",
border: "3px solid #aaa",
backgroundColor:"#fff",
cursor: "wait"
}
});
jQuery("#submit_dibs_payment_form").click();
});
</script>
</form>';
}
/**
* Process the payment and return the result
**/
function process_payment( $order_id ) {
$order = new jigoshop_order( $order_id );
return array(
'result' => 'success',
'redirect' => add_query_arg('order', $order->id, add_query_arg('key', $order->order_key, apply_filters('jigoshop_get_return_url', get_permalink(jigoshop_get_page_id('pay')))))
);
}
/**
* receipt_page
**/
function receipt_page( $order ) {
echo '<p>'.__('Thank you for your order, please click the button below to pay with DIBS.', 'jigoshop').'</p>';
echo $this->generate_form( $order );
}
/**
* Check for DIBS Response
**/
function check_callback() {
// Cancel order POST
if ( strpos($_SERVER["REQUEST_URI"], 'jigoshop/dibscancel') !== false) {
$this->cancel_order(stripslashes_deep($_POST));
return;
}
if ( strpos($_SERVER["REQUEST_URI"], 'jigoshop/dibscallback') !== false ) {
header("HTTP/1.1 200 Ok");
do_action("valid-dibspayment-callback", stripslashes_deep($_POST));
}
}
// This is a modified version of jigoshop_cancel_order.
// We must have our own since the original checks nonce on GET variables.
function cancel_order($posted) {
if(isset($posted['orderId']) && is_numeric($posted['orderId']) && isset($posted['s_jigoshop_order_key']) ) {
// Also verify HMAC
$MAC = $this->dibs_calculate_mac($posted);
// Cancel order the same way as jigoshop_cancel_order
$order_id = $_POST['orderId'];
$order_key = $_POST['s_jigoshop_order_key'];
$order = new jigoshop_order( $order_id );
if ($posted['MAC'] == $MAC && $order->id == $order_id && $order->order_key == $order_key && $order->status=='pending') :
// Cancel the order + restore stock
$order->cancel_order( __('Order cancelled by customer.', 'jigoshop') );
// Message
jigoshop::add_message( __('Your order was cancelled.', 'jigoshop') );
elseif ($order->status!='pending') :
jigoshop::add_error( __('Your order is no longer pending and could not be cancelled. Please contact us if you need assistance.', 'jigoshop') );
else :
jigoshop::add_error( __('Invalid order.', 'jigoshop') );
endif;
wp_safe_redirect(jigoshop_cart::get_cart_url());
exit;
}
}
function thankyou_message($message) {
// Fake a GET request for the Thank you page
if(isset($_POST['orderId']) && is_numeric($_POST['orderId']) && isset($_POST['s_jigoshop_order_key']) ) {
$_GET['order'] = $_POST['orderId'];
$_GET['key'] = $_POST['s_jigoshop_order_key'];
}
return $message;
}
/**
* Successful Payment!
**/
function successful_request( $posted ) {
// Custom holds post ID
if ( !empty($posted['transaction']) && !empty($posted['orderId']) && is_numeric($posted['orderId']) ) {
$error = FALSE;
$order_id = (int) $posted['orderId'];
$order_key = $posted['s_jigoshop_order_key'];
$transaction_id = $posted['transaction'];
// Load this order from database
$order = new jigoshop_order( $order_id );
// Verify HMAC
$MAC = $this->dibs_calculate_mac($posted);
if($posted['MAC'] != $MAC) {
$log = sprintf( __('DIBS transaction %s failed Dibs security check. HMAC from dibs was %s and calculated HMAC was %s.', 'jigoshop'),
$transaction_id, $posted['MAC'], $MAC ) ;
error_log($log);
$order->add_order_note($log);
$error = TRUE;
}
// Check transaction status
if ( ! isset($_POST['status']) || $_POST['status'] != 'ACCEPTED' ) {
$log = sprintf( __('DIBS transaction %s was completed but not successful. Please check Dibs administration for more info.', 'jigoshop'), $transaction_id ) ;
error_log($log);
$order->add_order_note($log);
$error = TRUE;
}
// Verify order key
if ($order->order_key !== $posted['s_jigoshop_order_key']) {
$log = sprintf( __('DIBS transaction %s failed Jigoshop security check. Key from dibs was %s and stored key was %s.', 'jigoshop'),
$transaction_id, $order_key, $order->order_key ) ;
error_log($log);
$order->add_order_note($log);
$error = TRUE;
}
if ( $error ) print "Error.\n";
// If all went well, complete order
if ($error === FALSE && $order->status !== 'completed') {
$order->add_order_note( sprintf( __('DIBS payment completed with transaction id %s.', 'jigoshop'), $transaction_id ) );
$order->payment_complete();
print "Success.\n";
}
}
exit('Dibs callback complete.');
}
// Found here: http://tech.dibs.dk/dibs_api/other_features/mac_calculation/
// This function converts an array holding the form key values to a string.
// The generated string represents the message to be signed by the MAC.
function dibs_create_message($formKeyValues) {
$string = "";
if (is_array($formKeyValues)) {
ksort($formKeyValues); // Sort the posted values by alphanumeric
foreach ($formKeyValues as $key => $value) {
if ($key != "MAC") { // Don't include the MAC in the calculation of the MAC.
if (strlen($string) > 0) $string .= "&";
$string .= "$key=$value"; // create string representation
}
}
return $string;
} else {
return "An array must be used as input!";
}
}
// This function converts from a hexadecimal representation to a string representation.
function dibs_hextostr($hex) {
$string = "";
foreach (explode("\n", trim(chunk_split($hex, 2))) as $h) {
$string .= chr(hexdec($h));
}
return $string;
}
// This function calculates the MAC for an array holding the form key values.
// The $logfile is optional.
function dibs_calculate_mac($formKeyValues, $logfile = null) {
$HmacKey = $this->MAC_key;
// Create the message to be signed.
if (is_array($formKeyValues)) {
$messageToBeSigned = $this->dibs_create_message($formKeyValues);
// Calculate the MAC.
$MAC = hash_hmac("sha256", $messageToBeSigned, $this->dibs_hextostr($HmacKey));
// Following is only relevant if you wan't to log the calculated MAC to a log file.
if ($logfile) {
$fp = fopen($logfile, 'a') or exit("Can't open $logfile!");
fwrite($fp, "messageToBeSigned: " . $messageToBeSigned . PHP_EOL
. " HmacKey: " . $HmacKey . PHP_EOL . " generated MAC: " . $MAC . PHP_EOL);
if (isset($formKeyValues["MAC"]) && $formKeyValues["MAC"] != "")
fwrite($fp, " posted MAC: " . $formKeyValues["MAC"] . PHP_EOL);
}
return $MAC;
} else {
die("Form key values must be given as an array");
}
}
}
}