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