Advertisement
Guest User

Untitled

a guest
May 3rd, 2017
399
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 29.40 KB | None | 0 0
  1. <?php
  2. // CONFIG: Enable debug mode. This means we'll log requests into 'ipn.log' in the same directory.
  3. // Especially useful if you encounter network errors or other intermittent problems with IPN (validation).
  4. // Set this to 0 once you go live or don't require logging.
  5. define("DEBUG", 1);
  6. // Set to 0 once you're ready to go live
  7. define("USE_SANDBOX", 0);
  8. define("LOG_FILE", "./ipn.log");
  9. define("LOG_FILE_ERRORS", "./errors.log");
  10. define("LOG_FILE_ATF", "./errorsatf.log");
  11.  
  12. //init vars
  13. //$receiver_email = "paypal@nutrio2.com";
  14. $receiver_id = "AZHAU5PH9YUA2";
  15.  
  16. // Read POST data
  17. // reading posted data directly from $_POST causes serialization
  18. // issues with array data in POST. Reading raw POST data from input stream instead.
  19. $raw_post_data = file_get_contents('php://input');
  20. $raw_post_array = explode('&', $raw_post_data);
  21. $myPost = array();
  22. foreach ($raw_post_array as $keyval) {
  23. $keyval = explode ('=', $keyval);
  24. if (count($keyval) == 2)
  25. $myPost[$keyval[0]] = urldecode($keyval[1]);
  26. }
  27. // read the post from PayPal system and add 'cmd'
  28. $req = 'cmd=_notify-validate';
  29. if(function_exists('get_magic_quotes_gpc')) {
  30. $get_magic_quotes_exists = true;
  31. }
  32. foreach ($myPost as $key => $value) {
  33. if($get_magic_quotes_exists == true && get_magic_quotes_gpc() == 1) {
  34. $value = urlencode(stripslashes($value));
  35. } else {
  36. $value = urlencode($value);
  37. }
  38. $req .= "&$key=$value";
  39. }
  40.  
  41. error_log(date('[Y-m-d H:i e] '). "IPN fired: $req" . PHP_EOL, 3, LOG_FILE);
  42.  
  43. // Post IPN data back to PayPal to validate the IPN data is genuine
  44. // Without this step anyone can fake IPN data
  45.  
  46. if(USE_SANDBOX == true) {
  47. $paypal_url = "https://www.sandbox.paypal.com/cgi-bin/webscr";
  48. } else {
  49. $paypal_url = "https://www.paypal.com/cgi-bin/webscr";
  50. }
  51.  
  52. $ch = curl_init($paypal_url);
  53. if ($ch == FALSE) {
  54. //LOGS all FALSE IPNs
  55. error_log(date('[Y-m-d H:i e] '). "FALSE IPN: $req" . PHP_EOL, 3, LOG_FILE);
  56. return FALSE;
  57. }
  58.  
  59. curl_setopt($ch, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1);
  60. curl_setopt($ch, CURLOPT_POST, 1);
  61. curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
  62. curl_setopt($ch, CURLOPT_POSTFIELDS, $req);
  63. curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 1);
  64. curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);
  65. curl_setopt($ch, CURLOPT_FORBID_REUSE, 1);
  66.  
  67. if(DEBUG == true) {
  68. curl_setopt($ch, CURLOPT_HEADER, 1);
  69. curl_setopt($ch, CURLINFO_HEADER_OUT, 1);
  70. }
  71.  
  72. // CONFIG: Optional proxy configuration
  73. //curl_setopt($ch, CURLOPT_PROXY, $proxy);
  74. //curl_setopt($ch, CURLOPT_HTTPPROXYTUNNEL, 1);
  75.  
  76. // Set TCP timeout to 30 seconds
  77. curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 30);
  78. curl_setopt($ch, CURLOPT_HTTPHEADER, array('Connection: Close'));
  79.  
  80. // CONFIG: Please download 'cacert.pem' from "http://curl.haxx.se/docs/caextract.html" and set the directory path
  81. // of the certificate as shown below. Ensure the file is readable by the webserver.
  82. // This is mandatory for some environments.
  83.  
  84. //$cert = __DIR__ . "./cacert.pem";
  85. //curl_setopt($ch, CURLOPT_CAINFO, $cert);
  86.  
  87. $res = curl_exec($ch);
  88. if (curl_errno($ch) != 0) // cURL error
  89. {
  90. if(DEBUG == true) {
  91. error_log(date('[Y-m-d H:i e] '). "Can't connect to PayPal to validate IPN message: " . curl_error($ch) . PHP_EOL, 3, LOG_FILE);
  92. }
  93. curl_close($ch);
  94. exit;
  95.  
  96. } else {
  97. // Log the entire HTTP response if debug is switched on.
  98. if(DEBUG == true) {
  99. error_log(date('[Y-m-d H:i e] '). "HTTP request of validation request:". curl_getinfo($ch, CURLINFO_HEADER_OUT) ." for IPN payload: $req" . PHP_EOL, 3, LOG_FILE);
  100. error_log(date('[Y-m-d H:i e] '). "HTTP response of validation request: $res" . PHP_EOL, 3, LOG_FILE);
  101. }
  102. curl_close($ch);
  103. }
  104.  
  105. // Inspect IPN validation result and act accordingly
  106.  
  107. // Split response headers and payload, a better way for strcmp
  108. $tokens = explode("\r\n\r\n", trim($res));
  109. $res = trim(end($tokens));
  110.  
  111. if (strcmp ($res, "VERIFIED") == 0) {
  112. // check whether the payment_status is Completed
  113. // check that txn_id has not been previously processed
  114. // check that receiver_email is your PayPal email
  115. // check that payment_amount/payment_currency are correct
  116. // process payment and mark item as paid.
  117.  
  118. //check based on secure merchant id (receiver_id)
  119. //error_log(date('[Y-m-d H:i e] '). "receiver email ".$_POST['receiver_email']. PHP_EOL, 3, LOG_FILE);
  120.  
  121. // assign posted variables to local variables
  122. //$item_name = $_POST['item_name'];
  123. //$item_number = $_POST['item_number'];
  124. //$payment_status = $_POST['payment_status'];
  125. //$payment_amount = $_POST['mc_gross'];
  126. //$payment_currency = $_POST['mc_currency'];
  127. //$txn_id = $_POST['txn_id'];
  128. //$receiver_email = $_POST['receiver_email'];
  129. //$payer_email = $_POST['payer_email'];
  130. //$transaction_id = $_POST['txn_id'];
  131. //$payerid = $_POST['payer_id'];
  132. //$firstname = $_POST['first_name'];
  133. //$lastname = $_POST['last_name'];
  134. //$payeremail = $_POST['payer_email'];
  135.  
  136. $paymentstatus = $_POST['payment_status'];
  137. $mdate= date('Y-m-d h:i:s',strtotime($paymentdate));
  138.  
  139. $otherstuff = json_encode($_POST);
  140.  
  141. $path = $_SERVER['DOCUMENT_ROOT'] . "/scripts/lib/includes.php";
  142. require_once($path);
  143.  
  144. //this is a recurring_payment_profile txn
  145. if (strpos($_POST["txn_type"],'recurring_payment_profile') !== false) {
  146. $txn_id = $_POST["initial_payment_txn_id"];
  147. $mc_gross = $_POST['initial_payment_amount'];
  148. $payment_status = $_POST["initial_payment_status"];
  149. $paymentdate = "0000-00-00 00:00:00";
  150. $nextpaymentdate = $_POST['next_payment_date'];
  151. $thispaymentdate = date("F j, Y, g:i a", strtotime($nextpaymentdate));
  152.  
  153. $profileId = $_POST["recurring_payment_id"];
  154.  
  155. $path = $_SERVER['DOCUMENT_ROOT'] . "/scripts/lib/Lionite/Paypal.php";
  156. require_once($path);
  157. $paypal = new Lionite_Paypal();
  158. //Set sandbox mode
  159. if(USE_SANDBOX == true) {
  160. $paypal_sb = true;
  161. } else {
  162. $paypal_sb = false;
  163. }
  164. Lionite_Paypal::sandbox($paypal_sb);
  165. $details = $paypal -> getRecurringProfile($profileId);
  166.  
  167. // Details found
  168. if(is_array($details)) {
  169. $ship_fname = $details["name"];
  170. $ship_lname = "-";
  171. $ship_address1 = $details["shipping_street"];
  172. $ship_address2 = "";
  173. $ship_city = $details["shipping_city"];
  174. $ship_zip = $details["shipping_zip"];
  175. $ship_state = $details["shipping_state"];
  176. $ship_country = $details["shipping_country_name"];
  177. $ship_country_code = $details["shipping_country_code"];
  178. $ship_phone = '00000000';
  179. $ship_email = $_POST["payer_email"];
  180. $currency = $_POST["currency_code"];
  181. $amount = 1;
  182. //uses rp_invoice_id or profile_reference because recurring profiles have no other fields
  183. //$ip = $_POST["rp_invoice_id"];
  184.  
  185. //parse custom to get things like IP
  186. parse_str($_POST["rp_invoice_id"]);
  187. $ip = $ip;
  188. }
  189.  
  190. //this is a regular txn
  191. } else {
  192. $txn_id = $_POST["txn_id"];
  193. $payment_status = $_POST["payment_status"];
  194. $mc_gross = $_POST['mc_gross'];
  195. $paymentdate = $_POST['payment_date'];
  196. $product_name = isset($_POST['product_name'])?$_POST['product_name']:'';
  197. $nextpaymentdate = "0000-00-00 00:00:00";
  198. $thispaymentdate = date("F j, Y, g:i a", strtotime($paymentdate));
  199.  
  200. //parse custom to get things like IP
  201. parse_str($_POST["custom"]);
  202.  
  203. // Prepare variables (for fulfillment)
  204. $ship_fname = $_POST["address_name"];
  205. $ship_lname = "-";
  206. $ship_address1 = $_POST["address_street"];
  207. $ship_address2 = "";
  208. $ship_city = $_POST["address_city"];
  209. $ship_zip = $_POST["address_zip"];
  210. $ship_state = $_POST["address_state"];
  211. $ship_country = $_POST["address_country"];
  212. $ship_country_code = $_POST["address_country_code"];
  213. $ship_phone = '8888888';
  214. $ship_email = $_POST["payer_email"];
  215. $currency = $_POST["mc_currency"];
  216. $amount = 1;
  217. $ip = $ip;
  218.  
  219. }
  220.  
  221. $parent_txn_id = '';
  222.  
  223. if (isset($_POST['parent_txn_id'])){
  224. $parent_txn_id = $_POST['parent_txn_id'];
  225. }
  226.  
  227. $sql = "INSERT INTO ipns (
  228. parent_txn_id,
  229. txn_id,
  230. recurring_payment_id,
  231. txn_type,
  232. custom,
  233. payment_type,
  234. payment_date,
  235. next_payment_date,
  236. payment_status,
  237. profile_status,
  238. product_name,
  239. first_name,
  240. last_name,
  241. payer_email,
  242. payer_id,
  243. address_name,
  244. address_country,
  245. address_country_code,
  246. address_zip,
  247. address_state,
  248. address_city,
  249. address_street,
  250. business,
  251. receiver_email,
  252. receiver_id,
  253. residence_country,
  254. item_name1,
  255. item_number1,
  256. quantity,
  257. shipping,
  258. tax,
  259. mc_currency,
  260. mc_fee,
  261. mc_gross,
  262. mc_gross1,
  263. invoice,
  264. ip,
  265. ieverything_else)
  266. VALUES (
  267. '".trim($parent_txn_id)."',
  268. '".trim($txn_id)."',
  269. '".trim($_POST["recurring_payment_id"])."',
  270. '".trim($_POST["txn_type"])."',
  271. '".trim($_POST["custom"])."',
  272. '".trim($_POST["payment_type"])."',
  273. '".trim(date('Y-m-d H:i:s', strtotime($paymentdate)))."',
  274. '".trim(date('Y-m-d H:i:s', strtotime($nextpaymentdate)))."',
  275. '".trim($payment_status)."',
  276. '".trim($_POST["profile_status"])."',
  277. '".trim($_POST["product_name"])."',
  278. '".trim($_POST["first_name"])."',
  279. '".trim($_POST["last_name"])."',
  280. '".trim($_POST["payer_email"])."',
  281. '".trim($_POST["payer_id"])."',
  282. '".trim($ship_fname)."',
  283. '".trim($ship_country)."',
  284. '".trim($ship_country_code)."',
  285. '".trim($ship_zip)."',
  286. '".trim($ship_state)."',
  287. '".trim($ship_city)."',
  288. '".addslashes($ship_address1)."',
  289. '".trim($_POST["business"])."',
  290. '".trim($_POST["receiver_email"])."',
  291. '".trim($_POST["receiver_id"])."',
  292. '".trim($_POST["residence_country"])."',
  293. '".trim($_POST["item_name1"])."',
  294. '".trim($_POST["item_number1"])."',
  295. '".trim($_POST["quantity"])."',
  296. '".trim($_POST["shipping"])."',
  297. '".trim($_POST["tax"])."',
  298. '".trim($currency)."',
  299. '".trim($_POST["mc_fee"])."',
  300. '".trim($mc_gross)."',
  301. '".trim($_POST["mc_gross1"])."',
  302. '".trim($_POST["invoice"])."',
  303. '".trim($ip)."',
  304. '".addslashes(print_r($otherstuff,true))."')";
  305.  
  306. //debug sql
  307. //error_log(date('[Y-m-d H:i e] '). "SQL: " . $sql . PHP_EOL, 3, LOG_FILE);
  308.  
  309. $result = mysql_query($sql);
  310.  
  311. //only post shipment when payment is completed (for creation of recurring billing profile, or for recurring/instant payments)
  312. if ( trim($payment_status)=="Completed" ) {
  313. $path = $_SERVER['DOCUMENT_ROOT'] . "/scripts/lib/ATF/ATF.php";
  314. require_once($path);
  315. // Create the client instance
  316. $atf = new atf();
  317. $date = date("m/d/Y"); //'02/22/2012'
  318. $time = date("h:ia"); //'02:01am'
  319. $orderID = $txn_id;
  320. $total = $mc_gross;
  321.  
  322. //gets the pname depending on the transaction
  323. if ($_POST["item_name1"]!="") {
  324. //this is for all instant payments
  325. $pname = $_POST["item_name1"];
  326. } else if ($_POST["product_name"]!="") {
  327. //this is likely for recurring profile CREATED
  328. $pname = $_POST["product_name"];
  329. } else if ($details["desc"]!="") {
  330. //this grabs desc from the recurring profile
  331. $pname = $details["desc"];
  332. }
  333.  
  334. //from the pname, extract the sku
  335. preg_match("/\(([^\)]*)\)/", $pname, $aMatches);
  336. $psku = $aMatches[1];
  337.  
  338. error_log(date('[Y-m-d H:i e] '). "ATF vars: ". $orderID."|".
  339. $date."|".
  340. $time."|".
  341. $total."|".
  342. $ship_fname."|".
  343. $ship_lname."|".
  344. $ship_address1."|".
  345. $ship_address2."|".
  346. $ship_city."|".
  347. $ship_zip."|".
  348. $ship_state."|".
  349. $ship_country."|".
  350. $ship_phone."|".
  351. $ship_email."|".
  352. $psku."|".
  353. $amount."|".
  354. $ip. PHP_EOL, 3, LOG_FILE_ATF);
  355.  
  356. // Sets city, state, zip to the country if they are unset
  357. if ($ship_city =="") { $ship_city = $ship_country; }
  358. if ($ship_zip =="") { $ship_zip = $ship_country; }
  359. if ($ship_state =="") { $ship_state = $ship_country; }
  360.  
  361. // Post shipment
  362. $callresult = $atf->postShipment(
  363. cleanText($orderID),
  364. cleanText($date),
  365. cleanText($time),
  366. cleanText($total),
  367. cleanText($ship_fname),
  368. cleanText($ship_lname),
  369. cleanText($ship_address1),
  370. cleanText($ship_address2),
  371. cleanText($ship_city),
  372. cleanText($ship_zip),
  373. cleanText($ship_state),
  374. cleanText($ship_country),
  375. cleanText($ship_phone),
  376. cleanText($ship_email),
  377. cleanText($psku),
  378. cleanText($amount),
  379. cleanText($ip)
  380. );
  381.  
  382. error_log(date('[Y-m-d H:i e] '). "ATF call: ". print_r($callresult,true). PHP_EOL, 3, LOG_FILE_ATF);
  383.  
  384.  
  385. /*******************************************
  386. Process ad tracking pixels
  387. ********************************************/
  388.  
  389. //do this for monthly recurring payments
  390. if ($psku==$SKU_NUTRI1Monthly) {
  391. $adURL = "http://www.nutrifrontier.net/track/a.php?type=sale&value=129.95&id=10&name=Nutrio2+Re-engage+6+bottles&description=";
  392. } else {
  393. $adURL = "";
  394. }
  395.  
  396. if ($adURL!="") {
  397. doCURL($adURL);
  398. }
  399.  
  400. /*******************************************
  401. Emails the customer
  402. ********************************************/
  403.  
  404.  
  405. $path = $_SERVER['DOCUMENT_ROOT'] . "/scripts/lib/PHPMailer/PHPMailerAutoload.php";
  406. require_once($path);
  407.  
  408. //this includes the email body
  409. $path = $_SERVER['DOCUMENT_ROOT'] . "/scripts/lib/include-email.php";
  410. require_once($path);
  411.  
  412. $mail = new PHPMailer;
  413. //$mail->SMTPDebug = 3; // Enable verbose debug output
  414. $mail->isSMTP(); // Set mailer to use SMTP
  415. $mail->Host = 'host.successvantage.com'; // Specify main and backup SMTP servers
  416. $mail->SMTPAuth = true; // Enable SMTP authentication
  417. $mail->Username = 'noreply@realhealthsciences.com'; // SMTP username
  418. $mail->Password = ',5iXeF.9J,4u'; // SMTP password
  419. $mail->SMTPSecure = 'ssl'; // Enable TLS encryption, `ssl` also accepted
  420. $mail->Port = 465; // TCP port to connect to
  421.  
  422. $mail->From = 'noreply@realhealthsciences.com';
  423. $mail->FromName = 'Real Health Sciences';
  424. //$mail->addAddress('joe@example.net', 'Joe User'); // Add a recipient
  425. $mail->addAddress($_POST["payer_email"]); // Name is optional
  426. //$mail->addReplyTo('info@example.com', 'Information');
  427. //$mail->addCC('cc@example.com');
  428. $mail->addBCC('mentismarketing.support@gmail.com');
  429. //***************
  430. $mail->isHTML(true); // Set email format to HTML
  431.  
  432. $mail->Subject = 'Renew Order '.$txn_id;
  433. $mail->Body = getEmail( $txn_id,
  434. $thispaymentdate,
  435. $_POST["first_name"],
  436. $_POST["last_name"],
  437. $ship_fname,
  438. $ship_address1,
  439. $ship_city,
  440. $ship_state,
  441. $ship_zip,
  442. $ship_country,
  443. $psku,
  444. $pname,
  445. $mc_gross,
  446. $currency );
  447. //$mail->AltBody = 'This is the body in plain text for non-HTML mail clients';
  448.  
  449. /********************
  450. * hasoffers postback
  451. ********************/
  452.  
  453. if( isset($hasoffers_cookie) ){
  454. $hasOffersURL = "http://tracking.gomagnesium-at.com/aff_goal?a=lsr";
  455.  
  456. //Add goal id is there is one
  457. isset($hasoffers_goal) ? $hasOffersURL .= "&goal_id=".$hasoffers_goal : '';
  458.  
  459. //Add transaction ID
  460. $hasOffersURL .= "&transaction_id=".$hasoffers_cookie;
  461.  
  462. //Add Advertiser Sub IDs
  463. $hasOffersURL .= "";
  464.  
  465. $hasOffersURL .= (isset($aff_sub1) && $aff_sub1 != '')?"&adv_sub=".$aff_sub1:'';
  466. $hasOffersURL .= (isset($aff_sub2) && $aff_sub2 != '')?"&adv_sub2=".$aff_sub2:'';
  467. $hasOffersURL .= (isset($aff_sub3) && $aff_sub3 != '')?"&adv_sub3=".$aff_sub3:'';
  468. $hasOffersURL .= (isset($aff_sub4) && $aff_sub4 != '')?"&adv_sub4=".$aff_sub4:'';
  469. $hasOffersURL .= (isset($aff_sub5) && $aff_sub5 != '')?"&adv_sub5=".$aff_sub5:'';
  470.  
  471. $hasoffers_result = doCURL($hasOffersURL);
  472.  
  473. $ho_fh = fopen("holog.txt","a");
  474. fwrite($ho_fh, $hasoffers_result.' '.$hasOffersURL.' '.$_POST["custom"]);
  475. fclose($ho_fh);
  476.  
  477. if(strpos( $hasoffers_result, 'success=true;') === false ){
  478. error_log(date('[Y-m-d H:i e] '). "HasOffers postback failed for txn: $hasoffers_cookie\nData:$hasoffers_result\n\n". PHP_EOL, 3, LOG_FILE_ERRORS);
  479. }
  480. }else{
  481. preg_match("/\((.*)\)/",$product_name,$matches);
  482. $conversionSKU = $matches[1];
  483.  
  484. $sub_id = (isset($aff_sub1) && $aff_sub1 != '')?$aff_sub1:'';
  485. $sub_id2 = (isset($aff_sub2) && $aff_sub2 != '')?$aff_sub2:'';
  486. $sub_id3 = (isset($aff_sub3) && $aff_sub3 != '')?$aff_sub3:'';
  487. $sub_id4 = (isset($aff_sub4) && $aff_sub4 != '')?$aff_sub4:'';
  488. $sub_id5 = (isset($aff_sub5) && $aff_sub5 != '')?$aff_sub5:'';
  489.  
  490. $args = array(
  491. 'NetworkId' => 'hvaffiliates',
  492. 'Target' => 'Conversion',
  493. 'Method' => 'create',
  494. 'NetworkToken' => 'NETj0R7lVEL8BJ35JdY5lv5jtZM89M',
  495. 'data' => array(
  496. 'ip' => $ip,
  497. 'offer_id' => '29',
  498. 'status' => 'approved',
  499. 'revenue' => $_POST['mc_gross'],
  500. 'goal_id' => $hasoffers_goal,
  501. 'payout' => $_POST['mc_gross'],
  502. 'affiliate_info1' => $sub_id,
  503. 'affiliate_info2' => $sub_id2,
  504. 'affiliate_info3' => $sub_id3,
  505. 'affiliate_info4' => $sub_id4,
  506. 'affiliate_info5' => $sub_id5,
  507. 'affiliate_id' => '1'
  508. ),
  509. 'return_object' => '1'
  510. );
  511.  
  512. // Initialize cURL
  513. $curlHandle = curl_init();
  514.  
  515. // Configure cURL request
  516. curl_setopt($curlHandle, CURLOPT_URL, "https://api.hasoffers.com/Apiv3/json");
  517.  
  518. // Configure POST
  519. curl_setopt($curlHandle, CURLOPT_POST, 1);
  520. curl_setopt($curlHandle, CURLOPT_POSTFIELDS, http_build_query($args));
  521.  
  522. // Make sure we can access the response when we execute the call
  523. curl_setopt($curlHandle, CURLOPT_RETURNTRANSFER, true);
  524.  
  525. // Execute the API call
  526. $jsonEncodedApiResponse = curl_exec($curlHandle);
  527.  
  528. // Ensure HTTP call was successful
  529. if($jsonEncodedApiResponse === false) {
  530. $ho_fh = fopen("holog.txt","a");
  531. fwrite($ho_fh, $jsonEncodedApiResponse."WOOT\n");
  532. fclose($ho_fh);
  533. }
  534. else{
  535. // Decode the response from a JSON string to a PHP associative array
  536. $apiResponse = json_decode($jsonEncodedApiResponse, true);
  537.  
  538. // Make sure we got back a well-formed JSON string and that there were no
  539. // errors when decoding it
  540. $jsonErrorCode = json_last_error();
  541. if($jsonErrorCode !== JSON_ERROR_NONE) {
  542. $ho_fh = fopen("holog.txt","a");
  543. fwrite($ho_fh, $jsonErrorCode);
  544. fclose($ho_fh);
  545. }
  546.  
  547. // Print out the response details
  548. if($apiResponse['response']['status'] === 1) {
  549. // No errors encountered
  550. file_put_contents('hosuccess.txt', print_r($apiResponse['response']['data'], true));
  551. }
  552. else {
  553. file_put_contents('hoerrors.txt', print_r($apiResponse['response']['errors'], true));
  554. }
  555.  
  556. $query = "UPDATE ipns SET hasOffersId='".$apiResponse['response']['data']['Conversion']['id']."' WHERE txn_id='".trim($txn_id)."'";
  557. }
  558. // Clean up the resource now that we're done with cURL
  559. curl_close($curlHandle);
  560. }
  561.  
  562. if(!$mail->send()) {
  563. echo 'Message could not be sent.';
  564. error_log(date('[Y-m-d H:i e] '). "Mailer Error: " . $mail->ErrorInfo . PHP_EOL, 3, LOG_FILE_ERRORS);
  565. } else {
  566. echo 'Message has been sent';
  567. }
  568. }
  569. else if(trim($payment_status)=="Refunded"){
  570. $ho_fh = fopen("holog.txt","a");
  571. fwrite($ho_fh, $raw_post_data." ".$hasoffers_cookie);
  572. fclose($ho_fh);
  573.  
  574. if(isset($hasoffers_cookie)){
  575. $args = array(
  576. 'NetworkId' => 'hvaffiliates',
  577. 'Target' => 'Conversion',
  578. 'Method' => 'update',
  579. 'NetworkToken' => 'NETj0R7lVEL8BJ35JdY5lv5jtZM89M',
  580. 'data' => array(
  581. 'revenue' => '0.00'
  582. ),
  583. 'transaction_id' => $hasoffers_cookie
  584. );
  585. }else{
  586. $query = "SELECT hasOffersId FROM ipns WHERE txn_id='".trim($txn_id)."' ORDER BY id ASC LIMIT 1";
  587. $result = mysql_query($query);
  588.  
  589. if($result){
  590. $row = mysql_fetch_assoc($result);
  591. $conversionId = $row["hasOffersId"];
  592. }else{
  593. error_log(date('[Y-m-d H:i e] '). "MySQL Refund Error: " . trim($txn_id) . PHP_EOL, 3, LOG_FILE_ERRORS);
  594. }
  595.  
  596. $args = array(
  597. 'NetworkId' => 'hvaffiliates',
  598. 'Target' => 'Conversion',
  599. 'Method' => 'update',
  600. 'NetworkToken' => 'NETj0R7lVEL8BJ35JdY5lv5jtZM89M',
  601. 'id' => $conversionId,
  602. 'data' => array(
  603. 'status' => 'rejected'
  604. )
  605. );
  606. }
  607.  
  608. // Initialize cURL
  609. $curlHandle = curl_init();
  610.  
  611. // Configure cURL request
  612. curl_setopt($curlHandle, CURLOPT_URL, "https://api.hasoffers.com/Apiv3/json");
  613.  
  614. // Configure POST
  615. curl_setopt($curlHandle, CURLOPT_POST, 1);
  616. curl_setopt($curlHandle, CURLOPT_POSTFIELDS, http_build_query($args));
  617.  
  618. // Make sure we can access the response when we execute the call
  619. curl_setopt($curlHandle, CURLOPT_RETURNTRANSFER, true);
  620.  
  621. // Execute the API call
  622. $jsonEncodedApiResponse = curl_exec($curlHandle);
  623.  
  624. // Ensure HTTP call was successful
  625. if($jsonEncodedApiResponse === false) {
  626. $ho_fh = fopen("holog.txt","a");
  627. fwrite($ho_fh, $jsonEncodedApiResponse."WOOT");
  628. fclose($ho_fh);
  629. }
  630.  
  631. // Clean up the resource now that we're done with cURL
  632. curl_close($curlHandle);
  633.  
  634. // Decode the response from a JSON string to a PHP associative array
  635. $apiResponse = json_decode($jsonEncodedApiResponse, true);
  636.  
  637. // Make sure we got back a well-formed JSON string and that there were no
  638. // errors when decoding it
  639. $jsonErrorCode = json_last_error();
  640. if($jsonErrorCode !== JSON_ERROR_NONE) {
  641. $ho_fh = fopen("holog.txt","a");
  642. fwrite($ho_fh, $jsonErrorCode);
  643. fclose($ho_fh);
  644. }
  645.  
  646. // Print out the response details
  647. if($apiResponse['response']['status'] === 1) {
  648. // No errors encountered
  649. file_put_contents('hosuccess.txt', print_r($apiResponse['response']['data'], true));
  650. }
  651. else {
  652. file_put_contents('hoerrors.txt', print_r($apiResponse['response']['errors'], true));
  653. }
  654. }
  655.  
  656. if(DEBUG == true) {
  657. error_log(date('[Y-m-d H:i e] '). "Verified IPN: $req ". PHP_EOL, 3, LOG_FILE);
  658. }
  659. } else if (strcmp ($res, "INVALID") == 0) {
  660. // log for manual investigation
  661. // Add business logic here which deals with invalid IPN messages
  662. if(DEBUG == true) {
  663. error_log(date('[Y-m-d H:i e] '). "Invalid IPN: $req" . PHP_EOL, 3, LOG_FILE);
  664. }
  665. }
  666.  
  667. //save a copy of IPN into tracker DB
  668. require_once('ipn-track.php');
  669.  
  670. function doCURL($url) {
  671.  
  672. $ch = curl_init();
  673. curl_setopt($ch, CURLOPT_URL, $url);
  674.  
  675. //return the transfer as a string
  676. curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
  677.  
  678. // $output contains the output string
  679. $output = curl_exec($ch);
  680. curl_close($ch);
  681. return $output;
  682. }
  683.  
  684. function cleanText($text) {
  685.  
  686. // Remove all none utf-8 symbols
  687. $text = htmlspecialchars_decode(htmlspecialchars($text, ENT_IGNORE, 'UTF-8'));
  688. // remove non-breaking spaces and other non-standart spaces
  689. $text = preg_replace('~\s+~u', ' ', $text);
  690. // replace controls symbols with "?"
  691. $text = preg_replace('~\p{C}+~u', '?', $text);
  692.  
  693. return $text;
  694.  
  695. }
  696.  
  697.  
  698. /********
  699.  
  700. Example of Paypal Profile
  701.  
  702.  
  703. Recurring profile details
  704.  
  705. array(50) {
  706. ["ACK"]=>
  707. string(7) "Success"
  708. ["VERSION"]=>
  709. string(4) "82.0"
  710. ["BUILD"]=>
  711. string(8) "17098556"
  712. ["profile_id"]=>
  713. string(14) "I-HY9V9MY0PE4W"
  714. ["status"]=>
  715. string(6) "Active"
  716. ["autobill"]=>
  717. string(10) "NoAutoBill"
  718. ["desc"]=>
  719. string(89) "Time magazine monthly subscription for 1 year. 1 month free trial, then 29.99 GBP monthly"
  720. ["max_failed"]=>
  721. string(1) "0"
  722. ["name"]=>
  723. string(10) "buyer test"
  724. ["start_date"]=>
  725. string(20) "2015-06-30T16:00:00Z"
  726. ["next_billing_date"]=>
  727. string(20) "2015-07-01T10:00:00Z"
  728. ["num_cycles_completed"]=>
  729. string(1) "0"
  730. ["num_cycles_remaining"]=>
  731. string(1) "1"
  732. ["outstanding_balance"]=>
  733. string(4) "0.00"
  734. ["failed_payments"]=>
  735. string(1) "0"
  736. ["trial_amount_paid"]=>
  737. string(4) "0.00"
  738. ["regular_amount_paid"]=>
  739. string(4) "0.00"
  740. ["aggregate_amount"]=>
  741. string(4) "0.00"
  742. ["aggregate_optional_amount"]=>
  743. string(4) "0.00"
  744. ["final_payment_date"]=>
  745. string(20) "2016-07-01T10:00:00Z"
  746. ["timestamp"]=>
  747. string(20) "2015-06-28T07:00:50Z"
  748. ["correlation_id"]=>
  749. string(13) "a1fa47056c5c7"
  750. ["shipping_street"]=>
  751. string(16) "123 Thomson Rd. "
  752. ["shipping_city"]=>
  753. string(9) "Singapore"
  754. ["shipping_zip"]=>
  755. string(6) "308123"
  756. ["shipping_country_code"]=>
  757. string(2) "SG"
  758. ["shipping_country"]=>
  759. string(2) "SG"
  760. ["shipping_country_name"]=>
  761. string(9) "Singapore"
  762. ["shipping_address_owner"]=>
  763. string(6) "PayPal"
  764. ["shipping_address_status"]=>
  765. string(11) "Unconfirmed"
  766. ["period"]=>
  767. string(5) "Month"
  768. ["frequency"]=>
  769. string(1) "1"
  770. ["total_cycles"]=>
  771. string(1) "1"
  772. ["currency"]=>
  773. string(3) "GBP"
  774. ["cost"]=>
  775. string(5) "29.99"
  776. ["shipping"]=>
  777. string(4) "0.00"
  778. ["tax"]=>
  779. string(4) "0.00"
  780. ["trial_period"]=>
  781. string(5) "Month"
  782. ["trial_frequency"]=>
  783. string(1) "1"
  784. ["trial_total_cycles"]=>
  785. string(1) "1"
  786. ["trial_currency_code"]=>
  787. string(3) "GBP"
  788. ["trial_cost"]=>
  789. string(4) "0.00"
  790. ["trial_shipping_amount"]=>
  791. string(4) "0.00"
  792. ["trial_tax_amount"]=>
  793. string(4) "0.00"
  794. ["regular_billing_period"]=>
  795. string(5) "Month"
  796. ["regular_billing_frequency"]=>
  797. string(1) "1"
  798. ["regular_total_billing_cycles"]=>
  799. string(2) "12"
  800. ["regular_currency_code"]=>
  801. string(3) "GBP"
  802. ["regular_shipping_amount"]=>
  803. string(4) "0.00"
  804. ["regular_tax_amount"]=>
  805. string(4) "0.00"
  806. }
  807.  
  808.  
  809.  
  810.  
  811. Recurring profile created::::
  812.  
  813. {"payment_cycle":"Daily","txn_type":"recurring_payment_profile_created","last_name":"buyer","initial_payment_status":"Completed","next_payment_date":"03:00:00 Jul 01, 2015 PDT","residence_country":"SG","initial_payment_amount":"1.00","rp_invoice_id":"103.245.95.50","currency_code":"USD","time_created":"00:24:47 Jul 01, 2015 PDT","verify_sign":"AN9zikv75AwD7FSABy-2H9RV1ETNAKBIFCX-19lgfr5pRs7dp0BR3jNQ","period_type":" Regular","payer_status":"verified","test_ipn":"1","tax":"0.00","payer_email":"paypal-buyer@brainmaxima.com","first_name":"test","receiver_email":"paypal-facilitator@brainmaxima.com","payer_id":"GPACWYCF3836U","product_type":"1","initial_payment_txn_id":"2HW30276WH825815R","shipping":"0.00","amount_per_cycle":"9.99","profile_status":"Active","charset":"gb2312","notify_version":"3.8","amount":"9.99","outstanding_balance":"0.00","recurring_payment_id":"I-KA4L0YUC1H9T","product_name":"Time magazine monthly subscription for 1 year. 1 month free trial, then 29.99 USD daily","ipn_track_id":"4b27a7e4c1e9"}
  814.  
  815.  
  816. Recurring payment::::
  817.  
  818. {"mc_gross":"9.99","period_type":" Regular","outstanding_balance":"0.00","next_payment_date":"03:00:00 Jun 29, 2015 PDT","protection_eligibility":"Eligible","payment_cycle":"Daily","address_status":"unconfirmed","tax":"0.00","payer_id":"GPACWYCF3836U","address_street":"123 Thomson Rd.","payment_date":"03:41:09 Jun 28, 2015 PDT","payment_status":"Completed","product_name":"Time magazine monthly subscription for 1 year. 1 month free trial, then 29.99 USD daily","charset":"gb2312","rp_invoice_id":"132.147.72.52","recurring_payment_id":"I-4EB8UFKB2LL5","address_zip":"308123","first_name":"test","mc_fee":"0.64","address_country_code":"SG","address_name":"buyer test","notify_version":"3.8","amount_per_cycle":"9.99","payer_status":"verified","currency_code":"USD","business":"paypal-facilitator@brainmaxima.com","address_country":"Singapore","address_city":"Singapore","verify_sign":"Agfb8DnF8gs6j4EwIwFPjQ7Rt9a.At5RBxymPJ.fwSjS0mt91UNJdiL1","payer_email":"paypal-buyer@brainmaxima.com","initial_payment_amount":"1.00","profile_status":"Active","amount":"9.99","txn_id":"71S220809S1846841","payment_type":"instant","last_name":"buyer","address_state":"","receiver_email":"paypal-facilitator@brainmaxima.com","payment_fee":"0.64","receiver_id":"FZBJUFBDMSBZJ","txn_type":"recurring_payment","mc_currency":"USD","residence_country":"SG","test_ipn":"1","transaction_subject":"Time magazine monthly subscription for 1 year. 1 month free trial, then 29.99 USD daily","payment_gross":"9.99","shipping":"0.00","product_type":"1","time_created":"00:32:46 Jun 28, 2015 PDT","ipn_track_id":"88e6336ee79"}
  819.  
  820.  
  821. One time payment::::
  822.  
  823. {"mc_gross":"69.97","protection_eligibility":"Eligible","address_status":"unconfirmed","item_number1":"1984","payer_id":"GPACWYCF3836U","tax":"0.00","address_street":"123 Thomson Rd.","payment_date":"08:56:44 Jun 24, 2015 PDT","payment_status":"Completed","charset":"gb2312","address_zip":"308123","mc_shipping":"0.00","mc_handling":"0.00","first_name":"test","mc_fee":"2.68","address_country_code":"SG","address_name":"buyer test","notify_version":"3.8","custom":"5","payer_status":"verified","address_country":"Singapore","num_cart_items":"1","mc_handling1":"0.00","address_city":"Singapore","verify_sign":"AMbszvxvYSF5dhC2-PBwiJRHzT8yALLUM2kWqwI-m6msJ0OyQ2NlvySO","payer_email":"paypal-buyer@brainmaxima.com","mc_shipping1":"0.00","tax1":"0.00","txn_id":"3G580325DH949014M","payment_type":"instant","last_name":"buyer","address_state":"","item_name1":"Product ABC","receiver_email":"paypal-facilitator@brainmaxima.com","payment_fee":"2.68","quantity1":"1","receiver_id":"FZBJUFBDMSBZJ","txn_type":"cart","mc_gross_1":"69.97","mc_currency":"USD","residence_country":"SG","test_ipn":"1","transaction_subject":"","payment_gross":"69.97","ipn_track_id":"20bae702572a5"}
  824.  
  825.  
  826. ********/
  827.  
  828. ?>
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement