ILIAS  release_4-3 Revision
 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  {
109 #echo "Wrong customer";
110  return ERROR_WRONG_CUSTOMER;
111  }
112 
113 // check the payment_status is Completed
114  if (!in_array($keyarray["payment_status"], array("Completed", "In-Progress", "Pending", "Processed")))
115  {
116 #echo "Not completed";
117  return ERROR_NOT_COMPLETED;
118  }
119 
120 // check that txn_id has not been previously processed
121  if ($this->__checkTransactionId($keyarray["txn_id"]))
122  {
123  if($_SESSION['tmp_transaction']['result'] == 'success'
124  && $_SESSION['tmp_transaction']['tx_id'] == $keyarray["txn_id"])
125  {
126  // this is for catching the problem, if the user doubleklicks on the paypal
127  // site to return to the ilias shop and his purchasings already exists in db
128  return SUCCESS;
129  }
130  else
131 #echo "Prev. processed trans. id";
132  return ERROR_PREV_TRANS_ID;
133  }
134 
135 // check that receiver_email is your Primary PayPal email
136  if ($keyarray["receiver_email"] != $this->paypalConfig["vendor"])
137  {
138 //echo "Wrong vendor";
139  return ERROR_WRONG_VENDOR;
140  }
141 
142 // check that payment_amount/payment_currency are correct
143  if (!$this->__checkItems($keyarray))
144  {
145 //echo "Wrong items";
146  return ERROR_WRONG_ITEMS;
147  }
148 
149 // if($ilUser->getId() == ANONYMOUS_USER_ID)
150 // {
151 // include_once './Services/Payment/classes/class.ilShopUtils.php';
152 // // anonymous user needs an account to use crs
153 // $ilUser = ilShopUtils::_createRandomUserAccount($keyarray);
154 // $user_id = $ilUser->getId();
155 //
156 // $_SESSION['tmp_transaction']['tx_id'] = $keyarray["txn_id"];
157 // $_SESSION['tmp_transaction']['usr_id'] = $user_id;
158 //
159 // if($_SESSION['is_crs_object'] && ($ilUser->getId() == ANONYMOUS_USER_ID))
160 // {
161 // include_once "./Modules/Course/classes/class.ilCourseParticipants.php";
162 // foreach ($_SESSION['crs_obj_ids'] as $obj_id)
163 // {
164 // $members_obj = ilCourseParticipants::_getInstanceByObjId($obj_id);
165 // $members_obj->add($user_id,IL_CRS_MEMBER);
166 // }
167 // }
168 // }
169 
170  $external_data = array();
171  $external_data['transaction_extern'] = $keyarray["txn_id"];
172  $external_data['street'] = $keyarray["address_street"];
173  $external_data['zipcode'] = $keyarray["address_zip"];
174  $external_data['city'] = $keyarray["address_city"];
175  $external_data['country'] = $keyarray["address_country"];
176 
177  parent::__addBookings($external_data);
178 
179  $_SESSION["coupons"]["paypal"] = array();
180  $_SESSION['tmp_transaction']['result'] = 'success';
181 
182  return SUCCESS;
183  }
184  else if (strcmp ($lines[0], "FAIL") == 0)
185  {
186  return ERROR_FAIL;
187  }
188  else
189  {
190  return ERROR_FAIL;
191  }
192  }
193 
194  private function __checkTransactionId($a_id)
195  {
196  global $ilDB;
197 
198  $res = $ilDB->queryF('SELECT * FROM payment_statistic
199  WHERE transaction_extern = %s',
200  array('text'), array($a_id));
201 
202  return $res->numRows() ? true : false;
203  }
204 
205  private function __checkItems($a_array)
206  {
208 
209 // Wrong currency
210  if ($a_array["mc_currency"] != $genSet->get("currency_unit"))
211  {
212  return false;
213  }
214 
215  $sc = $this->psc_obj->getShoppingCart($this->pay_method);
216  $this->psc_obj->clearCouponItemsSession();
217 
218  if (is_array($sc) && count($sc) > 0)
219  {
220  for ($i = 0; $i < count($sc); $i++)
221  {
222  $items[$i] = array(
223  "name" => $a_array["item_name".($i+1)],
224  "amount" => $a_array["mc_gross_".($i+1)]
225  );
226 
227  if (!empty($_SESSION["coupons"]["paypal"]))
228  {
229  $sc[$i]["math_price"] = (float) $sc[$i]["price"];
230 
231  $tmp_pobject = new ilPaymentObject($this->user_obj, $sc[$i]['pobject_id']);
232 
233  foreach ($_SESSION["coupons"]["paypal"] as $key => $coupon)
234  {
235  $this->coupon_obj->setId($coupon["pc_pk"]);
236  $this->coupon_obj->setCurrentCoupon($coupon);
237 
238  if ($this->coupon_obj->isObjectAssignedToCoupon($tmp_pobject->getRefId()))
239  {
240  $_SESSION["coupons"]["paypal"][$key]["total_objects_coupon_price"] += (float) $sc[$i]["price"];
241  $_SESSION["coupons"]["paypal"][$key]["items"][] = $sc[$i];
242  }
243  }
244  unset($tmp_pobject);
245  }
246  }
247 
248  $coupon_discount_items = $this->psc_obj->calcDiscountPrices($_SESSION["coupons"]["paypal"]);
249 
250  $found = 0;
251  $total = 0;
252  for ($i = 0; $i < count($sc); $i++)
253  {
254  if (array_key_exists($sc[$i]["pobject_id"], $coupon_discount_items))
255  {
256  $sc[$i]["price"] = round($coupon_discount_items[$sc[$i]["pobject_id"]]["discount_price"], 2);
257  if ($sc[$i]["price"] < 0) $sc[$i]["price"] = 0.0;
258  }
259 
260  for ($j = 0; $j < count($items); $j++)
261  {
262  if (substr($items[$j]["name"], 0, strlen($sc[$i]["obj_id"])+2) == "[".$sc[$i]["obj_id"]."]" &&
263  $items[$j]["amount"] == $sc[$i]["price"])
264  {
265  $total += $items[$j]["amount"];
266  $found++;
267  }
268  }
269  }
270 
271 // The number of items, the items themselves and their amounts and the total amount correct
272  if (number_format($total, 2, ".", "") == $a_array["mc_gross"] &&
273  $found == count($sc))
274  {
275  return true;
276  }
277  }
278  return false;
279  }
280 
374 }
375 ?>