3 +--------------------------------------------------------------------+
4 | Copyright CiviCRM LLC. All rights reserved. |
6 | This work is published under the GNU AGPLv3 license with some |
7 | permitted exceptions and without any warranty. For full license |
8 | and copyright information, see https://civicrm.org/licensing |
9 +--------------------------------------------------------------------+
15 * @copyright CiviCRM LLC https://civicrm.org/licensing
17 class CiviContributeProcessor
{
18 public static $_paypalParamsMapper = array(
19 //category => array(paypal_param => civicrm_field);
21 'salutation' => 'prefix_id',
22 'firstname' => 'first_name',
23 'lastname' => 'last_name',
24 'middlename' => 'middle_name',
25 'suffix' => 'suffix_id',
29 'shiptoname' => 'address_name',
30 'shiptostreet' => 'street_address',
31 'shiptostreet2' => 'supplemental_address_1',
32 'shiptocity' => 'city',
33 'shiptostate' => 'state_province',
34 'shiptozip' => 'postal_code',
35 'countrycode' => 'country',
37 'transaction' => array(
38 'amt' => 'total_amount',
39 'feeamt' => 'fee_amount',
40 'transactionid' => 'trxn_id',
41 'currencycode' => 'currency',
42 'l_name0' => 'source',
43 'ordertime' => 'receive_date',
46 'l_number0' => 'note',
47 'is_test' => 'is_test',
48 'transactiontype' => 'trxn_type',
49 'recurrences' => 'installments',
52 'invnum' => 'invoice_id',
53 'subscriptiondate' => 'start_date',
54 'subscriptionid' => 'processor_id',
55 'timestamp' => 'modified_date',
60 * Note: if csv header is not present in the mapper, header itself
61 * is considered as a civicrm field.
62 * category => array(csv_header => civicrm_field);
65 public static $_csvParamsMapper = array(
67 'first_name' => 'first_name',
68 'last_name' => 'last_name',
69 'middle_name' => 'middle_name',
73 'street_address' => 'street_address',
74 'supplemental_address_1' => 'supplemental_address_1',
76 'postal_code' => 'postal_code',
77 'country' => 'country',
79 'transaction' => array(
80 'total_amount' => 'total_amount',
81 'trxn_id' => 'trxn_id',
82 'currency' => 'currency',
84 'receive_date' => 'receive_date',
86 'is_test' => 'is_test',
91 * @param $paymentProcessor
96 public static function paypal($paymentProcessor, $paymentMode, $start, $end) {
97 $url = "{$paymentProcessor['url_api']}nvp";
100 'user' => $paymentProcessor['user_name'],
101 'pwd' => $paymentProcessor['password'],
102 'signature' => $paymentProcessor['signature'],
108 'method' => 'TransactionSearch',
109 'startdate' => $start,
113 require_once 'CRM/Core/Payment/PayPalImpl.php';
115 // as invokeAPI fetch only last 100 transactions.
116 // we should require recursive calls to process more than 100.
117 // first fetch transactions w/ give date intervals.
118 // if we get error code w/ result, which means we do have more than 100
119 // manipulate date interval accordingly and fetch again.
122 $result = CRM_Core_Payment_PayPalImpl
::invokeAPI($args, $url);
123 require_once "CRM/Contribute/BAO/Contribution/Utils.php";
125 $keyArgs['method'] = 'GetTransactionDetails';
126 foreach ($result as $name => $value) {
127 if (substr($name, 0, 15) == 'l_transactionid') {
129 // We don't/can't process subscription notifications, which appear
130 // to be identified by transaction ids beginning with S-
131 if (substr($value, 0, 2) == 'S-') {
135 // Before we bother making a remote API call to PayPal to lookup
136 // details about a transaction, let's make sure that it doesn't
137 // already exist in the database.
138 require_once 'CRM/Contribute/DAO/Contribution.php';
139 $dao = new CRM_Contribute_DAO_Contribution();
140 $dao->trxn_id
= $value;
141 if ($dao->find(TRUE)) {
142 preg_match('/(\d+)$/', $name, $matches);
144 $email = $result["l_email{$seq}"];
145 $amt = $result["l_amt{$seq}"];
146 CRM_Core_Error
::debug_log_message("Skipped (already recorded) - $email, $amt, $value ..<p>", TRUE);
150 $keyArgs['transactionid'] = $value;
151 $trxnDetails = CRM_Core_Payment_PayPalImpl
::invokeAPI($keyArgs, $url);
152 if (is_a($trxnDetails, 'CRM_Core_Error')) {
153 echo "PAYPAL ERROR: Skipping transaction id: $value<p>";
157 // only process completed payments
158 if (strtolower($trxnDetails['paymentstatus']) != 'completed') {
162 // only process receipts, not payments
163 if (strtolower($trxnDetails['transactiontype']) == 'sendmoney') {
167 $params = self
::formatAPIParams($trxnDetails,
168 self
::$_paypalParamsMapper,
171 if ($paymentMode == 'test') {
172 $params['transaction']['is_test'] = 1;
175 $params['transaction']['is_test'] = 0;
179 if (self
::processAPIContribution($params)) {
180 CRM_Core_Error
::debug_log_message("Processed - {$trxnDetails['email']}, {$trxnDetails['amt']}, {$value} ..<p>", TRUE);
183 CRM_Core_Error
::debug_log_message("Skipped - {$trxnDetails['email']}, {$trxnDetails['amt']}, {$value} ..<p>", TRUE);
186 catch (CiviCRM_API3_Exception
$e) {
187 CRM_Core_Error
::debug_log_message("Skipped - {$trxnDetails['email']}, {$trxnDetails['amt']}, {$value} ..<p>", TRUE);
191 if ($result['l_errorcode0'] == '11002') {
192 $end = $result['l_timestamp99'];
193 $end_time = strtotime("{$end}", time());
194 $end_date = date('Y-m-d\T00:00:00.00\Z', $end_time);
195 $args['enddate'] = $end_date;
197 } while ($result['l_errorcode0'] == '11002');
200 public static function csv() {
201 $csvFile = '/home/deepak/Desktop/crm-4247.csv';
205 $handle = fopen($csvFile, "r");
207 throw new CRM_Core_Exception("Can't locate csv file.");
210 require_once "CRM/Contribute/BAO/Contribution/Utils.php";
211 while (($data = fgetcsv($handle, 1000, $delimiter)) !== FALSE) {
213 $data['header'] = $header;
214 $params = self
::formatAPIParams($data,
215 self
::$_csvParamsMapper,
218 if (self
::processAPIContribution($params)) {
219 CRM_Core_Error
::debug_log_message("Processed - line $row of csv file .. {$params['email']}, {$params['transaction']['total_amount']}, {$params['transaction']['trxn_id']} ..<p>", TRUE);
222 CRM_Core_Error
::debug_log_message("Skipped - line $row of csv file .. {$params['email']}, {$params['transaction']['total_amount']}, {$params['transaction']['trxn_id']} ..<p>", TRUE);
225 // clean up memory from dao's
226 CRM_Core_DAO
::freeResult();
229 // we assuming - first row is always the header line
231 CRM_Core_Error
::debug_log_message("Considering first row ( line $row ) as HEADER ..<p>", TRUE);
233 if (empty($header)) {
234 throw new CRM_Core_Exception("Header is empty.");
242 public static function process() {
243 require_once 'CRM/Utils/Request.php';
245 $type = CRM_Utils_Request
::retrieve('type', 'String', CRM_Core_DAO
::$_nullObject, FALSE, 'csv', 'REQUEST');
246 $type = strtolower($type);
250 $start = CRM_Utils_Request
::retrieve('start', 'String',
251 CRM_Core_DAO
::$_nullObject, FALSE, 31, 'REQUEST'
253 $end = CRM_Utils_Request
::retrieve('end', 'String',
254 CRM_Core_DAO
::$_nullObject, FALSE, 0, 'REQUEST'
257 throw new CRM_Core_Exception("Start offset can't be less than End offset.");
260 $start = date('Y-m-d', time() - $start * 24 * 60 * 60) . 'T00:00:00.00Z';
261 $end = date('Y-m-d', time() - $end * 24 * 60 * 60) . 'T23:59:00.00Z';
263 $ppID = CRM_Utils_Request
::retrieve('ppID', 'Integer',
264 CRM_Core_DAO
::$_nullObject, TRUE, NULL, 'REQUEST'
266 $mode = CRM_Utils_Request
::retrieve('ppMode', 'String',
267 CRM_Core_DAO
::$_nullObject, FALSE, 'live', 'REQUEST'
270 $paymentProcessor = CRM_Financial_BAO_PaymentProcessor
::getPayment($ppID, $mode);
272 CRM_Core_Error
::debug_log_message("Start Date=$start, End Date=$end, ppID=$ppID, mode=$mode <p>", TRUE);
274 return self
::$type($paymentProcessor, $mode, $start, $end);
282 * @param array $apiParams
284 * @param string $type
285 * @param bool $category
289 public static function formatAPIParams($apiParams, $mapper, $type = 'paypal', $category = TRUE) {
290 $type = strtolower($type);
292 if (!in_array($type, array(
297 // return the params as is
300 $params = $transaction = array();
302 if ($type == 'paypal') {
303 foreach ($apiParams as $detail => $val) {
304 if (isset($mapper['contact'][$detail])) {
305 $params[$mapper['contact'][$detail]] = $val;
307 elseif (isset($mapper['location'][$detail])) {
308 $params['address'][1][$mapper['location'][$detail]] = $val;
310 elseif (isset($mapper['transaction'][$detail])) {
313 // Sadly, PayPal seems to send two distinct data elements in a single field,
314 // so we break them out here. This is somewhat ugly and tragic.
321 list($frequency_interval, $frequency_unit) = explode(' ', $val);
322 $transaction['frequency_interval'] = $frequency_interval;
323 $transaction['frequency_unit'] = $freqUnits[$frequency_unit];
326 case 'subscriptiondate':
328 // PayPal dates are in ISO-8601 format. We need a format that
330 $unix_timestamp = strtotime($val);
331 $transaction[$mapper['transaction'][$detail]] = date('YmdHis', $unix_timestamp);
338 $val = "[PayPal_field:{$detail}] {$val}";
339 $transaction[$mapper['transaction'][$detail]] = !empty($transaction[$mapper['transaction'][$detail]]) ?
$transaction[$mapper['transaction'][$detail]] . " <br/> " . $val : $val;
344 $transaction[$mapper['transaction'][$detail]] = $val;
349 if (!empty($transaction) && $category) {
350 $params['transaction'] = $transaction;
353 $params +
= $transaction;
356 CRM_Contribute_BAO_Contribution_Utils
::_fillCommonParams($params, $type);
361 if ($type == 'csv') {
362 $header = $apiParams['header'];
363 unset($apiParams['header']);
364 foreach ($apiParams as $key => $val) {
365 if (isset($mapper['contact'][$header[$key]])) {
366 $params[$mapper['contact'][$header[$key]]] = $val;
368 elseif (isset($mapper['location'][$header[$key]])) {
369 $params['address'][1][$mapper['location'][$header[$key]]] = $val;
371 elseif (isset($mapper['transaction'][$header[$key]])) {
372 $transaction[$mapper['transaction'][$header[$key]]] = $val;
375 $params[$header[$key]] = $val;
379 if (!empty($transaction) && $category) {
380 $params['transaction'] = $transaction;
383 $params +
= $transaction;
386 CRM_Contribute_BAO_Contribution_Utils
::_fillCommonParams($params, $type);
394 * @deprecated function.
396 * This function has probably been defunct for quite a long time.
398 * @param array $params
402 public static function processAPIContribution($params) {
403 if (empty($params) ||
array_key_exists('error', $params)) {
407 $params['contact_id'] = CRM_Contact_BAO_Contact
::getFirstDuplicateContact($params, 'Individual', 'Unsupervised', array(), FALSE);
409 $contact = civicrm_api3('Contact', 'create', $params);
411 // only pass transaction params to contribution::create, if available
412 if (array_key_exists('transaction', $params)) {
413 $params = $params['transaction'];
414 $params['contact_id'] = $contact['id'];
417 $params['custom'] = CRM_Core_BAO_CustomField
::postProcess($params,
418 CRM_Utils_Array
::value('id', $params, NULL),
421 // create contribution
423 // if this is a recurring contribution then process it first
424 if ($params['trxn_type'] == 'subscrpayment') {
425 // see if a recurring record already exists
426 $recurring = new CRM_Contribute_BAO_ContributionRecur();
427 $recurring->processor_id
= $params['processor_id'];
428 if (!$recurring->find(TRUE)) {
429 $recurring = new CRM_Contribute_BAO_ContributionRecur();
430 $recurring->invoice_id
= $params['invoice_id'];
431 $recurring->find(TRUE);
434 // This is the same thing the CiviCRM IPN handler does to handle
435 // subsequent recurring payments to avoid duplicate contribution
436 // errors due to invoice ID. See:
437 // ./CRM/Core/Payment/PayPalIPN.php:200
438 if ($recurring->id
) {
439 $params['invoice_id'] = md5(uniqid(rand(), TRUE));
442 $recurring->copyValues($params);
444 if (is_a($recurring, 'CRM_Core_Error')) {
448 $params['contribution_recur_id'] = $recurring->id
;
452 $contribution = CRM_Contribute_BAO_Contribution
::create($params);
453 if (!$contribution->id
) {
462 // bootstrap the environment and run the processor
464 require_once '../civicrm.config.php';
465 require_once 'CRM/Core/Config.php';
466 CRM_Core_Config
::singleton();
468 CRM_Utils_System
::authenticateScript(TRUE);
470 //log the execution of script
471 CRM_Core_Error
::debug_log_message('ContributionProcessor.php');
473 $lock = Civi
::lockManager()->acquire('worker.contribute.CiviContributeProcessor');
475 if ($lock->isAcquired()) {
476 // try to unset any time limits
477 if (!ini_get('safe_mode')) {
481 CiviContributeProcessor
::process();
484 throw new Exception('Could not acquire lock, another CiviContributeProcessor process is running');
489 echo "Done processing<p>";