-
Notifications
You must be signed in to change notification settings - Fork 9
/
Copy pathcommerce_wechatpay.module
executable file
·586 lines (467 loc) · 19.4 KB
/
commerce_wechatpay.module
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
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
<?php
include_once 'commerce_wechatpay.inc';
/**
* Implements hook_requirements().
*/
function commerce_wechatpay_requirements($phase) {
$requirements = array();
if ($phase == 'runtime') {
// Require overtrue_wechat package
$requirements['overtrue_wechat'] = array(
'title' => t('Overtrue_wechat SDK'),
);
$libraries = libraries_get_libraries();
if (isset($libraries['overtrue_wechat'])) {
$requirements['overtrue_wechat']['value'] = t('Installed');
$requirements['overtrue_wechat']['severity'] = REQUIREMENT_OK;
}
else {
$requirements['overtrue_wechat']['value'] = t('Not Installed');
$requirements['overtrue_wechat']['severity'] = REQUIREMENT_ERROR;
$requirements['overtrue_wechat']['description'] = t('Please download the overtrue_wechat SDK package via %url and place it inside libraries folder with structure -> "sites/all/libraries/overtrue_wechat/src/Wechat/..."', array('%url' => 'https://github.com/overtrue/wechat'));
}
}
return $requirements;
}
/**
* Implements hook_help().
*/
function commerce_wechatpay_help($path, $arg) {
switch ($path) {
case 'admin/help#commerce_wechatpay':
$output = file_get_contents(drupal_get_path('module', 'commerce_wechatpay') .'/README.md');
return module_exists('markdown') ? filter_xss_admin(module_invoke('markdown', 'filter', 'process', 0, -1, $output)) : '<pre>'. check_plain($output) .'</pre>';
}
}
/**
* Implements hook_init().
*/
function commerce_wechatpay_init() {
// load sdk
$path = libraries_get_path('overtrue_wechat');
$realpath = drupal_realpath($path);
if(file_exists($realpath.'/autoload.php')){
include_once $realpath.'/autoload.php';
include_once 'commerce_wechatpay.inc';
}
else {
drupal_set_message('Commerce wechatpay is not well-installed: Missing library "overtrue_wechat". For more information please see your ' . l('status report','admin/reports/status') . '.', 'error');
}
drupal_add_js(drupal_get_path('module', 'commerce_wechatpay') . '/commerce_wechatpay.js');
}
/**
* Implements hook_menu().
*/
function commerce_wechatpay_menu() {
// Listening to Wechatpay's notification.
$items['commerce_wechatpay/note/%'] = array(
'page callback' => 'commerce_wechatpay_notify_handler',
'page arguments' => array(2),
'access callback' => TRUE,
'type' => MENU_CALLBACK,
);
$items['commerce_wechatpay/order_status_check/%'] = array(
'page callback' => 'commerce_wechatpay_order_check_handler',
'page arguments' => array(2),
'access callback' => TRUE,
'type' => MENU_CALLBACK,
);
return $items;
}
/**
* Implements hook_commerce_checkout_page_info_alter().
* to hide the default help message on the checkout payment redirect form page
*
* @see commerce_payment_commerce_checkout_page_info()
*/
function commerce_wechatpay_commerce_checkout_page_info_alter(&$checkout_pages) {
//TODO: make a better solution to hide the help message
foreach ($checkout_pages as $page_id => $checkout_page) {
$defaults = array(
'page_id' => $page_id,
'name' => $checkout_page['title'],
'title' => '',
'help' => '',
'status_cart' => TRUE,
'buttons' => TRUE,
'back_value' => t('Go back'),
'submit_value' => t('Continue to next step'),
'prev_page' => NULL,
'next_page' => NULL,
);
$checkout_pages[$page_id] += $defaults;
}
if(arg(0) == 'checkout' && arg(2) == 'payment' && is_numeric(arg(1))){
$order_id = arg(1);
$order = commerce_order_load($order_id);
if($order){
if(preg_match('|^wechat|', $order->data['payment_method'], $wechat_matches)){
$checkout_pages['payment']['help'] = '';
}
}
}
}
/**
* implements hook_url_inbound_alter().
* create fake path for payment gateway to match Wechat's HIGHLY-SAFE security requirements
*/
function commerce_wechatpay_url_inbound_alter(&$path, $original_path, $path_language){
// Refers to "checkout/*/payment" when a link calls "commerce_wechatpay/checkout/*/payment"
if (preg_match('|^commerce_wechatpay/checkout/([0-9]*)|', $path, $matches)) {
$path = 'checkout/'.$matches[1].'/payment';
}
}
/**
* Implements hook_url_outbound_alter().
* create fake path for payment gateway to match Wechat's HIGHLY-SAFE security requirements
*/
function commerce_wechatpay_url_outbound_alter(&$path, &$options, $original_path) {
// Always make "checkout/*/payment" links go to "commerce_wechatpay/checkout/*/payment"
if (preg_match('|^checkout/([0-9]*)/payment|', $path, $matches)) {
$order = commerce_order_load($matches[1]);
if (preg_match('|^wechat|', $order->data['payment_method'], $wechat_matches)) {
$path = 'commerce_wechatpay/checkout/'.$matches[1];
}
}
}
/**
* Implements hook_commerce_payment_method_info().
*/
function commerce_wechatpay_commerce_payment_method_info() {
$payment_methods = array();
$payment_methods['wechatpay'] = array(
'base' => 'commerce_wechatpay',
'title' => t('Wechatpay'),
'description' => t('Wechatpay Payment'),
'terminal' => FALSE,
'offsite' => TRUE,
'offsite_autoredirect' => FALSE,
);
return $payment_methods;
}
function commerce_wechatpay_get_handler_class() {
$class_name = 'CommerceWechatpay';
// provide API to let other module alter handler class name
drupal_alter('commerce_wechatpay_class_name', $class_name);
return $class_name;
}
function commerce_wechatpay_get_js_process_function() {
$js_function_name = 'proceedWXPayment';
// provide API to let other module alter handler class name
drupal_alter('commerce_wechatpay_javascript_handler_name', $js_function_name);
return $js_function_name;
}
function commerce_wechatpay_get_js_checking_function() {
$js_function_name = 'qrCheckingLoop';
// provide API to let other module alter handler class name
drupal_alter('commerce_wechatpay_javascript_checking_loop_handler_name', $js_function_name);
return $js_function_name;
}
/**
* Payment method callback: settings form.
*/
function commerce_wechatpay_settings_form($settings = NULL) {
$form = array();
$settings = (array) $settings + array(
'appId' => '',
'appSecret' => '',
'mchId' => '',
'mchKey' => '',
'type' => 'mp',
'debug' => ''
);
$form['appId'] = array(
'#type' => 'textfield',
'#title' => t('appId'),
'#description' => t("Wechat appID (微信公众平台-应用ID), see " . l('here', 'https://mp.weixin.qq.com') . '.'),
'#default_value' => $settings['appId'],
'#required' => TRUE,
);
$form['appSecret'] = array(
'#type' => 'textfield',
'#title' => t('appSecret'),
'#description' => t("Wechat appSecret (微信公众平台-应用密钥), see " . l('here', 'https://mp.weixin.qq.com') . '.'),
'#default_value' => $settings['appSecret'],
'#required' => TRUE,
);
$form['mchId'] = array(
'#type' => 'textfield',
'#title' => t('mchId'),
'#description' => t("Wechat merchant id (微信商户平台-商户ID), see " . l('here', 'https://pay.weixin.qq.com') . '.'),
'#default_value' => $settings['mchId'],
'#required' => TRUE,
);
$form['mchKey'] = array(
'#type' => 'textfield',
'#title' => t('mchKey'),
'#description' => t("Wechat merchant API key (微信商户平台-商户API密钥), see " . l('here', 'https://pay.weixin.qq.com') . '.'),
'#default_value' => $settings['mchKey'],
'#required' => TRUE,
);
$form['type'] = array(
'#type' => 'select',
'#title' => t('Payment type'),
'#description' => t("Wechat payment type (支付模式)"),
'#default_value' => $settings['type'],
'#options' => array(
'mp' => 'MP pay (Require opening in wehcat browser)(公众号支付,用户须在微信浏览器内打开)',
'qr' => 'QRcode pay (Scan QRcode to pay)(扫描二维码支付)'
),
'#required' => TRUE,
);
// Enable debug mode.
$form['debug'] = array(
'#type' => 'checkbox',
'#title' => t('Enable debug mode <strong>(for development use only)</strong>'),
'#description' => t('<strong>Override all transactions to a total of 0.01 CNY</strong> for testing the configuration and making sure that payments can be received on the correct account.<br/>This setting should only be used for development purposes.'),
'#default_value' => $settings['debug'],
);
return $form;
}
/**
* Payment method callback: redirect form.
*
* Prepares the necessary data to be passed to Wechatpay with the redirection.
*/
function commerce_wechatpay_redirect_form($form, &$form_state, $order, $payment_method) {
$form = array();
commerce_wechatpay_checkout_handler($order->order_number, $payment_method['instance_id'], $form);
return $form;
}
/**
* refresh the page to try to trigger javascript again
*/
function commerce_wechatpay_redirect_out($form, &$form_state) {
$form_state['redirect'] = current_path();
}
/**
* Main checkout process function
*/
function commerce_wechatpay_checkout_handler($order_id, $payment_inst_id, &$form) {
global $language;
$data = array();
//setting notify_url is default_language
$default_language = language_default();
$payment_method_inst = commerce_payment_method_instance_load($payment_inst_id);
$credentials = commerce_wechatpay_get_credentials_from_payment_instance($payment_method_inst);
$classname = commerce_wechatpay_get_handler_class();
$class = new $classname($credentials[0], $credentials[1], $credentials[2], $credentials[3]);
$options = array('absolute' => TRUE);
if ($language->language != $default_language->language) {
$options += array('language' => $default_language);
}
// Load order entity
$order = commerce_order_load($order_id);
$wrapper = entity_metadata_wrapper('commerce_order', $order);
// Get order body sending to wechat
$data['order_body'] = commerce_wechatpay_get_body($order);
// Get order amount sending to wechat
$amount = $payment_method_inst['settings']["debug"] ? 1 : $wrapper->commerce_order_total->amount->value();
$data['amountToWechat'] = $amount;
// Set notify url to listen to wechat notification
$encrypted_inst_id = htmlentities($payment_inst_id);
$data['notify_url'] = url('commerce_wechatpay/note/'. $encrypted_inst_id, $options);
$data['return_success_url'] = url('checkout/'.$order_id.'/complete', $options);
$data['return_failure_url'] = url('', $options);
// provide API to let other module alter data before sending to wechat payment gateway or calling javascript
drupal_alter('commerce_wechatpay_data', $data, $payment_method_inst, $order);
switch ($payment_method_inst['settings']['type']) {
case 'mp':
commerce_wechatpay_checkout_mp_handler($data, $class, $order_id, $form);
break;
case 'qr':
commerce_wechatpay_checkout_qr_handler($data, $class, $order_id, $form);
break;
default:
commerce_wechatpay_checkout_mp_handler($data, $class, $order_id, $form);
break;
}
}
/**
* mp checkout process function
*/
function commerce_wechatpay_checkout_mp_handler ($data, $class, $order_id, &$form) {
$form['submit'] = array(
'#value' => t('Proceed with payment'),
'#type' => 'submit',
'#weight' => 5,
'#submit' => array('commerce_wechatpay_redirect_out'),
);
// get the Js parameters and then give them to javascript
$jsParms = $class->getJsParm($order_id, $data['order_body'], $data['amountToWechat'], $data['notify_url']);
watchdog('commerce_wechatpay', 'Talking to wechatpay with json parameters: %json', array('%json' => $jsParms));
$js_process_function = commerce_wechatpay_get_js_function();
drupal_add_js($js_process_function.'('.$jsParms.', "'.$data['return_success_url'].'", "'.$data['return_failure_url'].'");', 'inline');
}
/**
* qr checkout process function
*/
function commerce_wechatpay_checkout_qr_handler ($data, $class, $order_id, &$form) {
$response_qrcode_url = $class->proceed_qrpay($order_id, $data['order_body'], $data['amountToWechat'], $data['notify_url']);
$form['qr_code'] = array(
'#markup' => '<div class="wechat_qrcode_container" data-qrsource="'.$response_qrcode_url.'"></div>',
'#weight' => 5
);
$form['qr_desc'] = array(
'#markup' => '<p>'.t('Please scan this QRcode to proceed to the Wechat payment server.').'</p>',
'#weight' => 6
);
drupal_add_js(drupal_get_path('module', 'commerce_wechatpay').'/resources/qrcodejs/qrcode.min.js');
$order_status_check_url = url('commerce_wechatpay/order_status_check/'.$order_id, array('absolute' => TRUE));
$js_checking_function = commerce_wechatpay_get_js_checking_function();
drupal_add_js($js_checking_function.'("' . $order_status_check_url . '", "' . $data['return_success_url'] . '");', 'inline');
$_SESSION['order_'.$order_id] = 1;
}
/**
* Check current order if it's updated due to Wechat notification
* Use Session to be secure
* @param $order_id
*/
function commerce_wechatpay_order_check_handler($order_id) {
if (empty($_SESSION['order_'.$order_id])) {
header('HTTP/1.1 403 Forbidden');
header('Content-Type: application/json');
exit(json_encode(['status'=>0,'message'=>'forbidden']));
}
if (!$order = commerce_order_load($order_id)) {
header('HTTP/1.1 404 Unprocessable Entity');
header('Content-Type: application/json');
exit(json_encode(['status'=>0,'message'=>'order not found']));
}
// if order is real and is this user
$transactions = commerce_payment_transaction_load_multiple(array(), array('order_id' => $order_id));
header('HTTP/1.1 200 OK');
header('Content-Type: application/json');
$status = !empty($transactions) ? 1 : 0;
exit(json_encode(['status'=>$status]));
}
/**
* Menu callback function to process Wechatpay's callback notifications.
*/
function commerce_wechatpay_notify_handler($encrypted_inst_id) {
watchdog('commerce_wechatpay', 'receiving notification from wechatpay.');
$payment_instance_id = html_entity_decode($encrypted_inst_id);
$payment_method_inst = commerce_payment_method_instance_load($payment_instance_id);
if(!$payment_method_inst){
watchdog('commerce_wechatpay', 'Notification invalid from wechatpay: invalid payment method instance.');
return false;
}
$credentials = commerce_wechatpay_get_credentials_from_payment_instance($payment_method_inst);
$classname = commerce_wechatpay_get_handler_class();
$class = new $classname($credentials[0], $credentials[1], $credentials[2], $credentials[3]);
$feedback_transaction = $class->receiveNotify();
$reply_back_msg = $class->getReplyReceived();
if(!$feedback_transaction){
watchdog('commerce_wechatpay', 'Notification invalid from wechatpay: invalid feedback transaction.');
return false;
}
$order_id = $class->outTradeNo2orderId($feedback_transaction['out_trade_no']);
$order = commerce_order_load($order_id);
watchdog('commerce_wechatpay', 'Verified notification from wechatpay, retrieved data: @feedback', array('@feedback' => json_encode($feedback_transaction)));
commerce_wechatpay_notify_verified_handler($feedback_transaction, $order, $payment_method_inst, $reply_back_msg);
}
/**
* Submit and process a notification feedback from Wechatpay for a transaction.
*
* This function creates or updates payment transaction records for
* corresponding orders depending on the status of the notifications received.
*/
function commerce_wechatpay_notify_verified_handler($feedback_transaction, $order, $payment_method_instance, $reply_back_msg) {
// Attempt to load prior authorization capture IPN created previously.
$transactions = commerce_payment_transaction_load_multiple(array(), array('remote_id' => $feedback_transaction["transaction_id"]));
if (!empty($transactions)) {
// if status dose not change, jump out
$keys = array_keys($transactions);
if ($feedback_transaction['result_code'] == $transactions[$keys[0]]->remote_status) {
return false;
}
}
else {
// Create a new payment transaction for the order.
$transaction = commerce_payment_transaction_new($payment_method_instance['method_id'], $order->order_id);
$transaction->instance_id = $payment_method_instance['instance_id'];
}
$currency = (isset($feedback_transaction["fee_type"]))?$feedback_transaction["fee_type"]:'CNY';
$transaction->amount = $feedback_transaction['total_fee'];
$transaction->currency_code = $currency;
$transaction->remote_id = $feedback_transaction["transaction_id"];
// Set the transaction's statuses based on notify's trade_status.
$transaction->remote_status = $feedback_transaction['result_code'];
$transaction->data['notify'] = $feedback_transaction;
// Handle trade types of cases.
switch ($feedback_transaction['result_code']) {
// Operation failed.
case 'FAIL':
$transaction->status = COMMERCE_PAYMENT_STATUS_FAILURE;
$transaction->message = 'Transaction failed.';
break;
// Transaction successful.
case 'SUCCESS':
$transaction->status = COMMERCE_PAYMENT_STATUS_SUCCESS;
$transaction->message = 'Transaction success.';
break;
}
// provide API to let other module alter data before sending to wechat payment gateway
drupal_alter('commerce_wechatpay_transaction_presave', $transaction, $feedback_transaction, $order, $payment_method_instance);
// Save the payment transaction and redirect to next page.
commerce_payment_transaction_save($transaction);
switch ($feedback_transaction['result_code']) {
// Operation failed.
case 'FAIL':
commerce_order_status_update($order, 'canceled');
break;
// Transaction successful.
case 'SUCCESS':
// Proceed to the next page if it succeeded.
$order_status = commerce_order_status_load($order->status);
$checkout_page = commerce_checkout_page_load($order_status['checkout_page']);
$next_page = $checkout_page['next_page'];
if(!empty($next_page)){
// Update the order status to the next checkout page.
$order = commerce_order_status_update($order, 'checkout_' . $next_page, FALSE, FALSE);
// Inform modules of checkout completion if the next page is completed.
if ($next_page == 'complete') {
commerce_checkout_complete($order);
}
return $reply_back_msg;
}
break;
}
}
/**
* Generate order body
*/
function commerce_wechatpay_get_body($order) {
if (empty($order)) {
return '';
}
// Get a list of the items from the order to be paid.
$order_wrapper = entity_metadata_wrapper('commerce_order', $order);
$line_items = $order_wrapper->commerce_line_items->value();
foreach ($line_items as $line_item) {
if ($line_item->type == 'product' && !empty($line_item->commerce_product)) {
$line_item_wrapper = entity_metadata_wrapper('commerce_line_item', $line_item);
$body[] = $line_item_wrapper->commerce_product->title->value();
}
}
return implode($body, ' | ');
}
/**
* Helper function to get an array of credentials matches sdk needs
* @param array $payment_method
* @return array
*/
function commerce_wechatpay_get_credentials_from_payment_instance($payment_method) {
// load all parameters from rules-settings
$appId = $payment_method['settings']["appId"];
$appSecret = $payment_method['settings']["appSecret"];
$mchId = $payment_method['settings']["mchId"];
$mchKey = $payment_method['settings']["mchKey"];
// if parameters not configured correctly, call error
if(empty($appId) || empty($appSecret) || empty($mchId) || empty($mchKey)){
drupal_set_message('Please configure your wechat payment correctly! See ' . l('here', 'admin/commerce/config/payment-methods') . '.', 'warning');
return array();
}
$credentials = array($appId, $appSecret, $mchId, $mchKey);
return $credentials;
}