ILIAS  Release_4_2_x_branch Revision 61807
 All Data Structures Namespaces Files Functions Variables Groups Pages
class.ilPurchasePaypal.php
Go to the documentation of this file.
1 <?php
2 /* Copyright (c) 1998-2010 ILIAS open source, Extended GPL, see docs/LICENSE */
13 include_once './Services/Payment/classes/class.ilInvoiceNumberPlaceholdersPropertyGUI.php';
14 include_once './Services/Payment/classes/class.ilPayMethods.php';
15 include_once './Services/Payment/classes/class.ilPurchaseBaseGUI.php';
16 
17 define('SUCCESS', 0);
18 define('ERROR_OPENSOCKET', 1);
19 define('ERROR_WRONG_CUSTOMER', 2);
20 define('ERROR_NOT_COMPLETED', 3);
21 define('ERROR_PREV_TRANS_ID', 4);
22 define('ERROR_WRONG_VENDOR', 5);
23 define('ERROR_WRONG_ITEMS', 6);
24 define('ERROR_FAIL', 7);
25 
27 {
28  /*
29  * id of vendor, admin or trustee
30  */
31  public $psc_obj = null;
32  public $user_obj = null;
33  public $pay_method = null;
34  public $currency = null;
35  public $db = null;
36  public $paypalConfig;
37  private $totalVat = 0;
38 
39  public function ilPurchasePaypal($user_obj)
40  {
41  global $ilDB, $lng;
42 
43  $this->user_obj = $user_obj;
44  $this->pay_method = ilPayMethods::_getIdByTitle('paypal');
45 
47  $this->paypalConfig = $ppSet->getAll();
48 
49  parent::__construct($this->user_obj, $this->pay_method);
50  }
51 
52  public function openSocket()
53  {
54  // post back to PayPal system to validate
55  $fp = @fsockopen ($path = $this->paypalConfig["server_host"], 80, $errno, $errstr, 30);
56  return $fp;
57  }
58 
59  public function checkData($fp)
60  {
61  global $ilUser;
62 
63  //Token from paypal account
64  $auth_token = $this->paypalConfig["auth_token"];
65 
66  //add 'cmd' as required
67  $req = 'cmd=_notify-synch';
68 
69  //Get token
70  $tx_token = $_REQUEST['tx'];
71 
72  //append both tokens as required
73  $req .= "&tx=$tx_token&at=$auth_token";
74 
75  //send information back to paypal
76  // info: https required!!!
77  $submiturl = 'https://'.$this->paypalConfig["server_host"].$this->paypalConfig["server_path"];
78 
79  $ch = curl_init();
80  curl_setopt($ch, CURLOPT_URL,$submiturl);
81  curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);//return into variable
82  curl_setopt($ch, CURLOPT_POST, 1);//make it a post
83  curl_setopt($ch, CURLOPT_POSTFIELDS, $req);//post request
84  curl_setopt($ch, CURLOPT_HTTPHEADER, array("Content-Type: application/x-www-form-urlencoded", "Content-Length: " . strlen($req)));
85  curl_setopt($ch, CURLOPT_HEADER , 0); //dont return headers
86  curl_setopt($ch, CURLOPT_VERBOSE, 1);//more informaiton in error
87  curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);//dont verify
88  curl_setopt($ch, CURLOPT_TIMEOUT, 30);//define timeout
89  $result= @curl_exec($ch);//get result
90  curl_close($ch);//close connection
91 
92 // only for TEST
93 // echo $result;//display response
94 
95  // parse the data
96  $lines = explode("\n", $result);
97 
98  $keyarray = array();
99  $keyarray[0] = $lines[0]; // save payment status!
100 
101  if (strcmp ($lines[0], "SUCCESS") == 0)
102  {
103  for ($i=1; $i<count($lines);$i++)
104  {
105  list($key,$val) = explode("=", $lines[$i]);
106  $keyarray[urldecode($key)] = urldecode($val);
107  }
108 // check customer
109  if ($ilUser->getId() != $keyarray["custom"])
110  {
111 #echo "Wrong customer";
112  return ERROR_WRONG_CUSTOMER;
113  }
114 
115 // check the payment_status is Completed
116  if (!in_array($keyarray["payment_status"], array("Completed", "In-Progress", "Pending", "Processed")))
117  {
118 #echo "Not completed";
119  return ERROR_NOT_COMPLETED;
120  }
121 
122 // check that txn_id has not been previously processed
123  if ($this->__checkTransactionId($keyarray["txn_id"]))
124  {
125  if($_SESSION['tmp_transaction']['result'] == 'success'
126  && $_SESSION['tmp_transaction']['tx_id'] == $keyarray["txn_id"])
127  {
128  // this is for catching the problem, if the user doubleklicks on the paypal
129  // site to return to the ilias shop and his purchasings already exists in db
130  return SUCCESS;
131  }
132  else
133 #echo "Prev. processed trans. id";
134  return ERROR_PREV_TRANS_ID;
135  }
136 
137 // check that receiver_email is your Primary PayPal email
138  if ($keyarray["receiver_email"] != $this->paypalConfig["vendor"])
139  {
140 //echo "Wrong vendor";
141  return ERROR_WRONG_VENDOR;
142  }
143 
144 // check that payment_amount/payment_currency are correct
145  if (!$this->__checkItems($keyarray))
146  {
147 //echo "Wrong items";
148  return ERROR_WRONG_ITEMS;
149  }
150 
151 // if($ilUser->getId() == ANONYMOUS_USER_ID)
152 // {
153 // include_once './Services/Payment/classes/class.ilShopUtils.php';
154 // // anonymous user needs an account to use crs
155 // $ilUser = ilShopUtils::_createRandomUserAccount($keyarray);
156 // $user_id = $ilUser->getId();
157 //
158 // $_SESSION['tmp_transaction']['tx_id'] = $keyarray["txn_id"];
159 // $_SESSION['tmp_transaction']['usr_id'] = $user_id;
160 //
161 // if($_SESSION['is_crs_object'] && ($ilUser->getId() == ANONYMOUS_USER_ID))
162 // {
163 // include_once "./Modules/Course/classes/class.ilCourseParticipants.php";
164 // foreach ($_SESSION['crs_obj_ids'] as $obj_id)
165 // {
166 // $members_obj = ilCourseParticipants::_getInstanceByObjId($obj_id);
167 // $members_obj->add($user_id,IL_CRS_MEMBER);
168 // }
169 // }
170 // }
171 
172  $external_data = array();
173  $external_data['transaction_extern'] = $keyarray["txn_id"];
174  $external_data['street'] = $keyarray["address_street"];
175  $external_data['zipcode'] = $keyarray["address_zip"];
176  $external_data['city'] = $keyarray["address_city"];
177  $external_data['country'] = $keyarray["address_country"];
178 
179  parent::__addBookings($external_data);
180 
181  $_SESSION["coupons"]["paypal"] = array();
182  $_SESSION['tmp_transaction']['result'] = 'success';
183 
184  return SUCCESS;
185  }
186  else if (strcmp ($lines[0], "FAIL") == 0)
187  {
188  return ERROR_FAIL;
189  }
190  else
191  {
192  return ERROR_FAIL;
193  }
194  }
195 
196  private function __checkTransactionId($a_id)
197  {
198  global $ilDB;
199 
200  $res = $ilDB->queryF('SELECT * FROM payment_statistic
201  WHERE transaction_extern = %s',
202  array('text'), array($a_id));
203 
204  return $res->numRows() ? true : false;
205  }
206 
207  private function __checkItems($a_array)
208  {
210 
211 // Wrong currency
212  if ($a_array["mc_currency"] != $genSet->get("currency_unit"))
213  {
214  return false;
215  }
216 
217  $sc = $this->psc_obj->getShoppingCart($this->pay_method);
218  $this->psc_obj->clearCouponItemsSession();
219 
220  if (is_array($sc) && count($sc) > 0)
221  {
222  for ($i = 0; $i < count($sc); $i++)
223  {
224  $items[$i] = array(
225  "name" => $a_array["item_name".($i+1)],
226  "amount" => $a_array["mc_gross_".($i+1)]
227  );
228 
229  if (!empty($_SESSION["coupons"]["paypal"]))
230  {
231  $sc[$i]["math_price"] = (float) $sc[$i]["price"];
232 
233  $tmp_pobject = new ilPaymentObject($this->user_obj, $sc[$i]['pobject_id']);
234 
235  foreach ($_SESSION["coupons"]["paypal"] as $key => $coupon)
236  {
237  $this->coupon_obj->setId($coupon["pc_pk"]);
238  $this->coupon_obj->setCurrentCoupon($coupon);
239 
240  if ($this->coupon_obj->isObjectAssignedToCoupon($tmp_pobject->getRefId()))
241  {
242  $_SESSION["coupons"]["paypal"][$key]["total_objects_coupon_price"] += (float) $sc[$i]["price"];
243  $_SESSION["coupons"]["paypal"][$key]["items"][] = $sc[$i];
244  }
245  }
246  unset($tmp_pobject);
247  }
248  }
249 
250  $coupon_discount_items = $this->psc_obj->calcDiscountPrices($_SESSION["coupons"]["paypal"]);
251 
252  $found = 0;
253  $total = 0;
254  for ($i = 0; $i < count($sc); $i++)
255  {
256  if (array_key_exists($sc[$i]["pobject_id"], $coupon_discount_items))
257  {
258  $sc[$i]["price"] = round($coupon_discount_items[$sc[$i]["pobject_id"]]["discount_price"], 2);
259  if ($sc[$i]["price"] < 0) $sc[$i]["price"] = 0.0;
260  }
261 
262  for ($j = 0; $j < count($items); $j++)
263  {
264  if (substr($items[$j]["name"], 0, strlen($sc[$i]["obj_id"])+2) == "[".$sc[$i]["obj_id"]."]" &&
265  $items[$j]["amount"] == $sc[$i]["price"])
266  {
267  $total += $items[$j]["amount"];
268  $found++;
269  }
270  }
271  }
272 
273 // The number of items, the items themselves and their amounts and the total amount correct
274  if (number_format($total, 2, ".", "") == $a_array["mc_gross"] &&
275  $found == count($sc))
276  {
277  return true;
278  }
279  }
280  return false;
281  }
282 
376 }
377 ?>