forked from grlf/eyedock
/
Echeck.php
547 lines (478 loc) · 21.5 KB
/
Echeck.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
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
<?php
abstract class Am_Paysystem_Echeck extends Am_Paysystem_Abstract
{
const ACTION_ECHECK = 'echeck';
const ACTION_UPDATE = 'update';
const ACTION_CANCEL = 'cancel';
// form fields contants @see getFormOptions
const ECHECK_COMPANY = 'echeck_company';
const ECHECK_PHONE = 'echeck_phone';
const ECHECK_STREET2 = 'echeck_street2';
const ECHECK_STREET = 'echeck_street';
const ECHECK_CITY = 'echeck_city';
const ECHECK_ADDRESS = 'echeck_address';
const ECHECK_COUNTRY = 'echeck_country';
const ECHECK_STATE = 'echeck_state';
const ECHECK_ZIP = 'echeck_zip';
const ECHECK_TYPE_OPTIONS = 'echeck_type';
const ECHECK_BANK_NAME = 'echeck_bank_name';
const ECHECK_ACCOUNT_NAME = 'echeck_account_name';
/** invoice data field name */
const FIRST_REBILL_FAILURE = 'first_rebill_echeck_failure';
/** @var EcheckRecord set during bill processing */
protected $echeck;
/** @var bool do not display warning about PCI DSS compliance */
protected $_pciDssNotRequired = false;
const FORM_TYPE_ECHECK = 'Am_Form_Echeck';
/** @return Am_Form */
public function createForm($actionName)
{
return new Am_Form_Echeck($this);
}
public function getRecurringType()
{
return self::REPORTS_CRONREBILL;
}
/** @return bool if plugin needs to store EC info */
//defined at Am_Paysystem_Abstract
public function storesCcInfo()
{
return true;
}
public function _process(Invoice $invoice, Am_Request $request, Am_Paysystem_Result $result)
{
$action = new Am_Paysystem_Action_Redirect( $this->getPluginUrl(self::ACTION_ECHECK) );
$action->id = $invoice->getSecureId($this->getId());
$result->setAction($action);
}
public function createTransaction(Am_Request $request, Zend_Controller_Response_Http $response, array $invokeArgs){}
public function directAction(Am_Request $request, Zend_Controller_Response_Http $response, array $invokeArgs)
{
switch ($request->getActionName())
{
case self::ACTION_IPN:
return parent::directAction($request, $response, $invokeArgs);
case self::ACTION_UPDATE:
return $this->updateAction($request, $response, $invokeArgs);
case self::ACTION_CANCEL:
return $this->doCancelAction($request, $response, $invokeArgs);
case self::ACTION_ECHECK:
default:
return $this->echeckAction($request, $response, $invokeArgs);
}
}
protected function echeckActionValidateSetInvoice(Am_Request $request, array $invokeArgs)
{
$invoiceId = $request->getFiltered('id');
if (!$invoiceId)
throw new Am_Exception_InputError("invoice_id is empty - seems you have followed wrong url, please return back to continue");
$invoice = $this->getDi()->invoiceTable->findBySecureId($invoiceId, $this->getId());
if (!$invoice)
throw new Am_Exception_InputError('You have used wrong link for payment page, please return back and try again');
if ($invoice->isCompleted())
throw new Am_Exception_InputError(sprintf(___('Payment is already processed, please go to %sMembership page%s'), "<a href='".htmlentities($this->getDi()->config->get('root_url'))."/member'>","</a>"));
if ($invoice->paysys_id != $this->getId())
throw new Am_Exception_InputError("You have used wrong link for payment page, please return back and try again");
if ($invoice->tm_added < sqlTime('-30 days'))
throw new Am_Exception_InputError("Invoice expired - you cannot open invoice after 30 days elapsed");
$this->invoice = $invoice; // set for reference
}
/**
* Show echeck info input page, validate it if submitted
*/
public function echeckAction(Am_Request $request, Zend_Controller_Response_Http $response, array $invokeArgs)
{
$this->echeckActionValidateSetInvoice($request, $invokeArgs);
$p = $this->createController($request, $response, $invokeArgs);
$p->setPlugin($this);
$p->setInvoice($this->invoice);
$p->run();
}
/**
* Process echeck update request
* @param Am_Request $request
* @param Zend_Controller_Response_Http $response
* @param array $invokeArgs
*/
public function updateAction(Am_Request $request, Zend_Controller_Response_Http $response, array $invokeArgs)
{
if (!$this->getDi()->auth->getUser())
throw new Am_Exception_Security("Authentication required to access this page");
$p = $this->createController($request, $response, $invokeArgs);
$p->setPlugin($this);
$p->run();
}
/**
* Process "cancel recurring" request
* @param Am_Request $request
* @param Zend_Controller_Response_Http $response
* @param array $invokeArgs
*/
public function doCancelAction(Am_Request $request, Zend_Controller_Response_Http $response, array $invokeArgs)
{
$id = $request->getFiltered('id');
$invoice = $this->getDi()->invoiceTable->findBySecureId($id, 'STOP' . $this->getId());
if (!$invoice)
throw new Am_Exception_InputError("No invoice found [$id]");
if ($invoice->user_id != $this->getDi()->auth->getUserId())
throw new Am_Exception_InternalError("User tried to access foreign invoice: [$id]");
if (method_exists($this, 'cancelInvoice'))
$this->cancelInvoice($invoice);
$invoice->setCancelled();
$response->setRedirect(ROOT_SURL . '/member/payment-history');
}
/**
* To be overriden in children classes
* @param Am_Request $request
* @param Zend_Controller_Response_Http $response
* @param array $invokeArgs
* @return Am_Controller_Echeck
*/
protected function createController(Am_Request $request, Zend_Controller_Response_Http $response, array $invokeArgs)
{
return new Am_Controller_Echeck($request, $response, $invokeArgs);
}
/**
* Method must return array of self::ECHECK_xxx constants to control which
* additional fields will be displayed in the form
* @return array
*/
public function getFormOptions()
{
$ret = array(self::ECHECK_ADDRESS, self::ECHECK_COUNTRY, self::ECHECK_STATE, self::ECHECK_CITY, self::ECHECK_STREET, self::ECHECK_ZIP);
return $ret;
}
/**
* You can do form customization necessary for the plugin
* here
*/
public function onFormInit(Am_Form_Echeck $form)
{
}
/**
* You can do custom form validation here. If errors found,
* call $form->getElementById('xx-0')->setError('xxx') and
* return false
* @return bool
*/
public function onFormValidate(Am_Form_Echeck $form)
{
return true;
}
public function doBill(Invoice $invoice, $doFirst, EcheckRecord $echeck = null)
{
$this->invoice = $invoice;
$this->echeck = $echeck;
$result = new Am_Paysystem_Result();
$this->_doBill($invoice, $doFirst, $echeck, $result);
return $result;
}
abstract public function _doBill(Invoice $invoice, $doFirst, EcheckRecord $echeck, Am_Paysystem_Result $result);
/**
* Function can be overrided to change behaviour
*/
public function storeEcheck(EcheckRecord $echeck, Am_Paysystem_Result $result)
{
if ($this->storesCcInfo())
{
$echeck->replace();
$result->setSuccess();
}
return $this;
}
/**
* Method defined for overriding in child classes where EC info is not stored locally
* @return EcRecord
* @param Invoice $invoice
* @throws Am_Exception
*/
public function loadEcheck(Invoice $invoice)
{
if ($this->storesCcInfo())
return $this->getDi()->echeckRecordTable->findFirstByUserId($invoice->user_id);
}
public function prorateInvoice(Invoice $invoice, EcheckRecord $echeck, Am_Paysystem_Result $result, $date)
{
/** @todo use "reattempt" config **/
$reattempt = array_filter($this->getConfig('reattempt', array()));
sort($reattempt);
if (!$reattempt) {
$invoice->updateQuick('status', Invoice::RECURRING_FAILED);
$invoice->updateQuick('rebill_date', null);
return;
}
$first_failure = $invoice->data()->get(self::FIRST_REBILL_FAILURE);
if (!$first_failure)
{
$invoice->data()->set(self::FIRST_REBILL_FAILURE, $date)->update();
$first_failure = $date;
}
$days_diff = (strtotime($date) - strtotime($first_failure)) / (24*3600);
foreach ($reattempt as $day)
if ($day > $days_diff) break; // we have found next rebill date to jump
if ($day <= $days_diff){
// Several rebilling attempts failed already.
// change status to RECURRING_FAILED;
$invoice->updateQuick('status', Invoice::RECURRING_FAILED);
$invoice->updateQuick('rebill_date', null);
return;
}
$invoice->updateQuick('rebill_date', date('Y-m-d', strtotime($first_failure." +$day days")));
$tr = new Am_Paysystem_Transaction_Manual($this);
if ($invoice->getAccessExpire() < $invoice->rebill_date)
$invoice->extendAccessPeriod($invoice->rebill_date);
}
public function onRebillFailure(Invoice $invoice, EcheckRecord $echeck, Am_Paysystem_Result $result, $date)
{
$this->prorateInvoice($invoice, $echeck, $result, $date);
if($this->getDi()->config->get('cc.rebill_failed'))
$this->sendRebillFailedToUser($invoice, $result->getLastError(), $invoice->rebill_date);
}
function sendRebillFailedToUser(Invoice $invoice, $failedReason, $nextRebill)
{
try
{
if($et = Am_Mail_Template::load('cc.rebill_failed'))
{
$et->setError($failedReason);
$et->setUser($invoice->getUser());
$et->setInvoice($invoice);
$et->setProrate(
($nextRebill > $this->getDi()->sqlDate) ?
sprintf(___('Our system will try to charge your card again on %s'), amDate($nextRebill)) : ""
);
$et->setMailPeriodic(Am_Mail::USER_REQUESTED);
$et->send($invoice->getUser());
}
}catch(Exception $e)
{
// No mail exceptions when rebilling;
$this->getDi()->errorLogTable->logException($e);
}
}
function sendRebillSuccessToUser(Invoice $invoice)
{
try
{
if($et = Am_Mail_Template::load('cc.rebill_success'))
{
$et->setUser($invoice->getUser());
$et->setInvoice($invoice);
$et->setAmount($invoice->second_total);
$et->setRebill_date($invoice->rebill_date ? amDate($invoice->rebill_date) : ___('NEVER'));
$et->setMailPeriodic(Am_Mail::USER_REQUESTED);
$et->send($invoice->getUser());
}
}
catch(Exception $e)
{
// No mail exceptions when rebilling;
$this->getDi()->errorLogTable->logException($e);
}
}
public function onRebillSuccess(Invoice $invoice, EcheckRecord $echeck, Am_Paysystem_Result $result, $date)
{
if ($invoice->data()->get(self::FIRST_REBILL_FAILURE))
{
$invoice->addToRebillDate(false, $invoice->data()->get(self::FIRST_REBILL_FAILURE));
$invoice->data()->set(self::FIRST_REBILL_FAILURE, null)->update();
}
if($this->getDi()->config->get('cc.rebill_success'))
$this->sendRebillSuccessToUser($invoice);
}
// called from Bootstrap_Cc
public function ccRebill($date = null)
{
/**
* If plugin can't rebill payments itself, leave it alone.
*/
if($this->getRecurringType() != self::REPORTS_CRONREBILL) return;
$rebillTable = $this->getDi()->ccRebillTable;
$processedCount = 0;
foreach ($this->getDi()->invoiceTable->findForRebill($date, $this->getId()) as $invoice)
{
// Invoice must have status RECURRING_ACTIVE in order to be rebilled;
if($invoice->status != Invoice::RECURRING_ACTIVE)
continue;
// If we already have all payments for this invoice unset rebill_date and update invoice status;
if($invoice->getPaymentsCount() >= $invoice->getExpectedPaymentsCount())
{
$invoice->recalculateRebillDate();
$invoice->updateStatus();
continue;
}
/* @var $invoice Invoice */
try {
$rebill = $rebillTable->createRecord(array(
'paysys_id' => $this->getId(),
'invoice_id' => $invoice->invoice_id,
'rebill_date' => $date,
'status' => CcRebill::STARTED,
'status_msg' => "Not Processed",
));
//only one attempt to rebill per day
try {
$rebill->insert();
} catch (Am_Exception_Db_NotUnique $e) {
continue;
}
$echeck = null;
if ($this->storesCcInfo())
{
$echeck = $this->loadEcheck($invoice);
if (!$echeck)
{
$rebill->setStatus(CcRebill::NO_CC, "No credit card/echeck saved, cannot rebill");
continue;
}
}
$result = $this->doBill($invoice, false, $echeck);
if (!$result->isSuccess())
$this->onRebillFailure($invoice, $echeck, $result, $date);
else
$this->onRebillSuccess($invoice, $echeck, $result, $date);
$rebill->setStatus($result->isSuccess() ? CcRebill::SUCCESS : CcRebill::ERROR,
current($result->getErrorMessages()));
$processedCount++;
} catch (Exception $e) {
if (stripos(get_class($e), 'PHPUnit_')===0) throw $e;
$rebill->setStatus(CcRebill::EXCEPTION,
"Exception " . get_class($e) . " : " . $e->getMessage());
// if there was an exception in billing (say internal error),
// we set rebill_date to tomorrow
$invoice->updateQuick('rebill_date', date('Y-m-d', strtotime($invoice->rebill_date . ' +1 day')));
$this->getDi()->errorLogTable->logException($e);
$this->logError("Exception on rebilling", $e, $invoice);
unset($this->invoice);
}
}
// Send message only if rebill executed by cron;
if($this->getDi()->config->get('cc.admin_rebill_stats')
&& (is_null($date) || $date == $this->getDi()->sqlDate)
&& $processedCount)
$this->sendStatisticsEmail();
}
protected function getStatisticsRow(Array $r)
{
if($r['status']!= CcRebill::SUCCESS)
{
$failed = "Reason: ".$r['status_msg'];
if($r['rebill_date']>$this->getDi()->sqlDate)
$failed .= "\t Next Rebill Date: ".$r['rebill_date'];
}else
$failed = '';
$row = sprintf("%s, %s, %s %s, \nInvoice: %s\tAmount: %s\t%s\n%s\n\n",
$r['email'], $r['login'], $r['name_f'], $r['name_l'],
$r['public_id'], $r['second_total'], $failed,
ROOT_SURL . sprintf('/admin-user-payments/index/user_id/%s#invoice-%s', $r['user_id'], $r['invoice_id'])
);
return $row;
}
protected function sendStatisticsEmail()
{
$date = $this->getDi()->sqlDate;
$success = $failed = "";
$success_count = $failed_count = $success_amount = $failed_amount = 0;
if ($et = Am_Mail_Template::load('cc.admin_rebill_stats'))
{
foreach($this->getDi()->db->selectPage($total, "
SELECT r.*, i.second_total, i.user_id, i.invoice_id, i.public_id, i.rebill_date, u.name_f, u.name_l, u.email, u.login
FROM ?_cc_rebill r LEFT JOIN ?_invoice i USING(invoice_id) LEFT JOIN ?_user u ON(i.user_id = u.user_id)
WHERE status_tm>? and status_tm<=? and r.paysys_id=?
", $date, $this->getDi()->sqlDateTime, $this->getId()) as $r)
{
if($r['status'] == CcRebill::SUCCESS)
{
$success_count++; $success_amount+=$r['second_total'];
$success .= $this->getStatisticsRow($r);
}else{
$failed_count++; $failed_amount += $r['second_total'];
$failed .= $this->getStatisticsRow($r);;
}
}
if($success || $failed)
{
$currency = $this->getDi()->config->get('currency');
$et->setShort_stats(sprintf(___('Success: %d (%0.2f %s) Failed: %d (%0.2f %s)'),
$success_count, $success_amount, $currency, $failed_count, $failed_amount, $currency));
$et->setRebills_success(!empty($success) ? $success : ___('No items in this section'));
$et->setRebills_failed(!empty($failed) ? $failed : ___('No items in this section'));
$et->setPlugin($this->getId());
$et->setMailPeriodic(Am_Mail::ADMIN_REQUESTED);
$et->sendAdmin();
}
}
}
protected function _afterInitSetupForm(Am_Form_Setup $form)
{
// insert title, description fields
$form->setTitle(ucfirst(toCamelCase($this->getId())));
$el = $form->addMagicSelect('reattempt', array('multiple'=>'multiple'));
$options = array();
for ($i=1;$i<60;$i++) $options[$i] = ___("on %d-th day", $i);
$el->loadOptions($options);
$el->setLabel(___("Retry On Failure\n".
"if the recurring billing has failed,\n".
"aMember can repeat it after several days,\n".
"and extend customer subscription for that period\n".
"enter number of days to repeat billing attempt"));
if($this->storesCcInfo() && !$this->_pciDssNotRequired)
{
$text = "<p><font color='red'>WARNING!</font> Every application processing e-check information, must be certified\n" .
"as PA-DSS compliant, and every website processing credit cards must\n" .
"be certified as PCI-DSS compliant.</p>";
$text.= "<p>aMember Pro is not yet certified as PA-DSS compliant. We will start certification process\n".
"once we get 4.2.0 branch released and stable. This plugins is provided solely for TESTING purproses\n".
"Use it for anything else but testing at your own risk.</p>";
$form->addProlog(<<<CUT
<div class="warning_box">
$text
</div>
CUT
);
}
$keyFile = defined('AM_KEYFILE') ? AM_KEYFILE : APPLICATION_PATH . '/configs/key.php';
if (!is_readable($keyFile))
{
$random = $this->getDi()->app->generateRandomString(78);
$text = "<p>To use credit card plugins, you need to create a key file that contains unique\n";
$text .= "encryption key for your website. It is necessary even if the plugin does not\n";
$text .= "store sensitive information.</p>";
$text .= "<p>In a text editor, create file with the following content (one-line, no spaces before opening <?php):\n";
$text .= "<br /><br /><pre style='background-color: #e0e0e0;'><?php return '$random';</pre>\n";
$text .= "<br />save the file as <b>key.php</b>, and upload to <i>amember/application/configs/</i> folder.\n";
$text .= "This warning will disappear once you do it correctly.</p>";
$text .= "<p>KEEP A BACKUP COPY OF THE key.php FILE (!)</p>";
$form->addProlog(<<<CUT
<div class="warning_box">
$text
</div>
CUT
);
}
return parent::_afterInitSetupForm($form);
}
/**
* If plugin require special actions to cancel invoice, cancelInvoice will be called
* after Invoice will actually be cancelled by CreditCard Controller.
* do nothing by default;
* @throws Am_Exception_InputError if failure;
* @param Invoice $invoice
*/
function cancelInvoice(Invoice $invoice)
{
return true;
}
public function cancelAction(Invoice $invoice, $actionName, Am_Paysystem_Result $result)
{
$invoice->setCancelled(true);
}
public function getUpdateEcheckLink($user)
{
if ($this->storesCcInfo() &&
$this->getDi()->echeckRecordTable->findFirstByUserId($user->user_id))
{
return $this->getPluginUrl('update');
}
}
}