3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.7 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2015 |
7 +--------------------------------------------------------------------+
8 | This file is a part of CiviCRM. |
10 | CiviCRM is free software; you can copy, modify, and distribute it |
11 | under the terms of the GNU Affero General Public License |
12 | Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
14 | CiviCRM is distributed in the hope that it will be useful, but |
15 | WITHOUT ANY WARRANTY; without even the implied warranty of |
16 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
17 | See the GNU Affero General Public License for more details. |
19 | You should have received a copy of the GNU Affero General Public |
20 | License and the CiviCRM Licensing Exception along |
21 | with this program; if not, contact CiviCRM LLC |
22 | at info[AT]civicrm[DOT]org. If you have questions about the |
23 | GNU Affero General Public License or the licensing of CiviCRM, |
24 | see the CiviCRM license FAQ at http://civicrm.org/licensing |
25 +--------------------------------------------------------------------+
31 * @copyright CiviCRM LLC (c) 2004-2015
33 class CiviContributeProcessor
{
34 static $_paypalParamsMapper = array(
35 //category => array(paypal_param => civicrm_field);
37 'salutation' => 'prefix_id',
38 'firstname' => 'first_name',
39 'lastname' => 'last_name',
40 'middlename' => 'middle_name',
41 'suffix' => 'suffix_id',
45 'shiptoname' => 'address_name',
46 'shiptostreet' => 'street_address',
47 'shiptostreet2' => 'supplemental_address_1',
48 'shiptocity' => 'city',
49 'shiptostate' => 'state_province',
50 'shiptozip' => 'postal_code',
51 'countrycode' => 'country',
53 'transaction' => array(
54 'amt' => 'total_amount',
55 'feeamt' => 'fee_amount',
56 'transactionid' => 'trxn_id',
57 'currencycode' => 'currency',
58 'l_name0' => 'source',
59 'ordertime' => 'receive_date',
62 'l_number0' => 'note',
63 'is_test' => 'is_test',
64 'transactiontype' => 'trxn_type',
65 'recurrences' => 'installments',
68 'invnum' => 'invoice_id',
69 'subscriptiondate' => 'start_date',
70 'subscriptionid' => 'processor_id',
71 'timestamp' => 'modified_date',
75 static $_googleParamsMapper = array(
76 //category => array(google_param => civicrm_field);
78 'first-name' => 'first_name',
79 'last-name' => 'last_name',
80 'contact-name' => 'display_name',
84 'address1' => 'street_address',
85 'address2' => 'supplemental_address_1',
87 'postal-code' => 'postal_code',
88 'country-code' => 'country',
90 'transaction' => array(
91 'total-charge-amount' => 'total_amount',
92 'google-order-number' => 'trxn_id',
93 'currency' => 'currency',
94 'item-name' => 'source',
95 'item-description' => 'note',
96 'timestamp' => 'receive_date',
97 'latest-charge-fee' => 'fee_amount',
98 'net-amount' => 'net_amount',
99 'times' => 'installments',
100 'period' => 'frequency_unit',
101 'frequency_interval' => 'frequency_interval',
102 'start_date' => 'start_date',
103 'modified_date' => 'modified_date',
104 'trxn_type' => 'trxn_type',
105 'amount' => 'amount',
109 static $_csvParamsMapper = array(
110 // Note: if csv header is not present in the mapper, header itself
111 // is considered as a civicrm field.
112 //category => array(csv_header => civicrm_field);
114 'first_name' => 'first_name',
115 'last_name' => 'last_name',
116 'middle_name' => 'middle_name',
120 'street_address' => 'street_address',
121 'supplemental_address_1' => 'supplemental_address_1',
123 'postal_code' => 'postal_code',
124 'country' => 'country',
126 'transaction' => array(
127 'total_amount' => 'total_amount',
128 'trxn_id' => 'trxn_id',
129 'currency' => 'currency',
130 'source' => 'source',
131 'receive_date' => 'receive_date',
133 'is_test' => 'is_test',
138 * @param $paymentProcessor
139 * @param $paymentMode
143 public static function paypal($paymentProcessor, $paymentMode, $start, $end) {
144 $url = "{$paymentProcessor['url_api']}nvp";
147 'user' => $paymentProcessor['user_name'],
148 'pwd' => $paymentProcessor['password'],
149 'signature' => $paymentProcessor['signature'],
155 'method' => 'TransactionSearch',
156 'startdate' => $start,
160 require_once 'CRM/Core/Payment/PayPalImpl.php';
162 // as invokeAPI fetch only last 100 transactions.
163 // we should require recursive calls to process more than 100.
164 // first fetch transactions w/ give date intervals.
165 // if we get error code w/ result, which means we do have more than 100
166 // manipulate date interval accordingly and fetch again.
169 $result = CRM_Core_Payment_PayPalImpl
::invokeAPI($args, $url);
170 require_once "CRM/Contribute/BAO/Contribution/Utils.php";
172 $keyArgs['method'] = 'GetTransactionDetails';
173 foreach ($result as $name => $value) {
174 if (substr($name, 0, 15) == 'l_transactionid') {
176 // We don't/can't process subscription notifications, which appear
177 // to be identified by transaction ids beginning with S-
178 if (substr($value, 0, 2) == 'S-') {
182 // Before we bother making a remote API call to PayPal to lookup
183 // details about a transaction, let's make sure that it doesn't
184 // already exist in the database.
185 require_once 'CRM/Contribute/DAO/Contribution.php';
186 $dao = new CRM_Contribute_DAO_Contribution();
187 $dao->trxn_id
= $value;
188 if ($dao->find(TRUE)) {
189 preg_match('/(\d+)$/', $name, $matches);
191 $email = $result["l_email{$seq}"];
192 $amt = $result["l_amt{$seq}"];
193 CRM_Core_Error
::debug_log_message("Skipped (already recorded) - $email, $amt, $value ..<p>", TRUE);
197 $keyArgs['transactionid'] = $value;
198 $trxnDetails = CRM_Core_Payment_PayPalImpl
::invokeAPI($keyArgs, $url);
199 if (is_a($trxnDetails, 'CRM_Core_Error')) {
200 echo "PAYPAL ERROR: Skipping transaction id: $value<p>";
204 // only process completed payments
205 if (strtolower($trxnDetails['paymentstatus']) != 'completed') {
209 // only process receipts, not payments
210 if (strtolower($trxnDetails['transactiontype']) == 'sendmoney') {
214 $params = self
::formatAPIParams($trxnDetails,
215 self
::$_paypalParamsMapper,
218 if ($paymentMode == 'test') {
219 $params['transaction']['is_test'] = 1;
222 $params['transaction']['is_test'] = 0;
225 if (self
::processAPIContribution($params)) {
226 CRM_Core_Error
::debug_log_message("Processed - {$trxnDetails['email']}, {$trxnDetails['amt']}, {$value} ..<p>", TRUE);
229 CRM_Core_Error
::debug_log_message("Skipped - {$trxnDetails['email']}, {$trxnDetails['amt']}, {$value} ..<p>", TRUE);
233 if ($result['l_errorcode0'] == '11002') {
234 $end = $result['l_timestamp99'];
235 $end_time = strtotime("{$end}", time());
236 $end_date = date('Y-m-d\T00:00:00.00\Z', $end_time);
237 $args['enddate'] = $end_date;
239 } while ($result['l_errorcode0'] == '11002');
243 * @param $paymentProcessor
244 * @param $paymentMode
248 public static function google($paymentProcessor, $paymentMode, $start, $end) {
249 require_once "CRM/Contribute/BAO/Contribution/Utils.php";
250 require_once 'CRM/Core/Payment/Google.php';
251 $nextPageToken = TRUE;
252 $searchParams = array(
255 'notification-types' => array('charge-amount'),
258 $response = CRM_Core_Payment_Google
::invokeAPI($paymentProcessor, $searchParams);
260 while ($nextPageToken) {
261 if ($response[0] == 'error') {
262 CRM_Core_Error
::debug_log_message("GOOGLE ERROR: " .
263 $response[1]['error']['error-message']['VALUE'], TRUE
266 $nextPageToken = isset($response[1][$response[0]]['next-page-token']['VALUE']) ?
$response[1][$response[0]]['next-page-token']['VALUE'] : FALSE;
268 if (is_array($response[1][$response[0]]['notifications']['charge-amount-notification'])) {
270 if (array_key_exists('google-order-number',
271 $response[1][$response[0]]['notifications']['charge-amount-notification']
273 // sometimes 'charge-amount-notification' itself is an absolute
274 // array and not array of arrays. This is the case when there is only one
275 // charge-amount-notification. Hack for this special case -
276 $chrgAmt = $response[1][$response[0]]['notifications']['charge-amount-notification'];
277 unset($response[1][$response[0]]['notifications']['charge-amount-notification']);
278 $response[1][$response[0]]['notifications']['charge-amount-notification'][] = $chrgAmt;
281 foreach ($response[1][$response[0]]['notifications']['charge-amount-notification'] as $amtData) {
282 $searchParams = array(
283 'order-numbers' => array($amtData['google-order-number']['VALUE']),
284 'notification-types' => array('risk-information', 'new-order', 'charge-amount'),
286 $response = CRM_Core_Payment_Google
::invokeAPI($paymentProcessor,
289 // append amount information as well
290 $response[] = $amtData;
292 $params = self
::formatAPIParams($response,
293 self
::$_googleParamsMapper,
296 if ($paymentMode == 'test') {
297 $params['transaction']['is_test'] = 1;
300 $params['transaction']['is_test'] = 0;
302 if (self
::processAPIContribution($params)) {
303 CRM_Core_Error
::debug_log_message("Processed - {$params['email']}, {$amtData['total-charge-amount']['VALUE']}, {$amtData['google-order-number']['VALUE']} ..<p>", TRUE);
306 CRM_Core_Error
::debug_log_message("Skipped - {$params['email']}, {$amtData['total-charge-amount']['VALUE']}, {$amtData['google-order-number']['VALUE']} ..<p>", TRUE);
310 if ($nextPageToken) {
311 $searchParams = array('next-page-token' => $nextPageToken);
312 $response = CRM_Core_Payment_Google
::invokeAPI($paymentProcessor, $searchParams);
318 public static function csv() {
319 $csvFile = '/home/deepak/Desktop/crm-4247.csv';
323 $handle = fopen($csvFile, "r");
325 CRM_Core_Error
::fatal("Can't locate csv file.");
328 require_once "CRM/Contribute/BAO/Contribution/Utils.php";
329 while (($data = fgetcsv($handle, 1000, $delimiter)) !== FALSE) {
331 $data['header'] = $header;
332 $params = self
::formatAPIParams($data,
333 self
::$_csvParamsMapper,
336 if (self
::processAPIContribution($params)) {
337 CRM_Core_Error
::debug_log_message("Processed - line $row of csv file .. {$params['email']}, {$params['transaction']['total_amount']}, {$params['transaction']['trxn_id']} ..<p>", TRUE);
340 CRM_Core_Error
::debug_log_message("Skipped - line $row of csv file .. {$params['email']}, {$params['transaction']['total_amount']}, {$params['transaction']['trxn_id']} ..<p>", TRUE);
343 // clean up memory from dao's
344 CRM_Core_DAO
::freeResult();
347 // we assuming - first row is always the header line
349 CRM_Core_Error
::debug_log_message("Considering first row ( line $row ) as HEADER ..<p>", TRUE);
351 if (empty($header)) {
352 CRM_Core_Error
::fatal("Header is empty.");
360 public static function process() {
361 require_once 'CRM/Utils/Request.php';
363 $type = CRM_Utils_Request
::retrieve('type', 'String', CRM_Core_DAO
::$_nullObject, FALSE, 'csv', 'REQUEST');
364 $type = strtolower($type);
369 $start = CRM_Utils_Request
::retrieve('start', 'String',
370 CRM_Core_DAO
::$_nullObject, FALSE, 31, 'REQUEST'
372 $end = CRM_Utils_Request
::retrieve('end', 'String',
373 CRM_Core_DAO
::$_nullObject, FALSE, 0, 'REQUEST'
376 CRM_Core_Error
::fatal("Start offset can't be less than End offset.");
379 $start = date('Y-m-d', time() - $start * 24 * 60 * 60) . 'T00:00:00.00Z';
380 $end = date('Y-m-d', time() - $end * 24 * 60 * 60) . 'T23:59:00.00Z';
382 $ppID = CRM_Utils_Request
::retrieve('ppID', 'Integer',
383 CRM_Core_DAO
::$_nullObject, TRUE, NULL, 'REQUEST'
385 $mode = CRM_Utils_Request
::retrieve('ppMode', 'String',
386 CRM_Core_DAO
::$_nullObject, FALSE, 'live', 'REQUEST'
389 $paymentProcessor = CRM_Financial_BAO_PaymentProcessor
::getPayment($ppID, $mode);
391 CRM_Core_Error
::debug_log_message("Start Date=$start, End Date=$end, ppID=$ppID, mode=$mode <p>", TRUE);
393 return self
::$type($paymentProcessor, $mode, $start, $end);
401 * @param array $apiParams
403 * @param string $type
404 * @param bool $category
408 public static function formatAPIParams($apiParams, $mapper, $type = 'paypal', $category = TRUE) {
409 $type = strtolower($type);
411 if (!in_array($type, array(
417 // return the params as is
420 $params = $transaction = array();
422 if ($type == 'paypal') {
423 foreach ($apiParams as $detail => $val) {
424 if (isset($mapper['contact'][$detail])) {
425 $params[$mapper['contact'][$detail]] = $val;
427 elseif (isset($mapper['location'][$detail])) {
428 $params['address'][1][$mapper['location'][$detail]] = $val;
430 elseif (isset($mapper['transaction'][$detail])) {
433 // Sadly, PayPal seems to send two distinct data elements in a single field,
434 // so we break them out here. This is somewhat ugly and tragic.
441 list($frequency_interval, $frequency_unit) = explode(' ', $val);
442 $transaction['frequency_interval'] = $frequency_interval;
443 $transaction['frequency_unit'] = $freqUnits[$frequency_unit];
446 case 'subscriptiondate':
448 // PayPal dates are in ISO-8601 format. We need a format that
450 $unix_timestamp = strtotime($val);
451 $transaction[$mapper['transaction'][$detail]] = date('YmdHis', $unix_timestamp);
458 $val = "[PayPal_field:{$detail}] {$val}";
459 $transaction[$mapper['transaction'][$detail]] = !empty($transaction[$mapper['transaction'][$detail]]) ?
$transaction[$mapper['transaction'][$detail]] . " <br/> " . $val : $val;
464 $transaction[$mapper['transaction'][$detail]] = $val;
469 if (!empty($transaction) && $category) {
470 $params['transaction'] = $transaction;
473 $params +
= $transaction;
476 CRM_Contribute_BAO_Contribution_Utils
::_fillCommonParams($params, $type);
481 if ($type == 'csv') {
482 $header = $apiParams['header'];
483 unset($apiParams['header']);
484 foreach ($apiParams as $key => $val) {
485 if (isset($mapper['contact'][$header[$key]])) {
486 $params[$mapper['contact'][$header[$key]]] = $val;
488 elseif (isset($mapper['location'][$header[$key]])) {
489 $params['address'][1][$mapper['location'][$header[$key]]] = $val;
491 elseif (isset($mapper['transaction'][$header[$key]])) {
492 $transaction[$mapper['transaction'][$header[$key]]] = $val;
495 $params[$header[$key]] = $val;
499 if (!empty($transaction) && $category) {
500 $params['transaction'] = $transaction;
503 $params +
= $transaction;
506 CRM_Contribute_BAO_Contribution_Utils
::_fillCommonParams($params, $type);
511 if ($type == 'google') {
512 // return if response smell invalid
513 if (!array_key_exists('risk-information-notification', $apiParams[1][$apiParams[0]]['notifications'])) {
516 $riskInfo = &$apiParams[1][$apiParams[0]]['notifications']['risk-information-notification'];
518 if (array_key_exists('new-order-notification', $apiParams[1][$apiParams[0]]['notifications'])) {
519 $newOrder = &$apiParams[1][$apiParams[0]]['notifications']['new-order-notification'];
522 if ($riskInfo['google-order-number']['VALUE'] == $apiParams[2]['google-order-number']['VALUE']) {
523 foreach ($riskInfo['risk-information']['billing-address'] as $field => $info) {
524 if (!empty($mapper['location'][$field])) {
525 $params['address'][1][$mapper['location'][$field]] = $info['VALUE'];
527 elseif (!empty($mapper['contact'][$field])) {
528 if ($newOrder && !empty($newOrder['buyer-billing-address']['structured-name'])) {
529 foreach ($newOrder['buyer-billing-address']['structured-name'] as $namePart => $nameValue) {
530 $params[$mapper['contact'][$namePart]] = $nameValue['VALUE'];
534 $params[$mapper['contact'][$field]] = $info['VALUE'];
537 elseif (!empty($mapper['transaction'][$field])) {
538 $transaction[$mapper['transaction'][$field]] = $info['VALUE'];
542 // Response is an huge array. Lets pickup only those which we ineterested in
543 // using a local mapper, rather than traversing the entire array.
544 $localMapper = array(
545 'google-order-number' => $riskInfo['google-order-number']['VALUE'],
546 'total-charge-amount' => $apiParams[2]['total-charge-amount']['VALUE'],
547 'currency' => $apiParams[2]['total-charge-amount']['currency'],
548 'item-name' => $newOrder['shopping-cart']['items']['item']['item-name']['VALUE'],
549 'timestamp' => $apiParams[2]['timestamp']['VALUE'],
551 if (array_key_exists('latest-charge-fee', $apiParams[2])) {
552 $localMapper['latest-charge-fee'] = $apiParams[2]['latest-charge-fee']['total']['VALUE'];
553 $localMapper['net-amount'] = $localMapper['total-charge-amount'] - $localMapper['latest-charge-fee'];
556 // This is a subscription (recurring) donation.
557 if (array_key_exists('subscription', $newOrder['shopping-cart']['items']['item'])) {
558 $subscription = $newOrder['shopping-cart']['items']['item']['subscription'];
559 $localMapper['amount'] = $newOrder['order-total']['VALUE'];
560 $localMapper['times'] = $subscription['payments']['subscription-payment']['times'];
561 // Convert Google's period to one compatible with the CiviCRM db field.
565 'MONHTLY' => 'month',
568 $localMapper['period'] = $freqUnits[$subscription['period']];
569 // Unlike PayPal, Google has no concept of freq. interval, it is always 1.
570 $localMapper['frequency_interval'] = '1';
571 // Google Checkout dates are in ISO-8601 format. We need a format that
573 $unix_timestamp = strtotime($localMapper['timestamp']);
574 $mysql_date = date('YmdHis', $unix_timestamp);
575 $localMapper['modified_date'] = $mysql_date;
576 $localMapper['start_date'] = $mysql_date;
577 // This is PayPal's nomenclature, but just use it for Google as well since
578 // we act on the value of trxn_type in processAPIContribution().
579 $localMapper['trxn_type'] = 'subscrpayment';
582 foreach ($localMapper as $localKey => $localVal) {
583 if (!empty($mapper['transaction'][$localKey])) {
584 $transaction[$mapper['transaction'][$localKey]] = $localVal;
588 if (empty($params) && empty($transaction)) {
592 if (!empty($transaction) && $category) {
593 $params['transaction'] = $transaction;
596 $params +
= $transaction;
599 CRM_Contribute_BAO_Contribution_Utils
::_fillCommonParams($params, $type);
606 * @param array $params
610 public static function processAPIContribution($params) {
611 if (empty($params) ||
array_key_exists('error', $params)) {
615 // add contact using dedupe rule
616 $dedupeParams = CRM_Dedupe_Finder
::formatParams($params, 'Individual');
617 $dedupeParams['check_permission'] = FALSE;
618 $dupeIds = CRM_Dedupe_Finder
::dupesByParams($dedupeParams, 'Individual');
619 // if we find more than one contact, use the first one
620 if (!empty($dupeIds[0])) {
621 $params['contact_id'] = $dupeIds[0];
623 $contact = CRM_Contact_BAO_Contact
::create($params);
628 // only pass transaction params to contribution::create, if available
629 if (array_key_exists('transaction', $params)) {
630 $params = $params['transaction'];
631 $params['contact_id'] = $contact->id
;
634 // handle contribution custom data
635 $customFields = CRM_Core_BAO_CustomField
::getFields('Contribution',
638 CRM_Utils_Array
::value('financial_type_id',
642 $params['custom'] = CRM_Core_BAO_CustomField
::postProcess($params,
643 CRM_Utils_Array
::value('id', $params, NULL),
646 // create contribution
648 // if this is a recurring contribution then process it first
649 if ($params['trxn_type'] == 'subscrpayment') {
650 // see if a recurring record already exists
651 $recurring = new CRM_Contribute_BAO_ContributionRecur();
652 $recurring->processor_id
= $params['processor_id'];
653 if (!$recurring->find(TRUE)) {
654 $recurring = new CRM_Contribute_BAO_ContributionRecur();
655 $recurring->invoice_id
= $params['invoice_id'];
656 $recurring->find(TRUE);
659 // This is the same thing the CiviCRM IPN handler does to handle
660 // subsequent recurring payments to avoid duplicate contribution
661 // errors due to invoice ID. See:
662 // ./CRM/Core/Payment/PayPalIPN.php:200
663 if ($recurring->id
) {
664 $params['invoice_id'] = md5(uniqid(rand(), TRUE));
667 $recurring->copyValues($params);
669 if (is_a($recurring, 'CRM_Core_Error')) {
673 $params['contribution_recur_id'] = $recurring->id
;
677 $contribution = &CRM_Contribute_BAO_Contribution
::create($params,
678 CRM_Core_DAO
::$_nullArray
680 if (!$contribution->id
) {
689 // bootstrap the environment and run the processor
691 require_once '../civicrm.config.php';
692 require_once 'CRM/Core/Config.php';
693 $config = CRM_Core_Config
::singleton();
695 CRM_Utils_System
::authenticateScript(TRUE);
697 //log the execution of script
698 CRM_Core_Error
::debug_log_message('ContributionProcessor.php');
700 $lock = Civi\Core\Container
::singleton()->get('lockManager')->acquire('worker.contribute.CiviContributeProcessor');
702 if ($lock->isAcquired()) {
703 // try to unset any time limits
704 if (!ini_get('safe_mode')) {
708 CiviContributeProcessor
::process();
711 throw new Exception('Could not acquire lock, another CiviContributeProcessor process is running');
716 echo "Done processing<p>";