Odyssey
rdcTranzCap.i
1 <?php
2 
3 function RDCconfig($dbh, &$parms) {
4  $parms['QA'] = (!isset($parms['QA']) ? 0 : $parms['QA'] );
5  if ($parms['QA']) {
6  $parms['tzLoginURL'] = $parms['qaLoginURL'];
7  $parms['tzServiceURL'] = $parms['qaServiceURL'];
8  $parms['tzUser'] = $parms['qaUser'];
9  $parms['tzPass'] = htmlentities($parms['qaPass'], ENT_COMPAT | ENT_XML1);
10  $parms['tzLicense'] = htmlentities($parms['qaLicense'], ENT_COMPAT | ENT_XML1);
11  $parms['tzScope'] = $parms['qaScope'];
12 // $parms['tzScope'] = preg_replace("(^https?://)", "", $parms['qaScope'] );
13  } else {
14  $parms['tzLoginURL'] = $parms['prodLoginURL'];
15  $parms['tzServiceURL'] = $parms['prodServiceURL'];
16  $parms['tzUser'] = $parms['prodUser'];
17  $parms['tzPass'] = htmlentities($parms['prodPass'], ENT_COMPAT | ENT_XML1);
18  $parms['tzLicense'] = htmlentities($parms['prodLicense'], ENT_COMPAT | ENT_XML1);
19  $parms['tzScope'] = $parms['prodScope'];
20 // $parms['tzScope'] = preg_replace("(^https?://)", "", $parms['prodScope'] );
21  }
22  if (!isset($parms['tzLoginURL']) || !isset($parms['tzServiceURL']) ||
23  !isset($parms['tzUser']) || !isset($parms['tzPass']) ||
24  !isset($parms['tzLicense']) || !isset($parms['tzScope'])) {
25  throw new Exception("Missing Parameters", 100);
26  }
27 }
28 
29 function RDCauth($dbh, $HB_ENV, $MC, $parms) {
30 # requires: $parms['Cu']
31 # $parms['rdcvendor']
32 # Additional values rdcvendor retrieved and decoded from cutrusteddetail
33 #
34 # returns:
35  # assume we are going to succeed...
36  $return['status']['response'] = 'true';
37  $return['status']['code'] = '000';
38  $return['status']['message'] = 'Success';
39  $localTerms = '';
40 
41  try {
42  # If authorizing at HomeCU, is member authorized?
43  if (HCU_array_key_value('HomeCUAuth', $parms)) {
44  $mbr_rdc = Get_RDCSetting($dbh, $HB_ENV, 'RDCTranzCap', $parms['MBRACCT']);
45  if ($mbr_rdc['status']['code'] != '000') {
46  throw new Exception($mbr_rdc['status']['message'], $mbr_rdc['status']['code']);
47  }
48  $dl = abs(intval($mbr_rdc['rdcsetting']));
49 
50  // For HomeCUAuth we use non-zero cuusers.depositlimit as marker for 'member is eligible'
51  if (abs(intval($dl)) == 0) {
52 
53  $HB_Notices_ary = Get_NoticeInfo($dbh, $HB_ENV, $MC, 'M', "mblNoRDC", true);
54  if ($HB_Notices_ary['status']['code'] == '000') {
55  $noticeData = $HB_Notices_ary["notice"][0]["notice_text"];
56  } else {
57  $noticeData = "";
58  }
59  if (strlen($noticeData)) {
60  $message = $noticeData;
61  $code = 111;
62  } else {
63  $message = "Account not permitted for Remote Deposit. Please contact the Credit Union for more information";
64  $code = 110;
65  }
66  throw new Exception($message, $code);
67  }
68  }
69  $parms['deplimit'] = (isset($dl) ? $dl : 0);
70 
71  # member validation at Catalyst or member is authorized
72  # Get HomeCU-eligible accounts
73  # need the Fset flags for getting descriptions
74  $parms['Fset2'] = $HB_ENV['Fset2'];
75  $parms['Fset3'] = $HB_ENV['Fset3'];
76  $parms['Uid'] = $HB_ENV['Uid'];
77 
78  $hculist = RDCGetAccts($dbh, $parms);
79 
80  if ($hculist['status']['response'] == 'false') {
81  throw new Exception($hculist['status']['message'], $hculist['status']['code']);
82  }
83 
84  # got a valid RDC account list
85  $newrec = 1;
86  /**
87  * Don't recycle sessions with Tranzcap
88  * Anytime we get a request to start a session a new record will be created in the curdcstatus table
89  */
90 # - tranzAuth to get token and
91 # - rdcPresentAccts to
92 # - sync acct list with Catalyst
93 # - verify at least one active account with (scanlimit > 0 or scanlimit unlimited)
94 #
95 
96  $rdcresult = tranzAuth($parms);
97 
98  if ($rdcresult['status']['response'] == 'false') {
99  throw new Exception($rdcresult['status']['message'], $rdcresult['status']['code']);
100  }
101 
102  if (empty($rdcresult['data']['tzToken'])) {
103  throw new Exception('TranzCapture Invalid Token' . print_r($parms, true), 300);
104  }
105 
106  $parms['tzToken'] = $rdcresult['data']['tzToken'];
107  $parms['tzToken_expires'] = $rdcresult['data']['tzToken_expires'];
108 
109  $presaccts = RDCPresentAccounts($parms, $hculist['data']);
110  if ($presaccts['status']['response'] == 'false') {
111  # error send fail
112  throw new Exception($presaccts['status']['message'], $presaccts['status']['code']);
113  }
114 
115  # see if HomeCU is serving terms,
116  $parms['rdcstatus'] = 'S';
117  if (HCU_array_key_value('HomeCUterms', $parms)) {
118  $rdcterms = hcuGetRDCterms($dbh, $HB_ENV, $MC);
119  if ($rdcterms['status']['response'] == 'false') {
120  $e = "HCU GetTerms call failed ({$rdcterms['status']['code']} {$rdcterms['status']['message']}";
121  throw new Exception($e, 301);
122  }
123  if ($rdcterms['data']['notice_popup'] == 1) {
124  $parms['rdcstatus'] = 'T';
125  $localTerms = HCU_array_key_value('terms', $rdcterms['data']);
126  } else {
127  $parms['rdcstatus'] = 'S';
128  }
129  }
130  $parms['vendorinfo'] = array('Vendortime' => time(),
131  'userAgent' => $_SERVER['HTTP_USER_AGENT'],
132  'userIP' => $_SERVER['REMOTE_ADDR'],
133  'accounts' => $presaccts['data']['accounts'],
134  'depmessages' => $presaccts['data']['depmessages'],
135  'tzToken' => $parms['tzToken'],
136  'tzToken_expires' => $parms['tzToken_expires']);
137 
138  if ($newrec) {
139  # start curdc record, return depositid as part of result
140  $depostat = curdc_start($dbh, $parms);
141  if ($depostat['status']['response'] == 'false') {
142  # error send fail
143  throw new Exception('HomeCU Start Deposit Failed', 200);
144  }
145  $parms['depositid'] = $depostat['data']['depositid'];
146  // $parms['vendorinfo']['raw']=json_encode($rdcresult);
147  }
148  $return['data']['depositid'] = $parms['depositid'];
149  $return['data']['accounts'] = $parms['vendorinfo']['accounts'];
150  $return['data']['depmessages'] = $parms['vendorinfo']['depmessages'];
151  $return['data']['tzToken'] = $parms['tzToken'];
152  $return['data']['tzToken_expires'] = $parms['tzToken_expires'];
153  $return['data']['terms'] = $localTerms;
154 
155 
156  $depostat = curdc_setvinfo($dbh, array('Cu' => $parms['Cu'], 'depositid' => $parms['depositid'],
157  'vendorinfo' => json_encode($parms['vendorinfo'])));
158  if ($depostat['status']['response'] == 'false') {
159  # error send fail
160  throw new Exception($depostat['status']['message'], $depostat['status']['code']);
161  }
162  } catch (Exception $e) {
163  $return['status']['response'] = 'false';
164  $return['status']['code'] = $e->getCode();
165  $return['status']['message'] = "(" . $e->getLine() . ") " . htmlspecialchars($e->getMessage(), ENT_QUOTES, 'UTF-8', FALSE);
166  }
167  return $return;
168 }
169 
170 function RDCaccept($dbh, $HB_ENV, $MC, $parms) {
171 # requires: $parms['Cu']
172 # $parms['depositid']
173 # Additional values retrieved and decoded from cutrusteddetail
174 # or from curdcstatus record using depositid as key
175 # returns:
176  # assume we are going to succeed...
177  $return['status']['response'] = 'true';
178  $return['status']['code'] = '000';
179  $return['status']['message'] = 'Success';
180 
181  try {
182  if (!isset($parms['Cu']) || !isset($parms['depositid'])) {
183  throw new Exception('Missing Parameters', 100);
184  }
185  # look up depositid
186  # decode vendorinfo
187  $depo = curdc_read($dbh, $parms);
188  if ($depo['status']['response'] == 'false') {
189  throw new Exception('HomeCU DepositID not found', 205);
190  }
191 
192  # look up rdcTerms doc and then update to show acceptance
193  // get any notice text
194  $noticeInfo = Get_NoticeInfo($dbh, $HB_ENV, $MC, "P", "rdcTerms", false);
195  if ($noticeInfo["status"]["code"] == "000" && sizeof($noticeInfo['notice']) && intval($noticeInfo['notice'][0]['notice_id']) > 0) {
196  # action P post so set up the HCUPOST array
197  $HB_ENV['HCUPOST']['notice_id'] = $noticeInfo['notice'][0]['notice_id'];
198  $HB_ENV['HCUPOST']['notice_type'] = $noticeInfo['notice'][0]['notice_type'];
199  $HB_ENV['HCUPOST']['notice_device'] = 'P';
200  $HB_ENV["HCUPOST"]['notice_response'] = array("answer" => 1); // something non-zero but numeric
201  # not sure if the next two are needed -
202  $HB_ENV["HCUPOST"]['notice_cancel'] = "0";
203  $HB_ENV['HCUPOST']['notice_msg_show'] = 1;
204  $noticeUpd = Update_NoticeInfo($dbh, $HB_ENV, $MC);
205 
206  $return['status']['message'] = 'Accept Terms OK';
207  $vendorinfo = $depo['data']['vendorinfo'];
208  $vendorinfo['terms'] = '';
209  $vendorinfo['Vendortime'] = time();
210  $parms['vendorinfo'] = $vendorinfo;
211  }
212 
213  # update curdcstatus record
214  $parms['rdcstatus'] = 'O';
215 
216  $depostat = curdc_setvinfo($dbh, array('Cu' => $parms['Cu'], 'depositid' => $parms['depositid'],
217  'rdcstatus' => $parms['rdcstatus'], 'vendorinfo' => json_encode($parms['vendorinfo'])));
218  if ($depostat['status']['response'] == 'false') {
219  # error send fail
220  throw new Exception($depostat['status']['message'], $depostat['status']['code']);
221  }
222  } catch (Exception $e) {
223  $return['status']['response'] = 'false';
224  $return['status']['code'] = $e->getCode();
225  $return['status']['message'] = "(" . $e->getLine() . ") " . htmlspecialchars($e->getMessage(), ENT_QUOTES, 'UTF-8', FALSE);
226  }
227  return $return;
228 }
229 
230 function RDChistorylist($dbh, $parms) {
231 # requires: $parms['Cu']
232 # $parms['depositid']
233 # Additional values retrieved and decoded from cutrusteddetail
234 # or from curdcstatus record using depositid as key
235 # returns:
236  # assume we are going to succeed...
237  $return['status']['response'] = 'true';
238  $return['status']['code'] = '000';
239  $return['status']['message'] = 'Success';
240 
241  try {
242  if (!isset($parms['Cu']) || !isset($parms['depositid'])) {
243  throw new Exception('Missing Parameters', 100);
244  }
245  # look up depositid
246  # decode vendorinfo
247  $depo = curdc_read($dbh, $parms);
248  if ($depo['status']['response'] == 'false') {
249  throw new Exception("HomeCU DepositID not found [{$parms['depositid']}]", 205);
250  }
251  $rdcresult = tranzGetHistoryList($parms);
252  if ($rdcresult['status']['response'] == 'false') {
253  throw new Exception('tranz Get History List call failed ' . $rdcresult['status']['message'], 305);
254  }
255  foreach ((array) $rdcresult['data'] as $histkey => $histitem) {
256  // set return values using ensenta names, just because
257  // they were first and OFXRequest expects those names
258  $rdcresult['data'][$histkey]['ReceiptReferenceNo'] = "{$histitem['BatchID']}-{$histitem['ItemID']}";
259  $rdcresult['data'][$histkey]['transactionid'] = $histitem['ItemID'];
260  $rdcresult['data'][$histkey]['transactiondttm'] = $histitem['Created'];
261  $rdcresult['data'][$histkey]['submittedamount'] = sprintf('%.2f', $histitem['Amount']);
262  $rdcresult['data'][$histkey]['currentamount'] = sprintf('%.2f', $histitem['Amount']);
263  $rdcresult['data'][$histkey]['status'] = $histitem['ItemStatus'];
264  $rdcresult['data'][$histkey]['statusdescr'] = "{$histitem['ReviewComments']}";
265  if ($histitem['ItemStatus'] == 1) {
266  $rdcresult['data'][$histkey]['status'] .= " Received";
267  }
268  if ($histitem['ItemStatus'] == 2) {
269  $rdcresult['data'][$histkey]['status'] .= " Rejected";
270  }
271  if ($histitem['ItemStatus'] == 3) {
272  $rdcresult['data'][$histkey]['status'] .= " Approved";
273  }
274  if ($histitem['ItemStatus'] == 4) {
275  $rdcresult['data'][$histkey]['status'] .= " Pending";
276  }
277 // $rdcresult['data'][$histkey]['status'] .= "{$histitem['ReviewComments']}";
278  $rdcresult['data'][$histkey]['statusdisplay'] = "{$rdcresult['data'][$histkey]['status']} {$histitem['ReviewComments']}";
279  $rdcresult['data'][$histkey]['transactiontype'] = $histitem['AccountType'];
280 
281  if ($histitem['AccountType'] == '1') {
282  $rdcresult['data'][$histkey]['accountnumber'] = 'Checking ';
283  }
284  if ($histitem['AccountType'] == '2') {
285  $rdcresult['data'][$histkey]['accountnumber'] = 'Savings ';
286  }
287  $rdcresult['data'][$histkey]['accountnumber'] .= $histitem['AccountNumber'];
288  }
289  $return['status']['message'] = 'History List OK';
290  $vendorinfo = HCU_array_key_value('vendorinfo', $depo);
291  $vendorinfo['Vendortime'] = time();
292  $parms['vendorinfo'] = $vendorinfo;
293 
294  # update curdcstatus record
295 
296  $depostat = curdc_setvinfo($dbh, array('Cu' => $parms['Cu'], 'depositid' => $parms['depositid'],
297  'vendorinfo' => json_encode($parms['vendorinfo'])));
298  if ($depostat['status']['response'] == 'false') {
299  # error send fail
300  throw new Exception($depostat['status']['message'], $depostat['status']['code']);
301  }
302  $return['data']['TransactionList'] = $rdcresult['data'];
303  $return['data']['rdcvendor'] = $depo['data']['rdcvendor'];
304  } catch (Exception $e) {
305  $return['status']['response'] = 'false';
306  $return['status']['code'] = $e->getCode();
307  $return['status']['message'] = "(" . $e->getLine() . ") " . htmlspecialchars($e->getMessage(), ENT_QUOTES, 'UTF-8', FALSE);
308  }
309  return $return;
310 }
311 
312 function RDChistorydetl($dbh, $parms) {
313 # requires: $parms['Cu']
314 # $parms['ItemId']
315 # Additional values retrieved and decoded from cutrusteddetail
316 # or from curdcstatus record using depositid as key
317 # returns:
318  # assume we are going to succeed...
319  $return['status']['response'] = 'true';
320  $return['status']['code'] = '000';
321  $return['status']['message'] = 'Success';
322 
323  try {
324  if (!isset($parms['Cu']) || !isset($parms['ItemId']) || !isset($parms['depositid'])) {
325  throw new Exception('Missing Parameters', 100);
326  }
327  # look up depositid
328  # decode vendorinfo
329  $depo = curdc_read($dbh, $parms);
330  if ($depo['status']['response'] == 'false') {
331  throw new Exception('HomeCU DepositID not found', 205);
332  }
333  $rdcresult = tranzGetHistoryItem($parms);
334  if ($rdcresult['status']['response'] == 'false' || $rdcresult['data']['ResponseCode'] != '00') {
335  $e = ($rdcresult['status']['response'] == 'false' ? 'tranz Get History Item call failed' :
336  "GetHistoryItem - " . $rdcresult['data']['ResponseCode'] . ' ' . $rdcresult['data']['ErrorResponseText'] . ' ' . $rdcresult['data']['LocalizedMessageText']);
337  throw new Exception($e, 305);
338  }
339  $return['status']['message'] = 'tranz GetHistoryItem OK';
340  $vendorinfo = $depo['vendorinfo'];
341  $vendorinfo['Vendortime'] = time();
342  $parms['vendorinfo'] = $vendorinfo;
343 
344  # update curdcstatus record
345  $depostat = curdc_setvinfo($dbh, array('Cu' => $parms['Cu'], 'depositid' => $parms['depositid'],
346  'vendorinfo' => json_encode($parms['vendorinfo'])));
347  if ($depostat['status']['response'] == 'false') {
348  # error send fail
349  throw new Exception($depostat['status']['message'], $depostat['status']['code']);
350  }
351  $return['data'] = $rdcresult['data'];
352  } catch (Exception $e) {
353  $return['status']['response'] = 'false';
354  $return['status']['code'] = $e->getCode();
355  $return['status']['message'] = "(" . $e->getLine() . ") " . htmlspecialchars($e->getMessage(), ENT_QUOTES, 'UTF-8', FALSE);
356  }
357  return $return;
358 }
359 
360 function RDCdeposit($dbh, $parms) {
361 # requires: $parms['Cu']
362 # $parms['depositid']
363 # $parms['amount']
364 # $parms['acctid']
365 # $parms['rdcacctid']
366 # Additional values retrieved and decoded from cutrusteddetail
367 # or from curdcstatus record using depositid as key
368 # returns:
369  # assume we are going to succeed...
370  $return['status']['response'] = 'true';
371  $return['status']['message'] = 'Success';
372  $return['status']['code'] = '000';
373  try {
374  if (!isset($parms['Cu']) || !isset($parms['depositid']) ||
375  !isset($parms['amount']) || !isset($parms['acctid'])) {
376  // !isset($parms['rdcacctid'])) {
377  throw new Exception('Missing Parameters', 100);
378  }
379  /*
380  * need to use $parms['acctid'] to retrieve info about receiving account
381  * get from vendorinfo['accounts'] stored in deposit record, as that includes
382  * vendor-returned info
383  */
384 
385  # look up depositid
386  $depo = curdc_read($dbh, $parms);
387  if ($depo['status']['response'] == 'false') {
388  throw new Exception('HomeCU DepositID not found', 205);
389  }
390  $fail = '';
391  switch ($depo['data']['status']) {
392  case 'T':
393  $fail = 'Must accept terms of use before depositing funds';
394  break;
395  case 'R':
396  $fail = 'Deposit has been rejected';
397  break;
398  case 'C':
399  $fail = 'Deposit already completed';
400  break;
401  case 'B':
402  case 'F':
403  if (!isset($parms['POSTAWAY'])) {
404  $fail = 'Deposit requires override confirmation';
405  }
406  break;
407  }
408  if ("$fail" != '') {
409  throw new Exception($fail, 229);
410  }
411  if (is_null($depo['data']['frontpath']) || is_null($depo['data']['backpath']) || !getimagesize($depo['data']['frontpath']) || !getimagesize($depo['data']['backpath'])) {
412  throw new Exception('Check Images not found', 220);
413  }
414  $vendorinfo = $depo['data']['vendorinfo'];
415 
416  // Store amount, selected account in curdcstatus table
417  $depostat = curdc_update($dbh, array('Cu' => $parms['Cu'], 'depositid' => $parms['depositid'],
418  'amount' => $parms['amount'], 'acctid' => $parms['acctid']));
419  if ($depostat['status']['response'] == 'false') {
420  throw new Exception('HomeCU Update Deposit Amount Failed', 225);
421  }
422 
423  $acctid = $parms['acctid'];
424 
425  $hculist = RDCGetAccts($dbh, $parms, $acctid);
426 
427  if ($hculist['status']['response'] !== 'true') {
428  throw new Exception('Invalid Deposit Account', 230);
429  }
430  $scanlimit = $vendorinfo['accounts'][$acctid]['ScanLimitAmount'];
431  if (!is_null($scanlimit) && $scanlimit < ($parms['amount'] * .01)) {
432  throw new Exception("Deposit Amount Exceeds Deposit Limit (" .
433  sprintf('%.2f', $scanlimit) . ")", 231);
434  }
435  $parms['AccountNumber'] = $vendorinfo['accounts'][$acctid]['suffix'];
436  # set default AccountType, then override if configured
437  $parms['AccountType'] = $vendorinfo['accounts'][$acctid]['rdctype'];
438  // $parms['tzToken'] = $vendorinfo['tzToken'];
439  // $parms['tzToken_expires'] = $vendorinfo['tzToken_expires'];
440  $parms['CheckFront'] = base64_encode(file_get_contents($depo['data']['frontpath']));
441  $parms['CheckBack'] = base64_encode(file_get_contents($depo['data']['backpath']));
442 
443  $rdcresult = tranzPostItem($parms);
444 
445  if (HCU_array_key_value('response', $rdcresult['status']) == 'false' ||
446  !HCU_array_key_value('WasSuccessful',$rdcresult['data']) ) {
447  if ($rdcresult['status']['response'] == 'false') {
448  # HTTP error or Curl error or empty response
449  $vendorinfo['Message'] = "PostItem failed {$rdcresult['status']['message']}";
450  $errorcode = $rdcresult['status']['code'];
451  }
452  if (!$rdcresult['data']['WasSuccessful']) {
453  # rejected at TranzCap
454  $vendorinfo['Message'] = $rdcresult['data']['ErrorMessage'] . ' Deposit Cannot be processed as submitted';
455  $errorcode = 241;
456  }
457  $parms['rdcstatus'] = 'R';
458  $vendorinfo['Vendortime'] = time();
459  $vendorinfo['DepositStatus'] = "Failed";
460  $vendorinfo['DepositTime'] = date('YmdHis');
461 
462  # update vendorinfo here
463  $depostat = curdc_setvinfo($dbh, array('Cu' => $parms['Cu'], 'depositid' => $parms['depositid'],
464  'rdcstatus' => $parms['rdcstatus'], 'vendorinfo' => json_encode($vendorinfo)));
465  if ($depostat['status']['response'] == 'false') {
466  throw new Exception('HomeCU Update Vendorinfo Failed', 240);
467  }
468 
469  $return['data'] = $rdcresult['data'];
470  $return['data']['depositid'] = $parms['depositid'];
471  $return['data']['rdcstatus'] = $parms['rdcstatus'];
472 
473  throw new Exception($vendorinfo['Message'], $errorcode);
474 
475  } else {
476  $parms['rdcstatus'] = 'C';
477  $vendorinfo['Vendortime'] = time();
478  $vendorinfo['DepositStatus'] = "Accepted";
479  $vendorinfo['Message'] = 'Accepted';
480  $vendorinfo['Review'] = '';
481  $vendorinfo['TransactionReceiptNumber'] = "{$rdcresult['data']['BatchID']}-{$rdcresult['data']['ItemID']}";
482  $vendorinfo['TransactionDateTime'] = date('c');
483  // $vendorinfo['raw']=$rdcresult['data']['raw'];
484  $depostat = curdc_setvinfo($dbh, array('Cu' => $parms['Cu'], 'depositid' => $parms['depositid'], 'frontaccept' => 'Y',
485  'backaccept' => 'Y', 'rdcstatus' => $parms['rdcstatus'], 'vendorinfo' => json_encode($vendorinfo)));
486  if ($depostat['status']['response'] == 'false') {
487  throw new Exception('HomeCU Update Vendorinfo Failed', 240);
488  }
489  $return['status']['response'] = 'true';
490  $return['status']['message'] = 'TranzCapture Deposit Complete';
491  # this returns everything from Ensenta, but that will be a problem if we add other vendors
492  # pick a list of stuff to return and be consistent for everyone?
493  $return['data'] = $rdcresult['data'];
494  $return['data']['depositid'] = $parms['depositid'];
495  $return['data']['rdcstatus'] = $parms['rdcstatus'];
496  # use the Ensenta names for values the apps look for --
497  $return['data']['TransactionReceiptNumber'] = "{$rdcresult['data']['BatchID']}-{$rdcresult['data']['ItemID']}";
498  $return['data']['TransactionDateTime'] = date('c');
499  $return['data']['MaskedAccountholderNumber'] = $vendorinfo['accounts'][$acctid]['suffix'];
500 
501  $hcumessage = "Your deposit request for account {$vendorinfo['accounts'][$acctid]['suffix']} has been received";
502  if (HCU_array_key_value('SentToReview', $rdcresult['data']) == 'true') {
503  $hcumessage .= " pending review";
504  }
505  $hcumessage .= ". Your confirmation number is '{$rdcresult['data']['BatchID']}-{$rdcresult['data']['ItemID']}'. ";
506  if (HCU_array_key_value('depSuccessMsg',$parms)) {
507  $hcumessage .= convertMicrosoftCharacters($parms['depSuccessMsg']);
508  } else {
509  $hcumessage .= "Please save this number and refer to it if you need to contact the credit union regarding this transaction. ";
510  }
511  // if (!empty($vendorinfo['fundsavailable'])) {
512  // $hcumessage .= $vendorinfo['fundsavailable'];
513  // }
514 
515  $return['data']['HCUReceiptMessage'] = $hcumessage;
516  }
517  } catch (Exception $e) {
518  $return['status']['response'] = 'false';
519  $return['status']['code'] = $e->getCode();
520  $return['status']['message'] = "(" . $e->getLine() . ") " . htmlspecialchars($e->getMessage(), ENT_QUOTES, 'UTF-8', FALSE);
521  }
522 
523  return $return;
524 }
525 
526 function RDCGetAccts($dbh, $parms, $Acctid = "") {
527  $AcctList = array();
528 
529  if (!isset($parms['Cu']) || !isset($parms['Uid']) || !isset($parms['MBRACCT'])) {
530 // RDC_response('910', array('Settings Error'), 'ERROR'); # RDCGetAccts not enough info provided
531  $AcctList['status']['response'] = 'false';
532  $AcctList['status']['code'] = '910';
533  $AcctList['status']['message'] = 'Missing RDC Account Parameters'; # RDCGetAccts missing Cu/Uid/MBRACCT
534 
535  return ($AcctList);
536  }
537 
538  $Cu = $parms['Cu'];
539  $Uid = $parms['Uid'];
540  $MBRACCT = $parms['MBRACCT'];
541  $balwhere = $parms['balwhere'];
542  $Fset3 = $parms['Fset3'];
543 
544 # TranzCapture supports deposits only
545  $rtxn = ( sizeof($parms['rtxn']) == 0 ?
546  array('AT' => 1) :
547  json_decode($parms['rtxn'], TRUE) );
548  $savingsql = (!isset($parms['savingsql']) ?
549  "trim(accounttype)" :
550  $parms['savingsql'] );
551  $draftsql = (!isset($parms['draftsql']) ?
552  "trim(accounttype)" :
553  $parms['draftsql'] );
554  $mbrsql = (!isset($parms['mbrsql']) ?
555  "trim(accountnumber)" :
556  $parms['mbrsql'] );
557 
558 
559 # fetch transactions types
560 
561  $sql = "select ht.trancode, trim(t.trandesc), trim(ht.cudesc), t.specialproc
562  from cutrans t, cuhavetrans ht
563  where ht.cu='$Cu'
564  and ht.trancode = t.trancode\n";
565 
566  $sth = db_query($sql, $dbh);
567  #
568  # Return a line for each allowed transaction type.
569  #
570  $txncodes = array();
571  for ($row = 0; list($code, $desc, $cudesc, $spec) = db_fetch_array($sth, $row); $row++) {
572  $txncodes{$code} = array($desc, $spec, $cudesc);
573  }
574  db_free_result($sth);
575 
576  $sql = "";
577  $verb = "";
578 
579  $sv_rdctype = (!isset($parms['Sv_rdctype']) ? '2' : $parms['Sv_rdctype']);
580  $ck_rdctype = (!isset($parms['Ck_rdctype']) ? '1' : $parms['Ck_rdctype']);
581  # code was trying to:
582  # if the rdctype is all digits, leave it plain else wrap in single quotes for Postgres
583 // $sv_rdctype = (ctype_digit ( "$sv_rdctype" ) ? $sv_rdctype : "'$sv_rdctype'");
584 // $ck_rdctype = (ctype_digit ( "$sv_rdctype" ) ? $ck_rdctype : "'$ck_rdctype'");
585  # but didn't work as expected. Worked better to just quote the *_rdctype
586  # whether it was digits or string.
587 
588 # find out how many valid accounts the member has:
589  $sql = "WITH accountlist as (
590  SELECT ab.accountnumber,
591  ua.display_name,
592  description,
593  ua.accounttype as accounttype,
594  ua.certnumber as certnumber,
595  ua.recordtype,
596  ua.view_balances,
597  ua.view_transactions,
598  ab.deposittype,
599  'DP' as cbtype, amount as currentbalance,
600  ua.display_order,
601  trim(ab.micraccount) as micraccount
602  FROM {$Cu}useraccounts as ua
603  INNER JOIN {$Cu}accountbalance as ab ON ab.accountnumber = ua.accountnumber
604  AND ab.accounttype = ua.accounttype
605  AND ua.certnumber = ua.certnumber
606  WHERE ua.user_id = $Uid
607  AND ua.accountnumber = '{$MBRACCT}'
608  AND ua.recordtype = 'D'
609  AND ab.may_deposit = true ) ";
610 
611  if (HCU_array_key_exists('AT', $txncodes) && HCU_array_key_exists('AT', $rtxn)) {
612 # $txncodes is configured list @HCU - $rtxn is allowed list for RDC
613 
614  $sql .= "SELECT recordtype as tbl,
615  $mbrsql as rdcmember, trim(description) as description,
616  trim(display_name) as display_name,
617  trim(accounttype) as accounttype, $savingsql as suffix,
618  certnumber as certnumber, '$sv_rdctype' as rdctype,
619  display_order, trim(accountnumber) as accountnumber
620  FROM accountlist
621  WHERE recordtype = 'D' $balwhere
622  AND upper(deposittype) in ('S','N')
623  UNION
624  SELECT recordtype, $mbrsql as rdcmember,
625  trim(description), trim(display_name),
626  trim(accounttype), $draftsql,
627  certnumber, '$ck_rdctype', display_order,
628  trim(accountnumber)
629  FROM accountlist
630  WHERE recordtype = 'D' $balwhere
631  AND upper(deposittype) = 'Y' ";
632  }
633  $sql .= " order by 6,2,3";
634  $acct_rs = db_query($sql, $dbh);
635 
636  if (db_num_rows($acct_rs) == 0) {
637 // RDC_response('920', array('No Eligible Accounts'), 'ERROR'); # RDCGetAccts no valid accounts
638 // if vendor logging is active, save the sql
639  $AcctList['status']['response'] = 'false';
640  $AcctList['status']['code'] = '920';
641  $AcctList['status']['message'] = htmlspecialchars('No Eligible RDC Accounts', ENT_QUOTES, 'UTF-8', FALSE); # RDCGetAccts no valid accounts
642  if ($parms["logging"] == "enabled") {
643  $logParms = $parms["environment"]; // get the environment info passed in
644  $logParms["token"] = ''; // the id used across all communications in session
645  $logParms["txnId"] = time(); // the id for this transaction
646  $logParms["request"] = "$sql"; // the request
647  $logParms["reply"] = ""; // the response
648  LogSSOActivity($logParms);
649  }
650  } else {
651 
652  $AcctList['status']['response'] = 'true';
653  $AcctList['status']['code'] = '000';
654  $AcctList['status']['message'] = 'Success';
655  for ($row = 0; $drow = db_fetch_array($acct_rs, $row); $row++) {
656  $tbl = $drow['tbl'];
657  $accounttype = $drow['accounttype'];
658  $suffix = $drow['suffix'];
659  $cert = $drow['certnumber'];
660  $rdctype = $drow['rdctype'];
661  switch ($rdctype) {
662  case "$sv_rdctype":
663  $rdcdesc = 'Savings';
664  break;
665  case "$ck_rdctype":
666  $rdcdesc = 'Checking';
667  break;
668  default:
669  $rdcdesc = 'Savings';
670  break;
671  }
672  $rdcmember = $drow['rdcmember'];
673  if (strpos($accounttype, "@")) {
674  list($jtype, $jacct) = explode("@", $accounttype);
675  $trust = 'joint';
676  } else {
677  $jtype = $accounttype;
678  $jacct = $MBRACCT;
679  $trust = 'primary';
680  }
681  $tokn = sha1("${Uid}${accounttype}${Cu}${rdctype}obl1vi0u5");
682 
683  $desc = getAccountDescription($dbh, $Cu, $drow['accountnumber'], $drow['description'], $drow['accounttype'], $drow['display_name'], $Fset3, $drow['certnumber'], false, false);
684  $desc = htmlspecialchars($desc, ENT_QUOTES, 'UTF-8', FALSE);
685  $displaydesc = $desc;
686 
687  $Accts["$tbl|$jacct|$jtype|$cert"]['accounttype'] = $accounttype;
688  $Accts["$tbl|$jacct|$jtype|$cert"]['suffix'] = $suffix;
689  $Accts["$tbl|$jacct|$jtype|$cert"]['certnumber'] = $cert;
690  $Accts["$tbl|$jacct|$jtype|$cert"]['acctclass'] = $tbl;
691  $Accts["$tbl|$jacct|$jtype|$cert"]['description'] = $desc;
692  $Accts["$tbl|$jacct|$jtype|$cert"]['tokn'] = "$tokn";
693  $Accts["$tbl|$jacct|$jtype|$cert"]['Uid'] = "$Uid";
694  $Accts["$tbl|$jacct|$jtype|$cert"]['trust'] = "$trust";
695  $Accts["$tbl|$jacct|$jtype|$cert"]['displaydesc'] = "$displaydesc";
696  $Accts["$tbl|$jacct|$jtype|$cert"]['rdctype'] = $rdctype;
697  $Accts["$tbl|$jacct|$jtype|$cert"]['rdcdesc'] = $rdcdesc;
698  $Accts["$tbl|$jacct|$jtype|$cert"]['rdcmember'] = $rdcmember;
699  }
700  }
701  if (!empty($Acctid)) {
702  # got an account identifier - return one only
703  $AcctList['data'][$Acctid] = $Accts[$Acctid];
704  } else {
705  $AcctList['data'] = $Accts;
706  }
707 
708  return ($AcctList);
709 }
710 
711 /**
712  *
713  * @param array $parms
714  * @param array $hculist
715  * valid RDC accounts on record at HomeCU
716  * @return array
717  * ['data']['accounts'] list of valid accounts
718  * each entry looks like this:
719  * [D|666665|50|0] => Array
720  (
721  ['suffix'] => 50
722  ['certnumber'] => 0
723  ['acctclass'] => D
724  ['description'] => REGULAR SHARES - 50
725  ['tokn'] => a9a525ac33035b7c3845809443c5eed626297e0f
726  ['member'] => 666665
727  ['tomember'] => 666665
728  ['trust'] => primary
729  ['displaydesc'] => REGULAR SHARES - 50
730  ['rdctype'] => 0
731  ['rdcdesc'] =>
732  ['RDCAcctId'] => 1
733  )
734  * Note that for Ensenta we pass a list of accounts on the 'start session' call
735  * if the client uses shared branching, Ensenta returns list of shared branching
736  * accounts, or if batch they return the same list we sent.
737  * We need to parse through the list they send to record the account identifier
738  * they will recognize & which we are required to use when making the deposit.
739  *
740  * ['data']['terms'] terms of use (if any) returned from rdc vendor
741  * ['data'] array also contains any values returned from rdc vendor on
742  * start session call. For Ensenta, these include:
743  * ['ResponseCode'] => 00
744  * ['SessionStateId'] => 55121227-e3ea-4524-8e34-dec9b199a3f3
745  * ['IsTermsAcceptanceRequired'] => false
746  * ['IsBlackListed'] => false
747  * ['ReceiptEmail'] =>
748  * ['accounts'] => Array
749  *
750  */
751 function RDCPresentAccounts($parms, $hculist) {
752  # transGetMobileUser
753  # if not found, tranzAddMobileUser
754  # if fail to add, throw error member account not permitted
755  # For each account in hculist
756  # if not in tzlist tranzAddMobileUser to regiser account
757  # if IsActive,
758  # add to account list
759  # if ShowScanlimit && ScanLimit is not null, add scan limit to depmessages
760  # build array list to send to app
761  # include depositid
762  # include labels acctttl, descttl
763  try {
764  if (!isset($parms['RTN']) || !isset($parms['tzLoginURL']) ||
765  !isset($parms['tzLicense']) ||
766  !isset($parms['tzUser']) ||
767  !isset($parms['tzPass']) ||
768  !isset($parms['tzScope']) ||
769  !isset($parms['tzToken']) ||
770  !isset($hculist) ||
771  !isset($parms['MBRACCT'])) {
772  throw new Exception("Missing Parameters", 100);
773  }
774 
775  $rdcresult = tranzGetMobileUser($parms);
776 
777  if ($rdcresult['status']['response'] == 'false' && $rdcresult['status']['code'] != 404) {
778  throw new Exception($rdcresult['status']['message'], 999);
779  }
780  if ($rdcresult['status']['code'] == 404) {
781  # catalyst uses 404 to indicate user not found
782  $gmulist = array();
783  } else {
784  $gmulist = $rdcresult['data']['Accounts'];
785  if ($rdcresult['data']['EmailAddress'] != urldecode($parms['Ml']) ||
786  # SHOULD USE MIR HERE
787  $rdcresult['data']['FirstName'] != 'Mobile' ||
788  $rdcresult['data']['LastName'] != 'Deposit') {
789  $updresult = tranzUpdateMobileUser($parms);
790  if ($updresult['status']['response'] == 'false') {
791  throw new Exception($updresult['status']['message'], 999);
792  }
793  }
794  }
795  /*
796  * parse throught the gmu array and build a list of keys for existing accts
797  */
798  $gmukeys = array(); #get a list of the account keys back from TranzCap
799  foreach ((array) $gmulist as $key => $acct) {
800  $gmukeys[$key] = "{$acct['AccountNumber']}|{$acct['AccountType']}";
801  }
802 
803  $presentlist = array(); # this is the final list function will return
804  $depmessages = array(); # deposit messages to be returned
805 // For each account in hculist that is not in gmulist...
806  foreach ((array) $hculist as $histkey => $histitem) {
807  $gkey = array_search("{$histitem['suffix']}|{$histitem['rdctype']}", $gmukeys);
808  if ($gkey === false) { # not found, try to add this account
809  $parms['tzAccount'] = $histitem['suffix'];
810  $parms['tzType'] = $histitem['rdctype'];
811  $rdcresult = tranzAddMobileUser($parms);
812  if ($rdcresult['status']['response'] == 'false') {
813  throw new Exception($rdcresult['status']['message'], 999);
814  }
815  # add successful, add result to gmulist & set gkey
816  $gmulist[] = $rdcresult['data'];
817  end($gmulist);
818  $gkey = key($gmulist);
819  $gmukeys[$gkey] = "{$rdcresult['data']['AccountNumber']}|{$rdcresult['data']['AccountType']}";
820  }
821  # consider account at TranzCap, if IsActive=true & scanlimit >0 or unlimited,
822  if ($gmulist[$gkey]['IsActive'] == 1 &&
823  (is_null($gmulist[$gkey]['ScanLimitAmount']) || $gmulist[$gkey]['ScanLimitAmount'] > 0)) {
824  # add to present_list
825  $presentlist[$histkey] = $histitem;
826  # and capture the scan limit
827  $presentlist[$histkey]['ScanLimitAmount'] = (is_null($gmulist[$gkey]['ScanLimitAmount']) ? NULL : sprintf("%.2f", "{$gmulist[$gkey]['ScanLimitAmount']}"));
828  # if configured to show scan limit, and there is a scan limit, format the message
829  # note: not showing 'Unlimited' scan limit -- seems like asking for fraud?
830  if ($parms['ShowScanlimit'] &&
831  !is_null($gmulist[$gkey]['ScanLimitAmount']) && $gmulist[$gkey]['ScanLimitAmount'] > 0) {
832  $depmessages[] = array("MessageTextCd" => "HCU1", "LocalizedText" => "Deposit Limit for {$gmulist[$gkey]['AccountNumber']} {$histitem['rdcdesc']} is " . sprintf("%.2f", "{$gmulist[$gkey]['ScanLimitAmount']}"));
833  }
834  }
835  }
836 
837  $pass_along['data']['accounts'] = $presentlist;
838  $pass_along['data']['depmessages'] = $depmessages;
839  $pass_along['status']['response'] = 'true';
840  $pass_along['status']['code'] = '000';
841  $pass_along['status']['message'] = 'Success';
842  } catch (Exception $e) {
843  $pass_along['status']['response'] = 'false';
844  $pass_along['status']['message'] = $e->getMessage();
845  $pass_along['data'] = array();
846  }
847  return $pass_along;
848 }
849 
850 function tranzAuth($parms) {
851  # Requests an OAuth token with provided username/password
852  # Returns the token, expiration and grant_type to use in requests to the mobile API methods
853 
854  try {
855  if (!isset($parms['RTN']) || !isset($parms['tzLoginURL']) ||
856  !isset($parms['tzLicense']) ||
857  !isset($parms['tzUser']) ||
858  !isset($parms['tzPass']) ||
859  !isset($parms['tzScope']) ||
860  !isset($parms['MBRACCT'])) {
861  throw new Exception("Missing Parameters", 100);
862  }
863 
864  $reqData = json_encode(array("grant_type" => "client_credentials",
865  "scope" => $parms['tzScope'],
866  "username" => $parms['tzUser'],
867  "password" => $parms['tzPass']));
868 
869  $reqHeaders = array("Content-Type: application/json");
870 
871  $parms["environment"]["logPoint"] = "tranzAuth"; // this action in a readable form
872  $now = time(); # capture timestamp before we start, will calc token_expires afterward
873  $tzSaid = tranzEmbcurl($parms, $parms['tzLoginURL'], 'POST', $reqHeaders, $reqData);
874  # look for errors, otherwise decode and save the token
875  if (HCU_array_key_value('error', $tzSaid)) {
876  # look for errors, otherwise decode and save the token
877  throw new Exception("Error " . HCU_array_key_value('message', $tzSaid), 999);
878  }
879  $tzToken = "{$tzSaid['token_type']} {$tzSaid['access_token']}";
880  $tzToken_expires = $now + $tzSaid['expires_in'];
881  $return['status']['response'] = 'true';
882  $return['status']['code'] = '000';
883  $return['status']['message'] = 'Success';
884  $return['data']['tzToken'] = $tzToken;
885  $return['data']['tzToken_expires'] = $tzToken_expires;
886  } catch (Exception $e) {
887  $return['status']['response'] = 'false';
888  $return['status']['message'] = $e->getMessage();
889  $return['status']['code'] = $e->getCode();
890  $return['data'] = array();
891  }
892 
893  return $return;
894 }
895 
896 function tranzGetMobileUser($parms) {
897 //GET /v1/CreditUnions/{creditUnionId}/Licenses/{licenseKey}/MobileUsers/{userId}
898 //Gets member information about the user.
899 //Returns member information for the given user, if the user exists.
900 //Path parameters
901 //creditUnionId (required) - The credit union routing number format: int32 $parms['RTN']
902 //licenseKey (required) - The license key required for access to the Credit Union: int32 $parm['tzLicense']
903 //userId (required) - The user identifier: string $parms['MBRACCT']
904 # uses: $parms['RTN']
905 # $parms['tzLicense']
906 # $parms['MBRACCT']
907 # $parms['tzServiceURL']
908 #
909  try {
910  if (!isset($parms['RTN']) || !isset($parms['tzServiceURL']) ||
911  !isset($parms['tzLicense']) ||
912  !isset($parms['tzToken']) ||
913  !isset($parms['tzScope']) ||
914  !isset($parms['MBRACCT'])) {
915  throw new Exception("Missing Parameters", 100);
916  }
917  $reqHeaders = array("Authorization: {$parms['tzToken']}");
918  $reqURL = "{$parms['tzServiceURL']}/{$parms['RTN']}/Licenses/{$parms['tzLicense']}/MobileUsers/{$parms['MBRACCT']}";
919  $parms["environment"]["logPoint"] = "tzGetMobileUser"; // this action in a readable form
920  $tzSaid = tranzEmbcurl($parms, $reqURL, 'GET', $reqHeaders, '');
921 
922  if (isset($tzSaid['error'])) {
923  if ($tzSaid['error'] == 'hcuH404') {
924  # Catalyst throws 404 when user not found
925  throw new Exception("{$tzSaid['message']}", 404);
926  } else {
927  # look for errors, otherwise decode and save the token
928  throw new Exception("{$tzSaid['message']}", 999);
929  }
930  }
931  $return['status']['response'] = 'true';
932  $return['status']['message'] = 'Success';
933  $return['status']['code'] = '000';
934  $return['data'] = $tzSaid;
935  } catch (Exception $e) {
936  $return['status']['response'] = 'false';
937  $return['status']['message'] = $e->getMessage();
938  $return['status']['code'] = $e->getCode();
939  $return['data'] = array();
940  }
941  return $return;
942 }
943 
944 function tranzAddMobileUser($parms) {
945  # Add a user and account to TZ system, or associates an additional account to an existing user
946  try {
947  if (!isset($parms['RTN']) || !isset($parms['tzServiceURL']) ||
948  !isset($parms['tzLicense']) ||
949  !isset($parms['tzToken']) ||
950  !isset($parms['tzScope']) ||
951  !isset($parms['MBRACCT']) ||
952  !isset($parms['tzAccount']) ||
953  !isset($parms['tzType'])) {
954  throw new Exception("Missing Parameters", 100);
955  }
956 
957  $reqHeaders = array("Content-Type: application/json", "Authorization: {$parms['tzToken']}");
958  $reqURL = "{$parms['tzServiceURL']}/{$parms['RTN']}/Licenses/{$parms['tzLicense']}/MobileUsers";
959  # SHOULD USE MIR HERE
960  $reqData = json_encode(array("UserId" => "{$parms['MBRACCT']}",
961  "AccountNumber" => $parms['tzAccount'], # 1st account from RDCGetAccts call
962  "AccountType" => $parms['tzType'], # 1=Checking, 2=Savings / RDC Account Type
963  "FirstName" => 'Mobile',
964  "LastName" => 'Deposit',
965  "EmailAddress" => urldecode($parms['Ml'])));
966 
967  $parms["environment"]["logPoint"] = "tzAddMobileUser"; // this action in a readable form
968  $tzSaid = tranzEmbcurl($parms, $reqURL, 'POST', $reqHeaders, $reqData);
969  if (HCU_array_key_value('error', $tzSaid)) {
970  # look for errors, otherwise decode and save the token
971  throw new Exception("Error " . HCU_array_key_value('message', $tzSaid), 999);
972  }
973  $return['status']['response'] = 'true';
974  $return['status']['message'] = 'Success';
975  $return['data'] = $tzSaid;
976  } catch (Exception $e) {
977  $return['status']['response'] = 'false';
978  $return['status']['message'] = $e->getMessage();
979  $return['status']['code'] = $e->getCode();
980  $return['data'] = array();
981  }
982  return $return;
983 }
984 
985 function tranzUpdateMobileUser($parms) {
986  # Updates user information in the TZ system
987  try {
988  if (!isset($parms['RTN']) || !isset($parms['tzServiceURL']) ||
989  !isset($parms['tzLicense']) ||
990  !isset($parms['tzToken']) ||
991  !isset($parms['tzScope']) ||
992  !isset($parms['MBRACCT'])) {
993  throw new Exception("Missing Parameters", 100);
994  }
995 
996  $reqHeaders = array("Content-Type: application/json", "Authorization: {$parms['tzToken']}");
997  $reqURL = "{$parms['tzServiceURL']}/{$parms['RTN']}/Licenses/{$parms['tzLicense']}/MobileUsers/{$parms['MBRACCT']}";
998 // $reqData = json_encode(array("FirstName" => '', # send empty? Skip?
999 // "LastName" => '',
1000 // "PhoneNumber" => '', # strip punctuation?
1001 // "EmailAddress" => $parms['Ml'])); # need to URL_encode? HtmlEntities?
1002 // # as temporary measure, send name as Mobile Deposit
1003 // # more permanent fix to follow, get MIR and send actual name (but a lot of error checking & config issues to be resolved)
1004  #$reqData = json_encode(array("EmailAddress" => urldecode($parms['Ml']))); # need to URL_encode? HtmlEntities?
1005  # SHOULD USE MIR HERE
1006  $reqData = json_encode(array("FirstName" => 'Mobile',
1007  "LastName" => 'Deposit',
1008  "EmailAddress" => urldecode($parms['Ml']))); # need to URL_encode? HtmlEntities?
1009 
1010 
1011  $parms["environment"]["logPoint"] = "tzUpdMobileUser"; // this action in a readable form
1012  $tzSaid = tranzEmbcurl($parms, $reqURL, 'PUT', $reqHeaders, $reqData);
1013  if (HCU_array_key_value('error', $tzSaid)) {
1014  # look for errors, otherwise decode and save the token
1015  throw new Exception("Error " . HCU_array_key_value('message', $tzSaid), 999);
1016  }
1017  $return['status']['response'] = 'true';
1018  $return['status']['message'] = 'Success';
1019  $return['data'] = $tzSaid;
1020  } catch (Exception $e) {
1021  $return['status']['response'] = 'false';
1022  $return['status']['message'] = $e->getMessage();
1023  $return['status']['code'] = $e->getCode();
1024  $return['data'] = array();
1025  }
1026  return $return;
1027 }
1028 
1029 function tranzGetHistoryList($parms) {
1030 //GET /v1/CreditUnions/{creditUnionId}/Licenses/{licenseKey}/MobileUsers/{userId}/Items
1031 //Gets the deposit history for a user in a credit union
1032 
1033  try {
1034  if (!isset($parms['RTN']) || !isset($parms['tzServiceURL']) ||
1035  !isset($parms['tzLicense']) ||
1036  !isset($parms['tzToken']) ||
1037  !isset($parms['tzScope']) ||
1038  !isset($parms['MBRACCT'])) {
1039  throw new Exception("Missing Parameters", 100);
1040  }
1041 
1042  $reqHeaders = array("Authorization: {$parms['tzToken']}");
1043  $reqURL = "{$parms['tzServiceURL']}/{$parms['RTN']}/Licenses/{$parms['tzLicense']}/MobileUsers/{$parms['MBRACCT']}/Items";
1044 
1045  $parms["environment"]["logPoint"] = "tzGetHistory"; // this action in a readable form
1046  $tzSaid = tranzEmbcurl($parms, $reqURL, 'GET', $reqHeaders, '');
1047  if (HCU_array_key_value('error', $tzSaid)) {
1048  # look for errors, otherwise decode and save the token
1049  throw new Exception("Error " . HCU_array_key_value('message', $tzSaid), 999);
1050  }
1051  $return['status']['response'] = 'true';
1052  $return['status']['message'] = 'Success';
1053  $return['data'] = $tzSaid;
1054  } catch (Exception $e) {
1055  $return['status']['response'] = 'false';
1056  $return['status']['message'] = $e->getMessage();
1057  $return['status']['code'] = $e->getCode();
1058  $return['data'] = array();
1059  }
1060  return $return;
1061 }
1062 
1063 function tranzGetHistoryItem($parms) {
1064 //GET /v1/CreditUnions/{creditUnionId}/Licenses/{licenseKey}/MobileUsers/{userId}/Items
1065 //Gets the deposit history for a user in a credit union
1066 
1067  try {
1068  if (!isset($parms['RTN']) || !isset($parms['tzServiceURL']) ||
1069  !isset($parms['tzLicense']) ||
1070  !isset($parms['tzToken']) ||
1071  !isset($parms['tzScope']) ||
1072  !isset($parms['MBRACCT'])) {
1073  throw new Exception("Missing Parameters");
1074  }
1075 
1076  $reqHeaders = array("Authorization: {$parms['tzToken']}");
1077  $reqURL = "{$parms['tzServiceURL']}/{$parms['RTN']}/Licenses/{$parms['tzLicense']}/MobileUsers/{$parms['MBRACCT']}/Items";
1078 
1079  $parms["environment"]["logPoint"] = "tzGetHistory"; // this action in a readable form
1080  $tzSaid = tranzEmbcurl($parms, $reqURL, 'GET', $reqHeaders, '');
1081  if (HCU_array_key_value('error', $tzSaid)) {
1082  # look for errors, otherwise decode and save the token
1083  throw new Exception("Error " . HCU_array_key_value('message', $tzSaid), 100);
1084  }
1085  $return['status']['response'] = 'true';
1086  $return['status']['message'] = 'Success';
1087  $return['data'] = $tzSaid;
1088  } catch (Exception $e) {
1089  $return['status']['response'] = 'false';
1090  $return['status']['message'] = $e->getMessage();
1091  $return['status']['code'] = $e->getCode();
1092  $return['data'] = array();
1093  }
1094  return $return;
1095 }
1096 
1097 function tranzPostItem($parms) {
1098 # Deposts a mobile item in a new batch and immediately submits that batch.
1099 # If the item was unable to be processed, the item and batch are rejected
1100 #
1101 # $parms['tzServiceURL']
1102 # $parms['certfile']
1103 # $parms['SessionStateId']
1104 # $parms['amount']
1105 
1106  try {
1107 
1108  $tzSaid = [];
1109 
1110  $reqParms = [
1111  'RTN' => 1,
1112  'tzLicense' => 1,
1113  'tzToken' => 1,
1114  'tzScope' => 1,
1115  'MBRACCT' => 1,
1116  'AccountNumber' => 1,
1117  'AccountType' => 1,
1118  'CheckFront' => 1,
1119  'CheckBack' => 1,
1120  'amount' => 1
1121  ];
1122 
1123  $missing = '';
1124 
1125  foreach (array_keys($reqParms) as $reqKey) {
1126  if (!isset($parms[$reqKey])) {
1127  $missing .= "$reqKey ";
1128  }
1129  }
1130  if (strlen($missing) ) {
1131  if ($parms["logging"] == "enabled") {
1132  $logParms = Array();
1133  $logParms = $parms["environment"]; // get the environment info passed in
1134  $logParms["token"] = ''; // the id used across all communications in session
1135  $logParms["txnId"] = time(); // the id for this transaction
1136  $logParms["logPoint"] = "tzPostItem Error";
1137  $logParms["request"] = "Missing $missing"; // the request
1138  $logParms["reply"] = print_r($parms, true); // the response
1139  LogSSOActivity($logParms);
1140  }
1141 
1142  throw new Exception("Missing Parameters", 100);
1143  }
1144 
1145 
1146  $deposittime = date('c');
1147 
1148  $reqHeaders = array("Content-Type: application/json", "Authorization: {$parms['tzToken']}");
1149  $reqURL = "{$parms['tzServiceURL']}/{$parms['RTN']}/Licenses/{$parms['tzLicense']}/MobileUsers/{$parms['MBRACCT']}/Items";
1150  $reqData = array("Accountnumber" => "{$parms['AccountNumber']}",
1151  "AccountType" => $parms['AccountType'],
1152  "Amount" => sprintf('%.2f', $parms['amount'] * .01),
1153  "FrontImage" => "{$parms['CheckFront']}",
1154  "BackImage" => "{$parms['CheckBack']}");
1155  if (isset($parms['MobilePhoneId'])) {
1156  $reqData['MobilePhoneId'] = $parms['MobilePhoneId']; # need to URL_encode? HtmlEntities?
1157  }
1158  if (isset($parms['MobileDeviceDescription'])) {
1159  $reqData['MobileDeviceDescription'] = $parms['MobileDeviceDescription']; # need to URL_encode? HtmlEntities?
1160  }
1161  $reqData = json_encode($reqData);
1162 
1163  $parms["environment"]["logPoint"] = "tzPostItem"; // this action in a readable form
1164  $tzSaid = tranzEmbcurl($parms, $reqURL, 'POST', $reqHeaders, $reqData);
1165  if (HCU_array_key_value('error', $tzSaid)) {
1166  # look for errors, otherwise decode and save the token
1167  throw new Exception("Error " . HCU_array_key_value('message', $tzSaid), 999);
1168  }
1169 // when WasSuccessful is false, don't throw error, just return with messages intact
1170 // so we can reject cleanly in calling function
1171 // if (!$tzSaid['WasSuccessful']) {
1172 // # look for errors, otherwise decode and save the token
1173 // throw new Exception("{$tzSaid['ErrorMessage']},999");
1174 // }
1175 
1176  $return['status']['response'] = 'true';
1177  $return['status']['message'] = 'Success';
1178  $return['data'] = $tzSaid;
1179  } catch (Exception $e) {
1180  $return['status']['response'] = 'false';
1181  $return['status']['message'] = $e->getMessage();
1182  $return['status']['code'] = $e->getCode();
1183  $return['data'] = $tzSaid;
1184  }
1185  return $return;
1186 }
1187 
1188 function tranzEmbcurl($parms, $reqURL, $reqMethod, $reqHeaders, $reqData = '') {
1189  # reqURL is the service url, loginUrl for auth
1190  # reqMethod is yeah, the method
1191  # reqHeaders is an array of headers to be sent
1192  # will include Authorization: oauth token for all calls after the get token
1193 
1194  $curlopts = array(
1195  CURLOPT_RETURNTRANSFER => 1,
1196  CURLOPT_SSL_VERIFYPEER => 0,
1197  CURLOPT_SSL_VERIFYHOST => 0,
1198  CURLOPT_HEADER => FALSE,
1199  CURLOPT_URL => "$reqURL");
1200 
1201  $ch = curl_init();
1202 
1203 //curl_setopt($ch, CURLOPT_VERBOSE, true);
1204 //$verbose = fopen('/tmp/tztrace', 'a+');
1205 //curl_setopt($ch, CURLOPT_STDERR, $verbose);
1206 
1207  curl_setopt_array($ch, $curlopts);
1208  if ($reqMethod != 'GET') {
1209  curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $reqMethod);
1210  }
1211  if (strlen($reqData) > 0) {
1212  curl_setopt($ch, CURLOPT_POSTFIELDS, $reqData);
1213  }
1214  curl_setopt($ch, CURLOPT_HTTPHEADER, $reqHeaders);
1215 
1216  $respERR = '';
1217  $respArr = '';
1218  $response = curl_exec($ch);
1219  $respHTTP = curl_getinfo($ch, CURLINFO_HTTP_CODE);
1220  $respCURL = curl_errno($ch);
1221 
1222  if ($respCURL) {
1223  # Bad! Don't hide the error, return the curl error if it occurred.
1224  $respERR = "HCUERROR: Connection Failed cURL $respCURL";
1225  $respArr = array("error" => "hcuC{$respCURL}", "message" => "$respERR");
1226  } elseif ($respHTTP > 400 && $respHTTP < 600) {
1227  # HTTP Response 4xx client error or 5xx server error
1228  $respArr = json_decode($response, true);
1229  $respERR = "HCUERROR: Connection Failed HTTP $respHTTP " . $respArr['Message'];
1230  $respArr = array("error" => "hcuH{$respHTTP}", "message" => "$respERR");
1231  } elseif (!isset($response) || $response == '') {
1232  if ($respHTTP == 204) {
1233  # HTTP 204 No Content w/o response = 'Everything OK but no data'
1234  $respArr = array();
1235  } else {
1236  $respArr = array("error" => "hcuE", "message" => "Empty Response");
1237  }
1238  } else {
1239  $respArr = json_decode($response, TRUE);
1240  if (is_null($respArr)) {
1241  $respArr = array("error" => "tzE", "message" => "Invalid Response");
1242  }
1243  if (!empty($respArr['Message'])) {
1244  $respArr = array("error" => "tzE", "message" => $respArr['Message']);
1245  }
1246  # tranzAddMobileUser returning system-level config error from TranzCap
1247  # with an extra layer in the response array -- this will catch it...
1248  if (isset($respArr[0]) && !empty($respArr[0]['Message'])) {
1249  $respArr = array("error" => "tzE", "message" => $respArr[0]['Message']);
1250  }
1251  }
1252 
1253  if ($parms["logging"] == "enabled") {
1254  $logParms = $parms["environment"]; // get the environment info passed in
1255  $logParms["token"] = ''; // the id used across all communications in session
1256  $logParms["txnId"] = time(); // the id for this transaction
1257  $logParms["request"] = "curl "; // the request
1258  if ($reqMethod != 'GET') {
1259  $logParms["request"] .= "-X $reqMethod ";
1260  }
1261  if (is_array($reqHeaders)) {
1262  foreach ($reqHeaders as $hdr) {
1263  $logParms["request"] .= "-H '$hdr' ";
1264  }
1265  }
1266  # for PostItem call, reqData includes images
1267  # "FrontImage" => "{$parms['CheckFront']}",
1268  # "BackImage" => "{$parms['CheckBack']}");
1269  # no need to log big encoded blobs of data
1270  # take them out before logging
1271  if (strlen($reqData) > 0) {
1272  $logReq = json_decode($reqData, TRUE);
1273  if (HCU_array_key_value('FrontImage', $logReq) ) {
1274  $logReq['FrontImage'] = 'base64_encoded Image Data';
1275  }
1276  if (HCU_array_key_value('BackImage', $logReq) ) {
1277  $logReq['BackImage'] = 'base64_encoded Image Data';
1278  }
1279  $logReq = json_encode($logReq);
1280  $logParms["request"] .= "-d '$logReq' "; // the request
1281  }
1282  $logParms["request"] .= "'$reqURL' "; // the request
1283  $logParms["reply"] = $response; // the response
1284  if ($respERR > '') {
1285  $logParms["reply"] .= "\n$respERR";
1286  }
1287  LogSSOActivity($logParms);
1288  }
1289 
1290  @curl_close($ch);
1291  return $respArr;
1292 }
1293 
1294 function LogToFile($line, $title, $show) {
1295  # call as LogToFile( __LINE__ ,"Title",$array_to_print);
1296  $log = date('Y-m-d H:i:s');
1297  $tfile = fopen("/tmp/tzLog", "a");
1298  fwrite($tfile, "+++ $log $line +++++++++++++++\n");
1299  fwrite($tfile, " $title " . print_r($show, true));
1300  fwrite($tfile, "\n++++++++++++++++++\n");
1301  fclose($tfile);
1302 }
1303 
1304 ?>