[x]
Posted via EE Mobile

Search, ask, and monitor your questions on the go with EE Mobile. Visit Experts Exchange from your mobile device and never be out of touch again.

08/04/2009 at 09:09PM PDT, ID: 24626968
[x]
Attachment Details
[x]
The Solution Rating System

With so many solutions, how can you tell which solutions are most likely to help you and which ones are not? To provide you with a tool to use, we rate our solutions based on various elements that most accurately determine if a solution is a quality solution. To explain what factors affect the solution rating, here are the elements we take into consideration when formulating our solution rating.

  • The Grade of the Solution
  • The Zone Rank of the Expert Providing the Solution
  • The Number of Author and Expert Comments
  • The Number of Experts Contributing
  • The Feedback of the Community

Your Input Matters
Because of the way the system is set up, the most important variable in this equation is you. As a member of Experts Exchange, you are able to cast your vote on the quality of the solutions in regard to how complete, accurate, helpful and easy to understand each solution is. When you provide your feedback, each rating is adjusted accordingly. So, if you see a solution that has a poor rating that you think is a good solution, let us know by rating it. As you do, the rating will be adjusted and will become more accurate for other members of our site.

If you have any suggestions that you would like to make for our rating system, please ask a question in the Suggestions Zone of Community Support.

Thank you!

9.2

Help with small paypal IPN problem

Asked by elvin66 in Payment Processing Recommendation and Integrating, Internet Marketing, PHP Scripting Language

Tags: paypal ipn, php, ipn script, website payments

I have setup a standard PayPal IPN script for online buynow payments. All is working fine except in my button code I have a text field that my buynow page inserts a username for.  The first paragraph in the code snippet is the paypal button code (modified foir this post). The section section is my complete ipn script.

You will see the text field in that button.  In my IPN script, I have added a variable $username = $_POST['Username'];
When my IPN script goes to update my database I use the $username variable to do so, but $username is "" or at least the actual users account is not being updated. If I manually insert the actual username into the query it works.

I also tried $username = $_POST['os1']; as os1 is the [name] of the text input field in the button. This also returns no result. I could fix it very easily if I knew which post data paypal is sending for the username. I know it is received as the resulting emails I get after a purchase include it like:  Username: Wally  or whatever the name is.

Does anyone know how to find the correct variable to use for $username?  I originally tried $_session->username as all users must be logged in before doing anything on the site. That did not give me a result either.  I figure that doesn't work as paypal is contacting the ipn script directly so it does not know who the session user is (I imagine that is correct but not sure).

Once this is fixed I can relax!  Thanks in advance
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:
15:
16:
17:
18:
19:
20:
21:
22:
23:
24:
25:
26:
27:
28:
29:
30:
31:
32:
33:
34:
35:
36:
37:
38:
39:
40:
41:
42:
43:
44:
45:
46:
47:
48:
49:
50:
51:
52:
53:
54:
55:
56:
57:
58:
59:
60:
61:
62:
63:
64:
65:
66:
67:
68:
69:
70:
71:
72:
73:
74:
75:
76:
77:
78:
79:
80:
81:
82:
83:
84:
85:
86:
87:
88:
89:
90:
91:
92:
93:
94:
95:
96:
97:
98:
99:
100:
101:
102:
103:
104:
105:
106:
107:
108:
109:
110:
111:
112:
113:
114:
115:
116:
117:
118:
119:
120:
121:
122:
123:
124:
125:
126:
127:
128:
129:
130:
131:
132:
133:
134:
135:
136:
137:
138:
139:
140:
141:
142:
143:
144:
145:
146:
147:
148:
149:
150:
151:
152:
153:
154:
155:
156:
157:
158:
159:
160:
161:
162:
163:
164:
165:
166:
167:
168:
169:
170:
171:
172:
173:
174:
175:
176:
177:
178:
179:
180:
181:
182:
183:
184:
185:
186:
187:
188:
189:
190:
191:
192:
193:
194:
195:
196:
197:
198:
199:
200:
201:
202:
203:
204:
205:
206:
207:
208:
209:
210:
211:
212:
213:
214:
215:
216:
217:
218:
219:
220:
221:
222:
223:
224:
225:
226:
227:
228:
229:
230:
231:
232:
233:
234:
235:
236:
237:
238:
239:
240:
241:
242:
243:
244:
245:
246:
247:
248:
249:
250:
251:
252:
253:
254:
255:
256:
257:
258:
259:
260:
261:
262:
263:
264:
265:
266:
267:
268:
269:
270:
271:
272:
273:
274:
275:
276:
277:
278:
279:
280:
281:
282:
283:
284:
285:
286:
287:
288:
289:
290:
291:
292:
293:
294:
295:
296:
297:
298:
299:
300:
301:
302:
303:
304:
305:
306:
307:
308:
309:
310:
311:
312:
313:
314:
315:
316:
317:
318:
319:
320:
321:
322:
323:
324:
325:
326:
327:
328:
329:
330:
331:
332:
333:
334:
335:
336:
337:
338:
339:
340:
341:
342:
343:
344:
345:
346:
347:
348:
349:
350:
351:
352:
353:
354:
355:
356:
357:
358:
359:
360:
361:
362:
363:
364:
365:
366:
367:
368:
369:
370:
371:
372:
373:
374:
375:
376:
377:
378:
379:
380:
381:
382:
383:
384:
385:
386:
387:
388:
389:
390:
391:
392:
393:
394:
395:
396:
397:
398:
399:
400:
401:
402:
403:
404:
405:
406:
407:
408:
409:
410:
411:
412:
413:
414:
415:
416:
417:
418:
419:
420:
421:
422:
423:
424:
425:
426:
427:
428:
429:
430:
431:
432:
433:
434:
435:
436:
437:
438:
439:
440:
441:
442:
443:
444:
445:
446:
447:
448:
449:
450:
451:
452:
453:
454:
455:
456:
457:
458:
459:
460:
461:
462:
463:
464:
465:
466:
467:
468:
469:
470:
471:
472:
473:
474:
475:
476:
477:
478:
479:
480:
481:
482:
483:
484:
485:
486:
487:
488:
489:
490:
491:
492:
493:
494:
495:
496:
497:
498:
499:
500:
501:
502:
503:
504:
505:
506:
507:
508:
509:
510:
511:
512:
513:
514:
515:
516:
517:
518:
519:
520:
521:
522:
523:
524:
525:
526:
527:
528:
529:
530:
531:
532:
533:
534:
535:
536:
537:
538:
539:
540:
541:
542:
543:
544:
545:
546:
547:
548:
549:
550:
551:
552:
553:
554:
555:
556:
557:
558:
559:
560:
561:
562:
563:
564:
565:
566:
567:
568:
569:
570:
571:
572:
573:
574:
575:
576:
577:
578:
579:
580:
581:
582:
583:
584:
585:
586:
587:
588:
589:
590:
591:
592:
593:
594:
595:
596:
597:
598:
599:
600:
601:
602:
603:
604:
605:
606:
607:
608:
609:
610:
611:
612:
613:
614:
615:
616:
617:
618:
619:
620:
621:
622:
623:
624:
625:
626:
627:
628:
629:
630:
631:
632:
633:
634:
635:
636:
637:
638:
639:
640:
641:
642:
643:
644:
645:
646:
647:
648:
649:
650:
651:
652:
653:
654:
655:
656:
657:
658:
659:
660:
661:
662:
663:
664:
665:
666:
667:
668:
669:
670:
671:
672:
673:
674:
675:
676:
677:
678:
679:
680:
<form action="https://www.paypal.com/cgi-bin/webscr" method="post">
<input type="hidden" name="cmd" value="_s-xclick">
<input type="hidden" name="hosted_button_id" value="xxxxxx"> // changed for this email
<table>
<tr><td><input type="hidden" name="on0" value="Select Token Qty below">Select Token Qty below</td></tr><tr><td><select name="os0">
 <option value="1">1 $0.01   // set to 1 penny for testing
 <option value="2">2 $0.02
 <option value="3">3 $0.03
 <option value="4">4 $0.04
 <option value="5">5 $0.05
 <option value="1000">1000 $500.00
</select> </td></tr>
<tr><td><input type="hidden" name="on1" value="Username">Username</td></tr><tr><td><input type="text" name="os1" maxlength="60" value="<?php echo $session->username; ?>"></td></tr>
</table>
<input type="hidden" name="currency_code" value="NZD"><br /><br />
<input type="image" src="https://www.paypal.com/en_US/i/btn/btn_buynowCC_LG.gif" border="0" name="submit" alt="PayPal - The safer, easier way to pay online!">
<img alt="" border="0" src="https://www.paypal.com/en_US/i/scr/pixel.gif" width="1" height="1">
</form>
 
// Second code snippet starts here
 
// My IPN script I paid $10 for lol. Oh well I guess it's a fairly standard one
All the email functions work great it's just the $username. I tried messing around with capitalisation on the posted value but no good.
 
<?php
/***************************************************************************
 *                              ipn_process.php
 *                            --------------------
 *   begin                : Monday, Jan 30, 2006
 *   copyright            : (C) 2006 MaxProgramming, LLC
 *   email                : support@maxprog.com
 *
 ***************************************************************************/
include("../include/session.php");
 
//--PAYPAL SCRIPT---------------------------------------------------------------
 
// read the post from PayPal system and add 'cmd'
$req = 'cmd=_notify-validate';
 
foreach ($_POST as $key => $value) {
	$value = urlencode(stripslashes($value));
	$req .= "&$key=$value";
}
 
// post back to PayPal system to validate
$header .= "POST /cgi-bin/webscr HTTP/1.0\r\n";
$header .= "Content-Type: application/x-www-form-urlencoded\r\n";
$header .= "Content-Length: " . strlen($req) . "\r\n\r\n";
$fp = fsockopen ('www.paypal.com', 80, $errno, $errstr, 30);             // <- Use this line for real use
//$fp = fsockopen ('www.sandbox.paypal.com', 80, $errno, $errstr, 30);   // <- Use this line when testing in SandBox
 
// assign posted variables to local variables
$item_name            = $_POST['item_name'];
$item_number          = $_POST['item_number'];
$quantity             = $_POST['quantity'];
$payment_amount       = $_POST['mc_gross'];
$fee                  = $_POST['mc_fee'];
$settle_amount        = $_POST['settle_amount'];                  // mc_gross - mc_fee
$settle_currency      = $_POST['settle_currency'];
$tax                  = $_POST['tax'];
$payment_currency     = $_POST['mc_currency'];
$exchange_rate        = $_POST['exchange_rate'];
$payment_status       = $_POST['payment_status'];
$payment_type         = $_POST['payment_type'];
$payment_date         = $_POST['payment_date'];
$txn_id               = $_POST['txn_id'];
$txn_type             = $_POST['txn_type']; // 'cart', 'send_money' or 'web_accept' (manual page 46)
$custom               = $_POST['custom'];   // Any custom data
$receiver_email       = $_POST['receiver_email'];
$first_name           = $_POST['first_name'];
$last_name            = $_POST['last_name'];
$username             = $_POST['Username'];  // Sent to paypal from the payments page on my site
$payer_business_name  = $_POST['payer_business_name'];
$payer_email          = $_POST['payer_email'];
$address_street       = $_POST['address_street'];
$address_zip          = $_POST['address_zip'];
$address_city         = $_POST['address_city'];
$address_state        = $_POST['address_state'];
$address_country      = $_POST['address_country'];
$address_country_code = $_POST['address_country_code'];
$residence_country    = $_POST['residence_country'];
 
if ( strcmp ( $txn_type, "cart" ) == 0 ) {
	$num_cart_items = $_POST['num_cart_items'];
	if ( $num_cart_items > 0 ) {
		$cart_item = array();
		for ( $i = 1; $i <= $num_cart_items; $i++ ) {
			$cart_item[] = $_POST['item_name' . $i] . ";" . $_POST['item_number' . $i] . ";" . $_POST['quantity' . $i] . ";" . $_POST['mc_gross_' . $i];
		}
	}
}
 
if (!$fp) {
	// HTTP ERROR
} else {
	fputs ($fp, $header . $req);
	while (!feof($fp)) {
		$res = fgets ($fp, 1024);
		if (strcmp ($res, "VERIFIED") == 0) {
			$payment_verified = true;
		} else if (strcmp ($res, "INVALID") == 0) {
			$payment_verified = false;
		}
	}
	fclose ($fp);
}
 
//--CONFIG----------------------------------------------------------------------
 
$supplier_address      = "Admin <admin@mysite.co.nz>";    // Destination address for all internal notifications
$paypal_address        = "Sales <sales@mysite.co.nz>";   // Sender address for outgoing messages
$paypal_address_raw    = "sales@mysite.co.nz";              // The address the IPN should come from
 
$supplier_name_long    = "Mysite.co.nz";            // Company Long name
$supplier_name_short   = "Mysite";                         // Company short name
$supplier_web_site     = "http://www.mysite.co.nz/";         // Company web site
$supplier_support_site = "http://www.mysite.co.nz/contact.php";      // Company Help desk URL
$supplier_tax_id       = "N/A";                  // VAT / Tax ID
 
$txnid_daystokeep      = 30;                                 // Days transaction ID will be kept
 
//--FORMAT TRANSACTION DETAILS--------------------------------------------------
 
if ($quantity == '0' || $quantity == "" ) { $quantity = 1; }
if ($exchange_rate == '0' || $exchange_rate == "" ) { $exchange_rate = 1; }
if ($settle_amount == '0' || $settle_amount == "" ) { $settle_amount = strval($payment_amount - $fee); }
if ($residence_country <> "") { $country = $residence_country; } else { $country = $address_country_code; }
 
list($user_system, $user_country, $user_oldserial) = split(';', $custom); // Get custom data
if ($country == "") { $country = $user_country; }        // In case PayPal has no country value we use custom one
 
$transaction_details .= "--------------------------------------------------\r";
$transaction_details .= "Order Details\r";
$transaction_details .= "--------------------------------------------------\r";
$transaction_details .= " Product: $item_name (SKU# $item_number)\r";
$transaction_details .= "  System: $user_system\r";
$transaction_details .= "Quantity: $quantity\r";
$transaction_details .= "  Amount: $payment_amount\r";
$transaction_details .= "Currency: $payment_currency\r";
$transaction_details .= "    Rate: $exchange_rate\r";
$transaction_details .= "--------------------------------------------------\r";
$transaction_details .= "   Buyer: $first_name $last_name\r";
$transaction_details .= " Company: $payer_business_name\r";
$transaction_details .= "  E-Mail: $payer_email\r";
$transaction_details .= " Country: $country\r";
$transaction_details .= "--------------------------------------------------\r";
$transaction_details .= "Trans ID: $txn_id\r";
$transaction_details .= "  Status: $payment_status\r";
$transaction_details .= "    Type: $payment_type\r";
$transaction_details .= "  Method: $txn_type\r";
$transaction_details .= "--------------------------------------------------\r";
 
 
//--PROCESS PAYMENT-------------------------------------------------------------
 
$headers = "From: $paypal_address";
$customer_address = "$first_name $last_name <$payer_email>";
 
if ($payment_verified) {
	// check the payment_status is Completed
	// check that txn_id has not been previously processed
	// check that receiver_email is your Primary PayPal email
	// check that payment_amount/payment_currency are correct
	// process payment
	
	if (strcmp ($payment_status, "Completed") == 0) { // Payment has been successfully completed
		
		if (strcmp ($receiver_email, $paypal_address_raw) == 0) { // The sender e-mail is the right address
		
			if (!CheckTransactionID($txn_id)) { // Check if it is not a duplicate transaction
		
				if (strcmp ($txn_type, "web_accept") == 0) { // This is a direct sale thru Purchase button on web site
				
/*****************************************************************************************************
*  Update the users tokens                                                                           *
*                                                                                                    */
mysql_query("UPDATE users SET tokens = tokens + $quantity WHERE username= $username")     
or die(mysql_error());
 
/******************************************************************************************************/				
					
					$customer_subject = "Thanks for purchasing $item_name!";
					$customer_message  = "Greetings from $supplier_name_short,\r\r";
					$customer_message .= "Thank you for your recent purchase!"; 
					$customer_message .= "$transaction_details\r";
					$customer_message .= "Please feel free to send us your questions, comments, or suggestions to\r";
					$customer_message .= "$supplier_support_site\r\r";
					
					$customer_message .= "Thanks again for supporting our site!\r\r";
					$customer_message .= "The $supplier_name_short Team.\r";
					$customer_message .= "$supplier_web_site\r";
						
					$supplier_subject  = "PayPal purchase notification";
					$supplier_message  = "\r";
					$supplier_message .= "<paypal>\r";
					$supplier_message .= "    Product purchased: $item_name\r";
					$supplier_message .= "    System: $user_system\r";
					$supplier_message .= "    SKU: $item_number\r";
					$supplier_message .= "    Quantity: $quantity\r";
					$supplier_message .= "    Customer: $first_name $last_name\r";
					$supplier_message .= "    Email: $payer_email\r";
					$supplier_message .= "    Username: $username\r";
					$supplier_message .= "    Total Amount Paid: $payment_currency $payment_amount\r";
					$supplier_message .= "    Profit: " . strval($payment_amount - $fee - $tax) . "\r";
					$supplier_message .= "    Fee: $fee\r";
					$supplier_message .= "    Tax: $tax\r";
					$supplier_message .= "    Date: " . date('m/d/Y') . "\r"; //$payment_date\r";
					$supplier_message .= "    TransactionID: $txn_id\r";
					$supplier_message .= "    Country: $country\r";
					$supplier_message .= "</paypal>\r\r";	
					$supplier_message .= "$transaction_details\r\r";
			
					SendMessage($supplier_address, $supplier_subject, $supplier_message, $headers);      // Copy for Supplier
					SendMessage($customer_address, $customer_subject, $customer_message, $headers);      // Copy for customer			
					
				/*   I Don't use any of this part'
				
					//Prepare invoice
					$invoice_number = "P" . date("Y") . str_pad(GetInvoiceNumber("invoice_counter.dat") , 6, "0", STR_PAD_LEFT);
					
					$invoice  = "$first_name $last_name,\r\r";			
					$invoice .= "Thanks for your order! A copy of your invoice is included below. If you\r";
					$invoice .= "have any questions, contact us at $supplier_support_site\r";
					$invoice .= "Give the order ID shown below as an identifier. Please note your license\r";
					$invoice .= "code is included below and a copy will also arrive via a separate email\r";
					$invoice .= "with instructions. Nothing is to be shipped to you.\r";
					$invoice .= "\r";
					$invoice .= $supplier_name_long . str_pad("Order-ID: #" . $invoice_number , 72 - 21, " ", STR_PAD_LEFT) . "\r";
					
					if ($tax <> '0' && $tax <> "") {
						$invoice .= $supplier_tax_id . str_pad("Date: " . date('m/d/Y') , 72 - strlen($supplier_tax_id), " ", STR_PAD_LEFT) . "\r";
					} else {
						$invoice .= $supplier_web_site . str_pad("Date: " . date('m/d/Y') , 72 - strlen($supplier_web_site), " ", STR_PAD_LEFT) . "\r";
					}
					
					$invoice .= "________________________________________________________________________\r\r";
					$invoice .= "Billing Information:\r\r";
					if ( $payer_business_name <> "" ) { $invoice .= "  $payer_business_name\r"; }
					$invoice .= "  $first_name $last_name\r";
					$invoice .= "  $payer_email\r";
					if ( $address_street <> "" ) { $invoice .= "  $address_street\r"; }
					if ( $address_city <> "" && $address_state <> "" ) { $invoice .= "  $address_city, $address_state $address_zip\r"; }
					if ( $address_country <> "" ) { $invoice .= "  $address_country\r"; }
					$invoice .= "\r";
					$invoice .= "Currency: $payment_currency (Rate= $exchange_rate)\r";
					$invoice .= "Order Method: PayPal";
					$invoice .= "\r\r";
					$invoice .= "Item name                                      Price      Qty      Total\r";
					$invoice .= "------------------------------------------------------------------------\r";
					$invoice .= "$item_name" . str_pad($payment_amount , 52 - strlen($item_name), " ", STR_PAD_LEFT);
					$invoice .= str_pad($quantity , 61 - 52, " ", STR_PAD_LEFT) . str_pad($payment_amount , 11, " ", STR_PAD_LEFT) . "\r";
					$invoice .= "\r\r";
					$invoice .= "------------------------------------------------------------------------\r";
					$invoice .= "Total:" . str_pad($payment_amount , 72 - 6, " ", STR_PAD_LEFT) . "\r";
					if ($tax <> '0' && $tax <> "") { $invoice .= "  Tax:" . str_pad($tax , 72 - 6, " ", STR_PAD_LEFT) . "\r"; }
					$invoice .= "------------------------------------------------------------------------\r";
					$invoice .= "\r";
					$invoice .= "We have charged your PayPal account for the total above.\r";
					$invoice .= "Thanks for your business!\r";
					$invoice .= "\r";
					$invoice .= "NOTE:  Please do not reply to this e-mail as it will not be received.\r";
					$invoice .= "Please visit our support page: $supplier_support_site\r";
					$invoice .= "\r";
					
					LogInvoice($invoice_number, "$first_name $last_name", $country, $txn_id, $item_name, $payment_currency, $exchange_rate, $payment_amount, $fee, $tax);
					SaveInvoice($invoice_number, $invoice);	
					
				//	SendMessage($supplier_address, "Invoice #" . $invoice_number, $invoice, $headers);                           // Send invoice to Supplier
				//	SendMessage($customer_address, "Your $supplier_name_short Order #" . $invoice_number, $invoice, $headers);   // Send invoice to customer   */
	
				
				} else if (strcmp ($txn_type, "send_money") == 0) { // Transaction created by customer from the Send Money tab on the PayPal website.
					// Handle 'Send money' here or do nothing
				} else if (strcmp ($txn_type, "cart") == 0) { // Transaction created by customer via the PayPal Shopping Cart feature.
					// Handle cart purchase here
					//************************************************************************************************************************************************************************<CART>
					$customer_subject = "Thanks for your purchase!";
					$customer_message  = "Greetings from $supplier_name_short,\r\r";
					$customer_message .= "Thank you for your recent purchase! Provided below is important information\r";
					$customer_message .= "about the delivery of your products. It is recommended that you print or save\r";
					$customer_message .= "this email for future reference. Should you experience any product related\r";
					$customer_message .= "problems, please use the support information found below.\r\r";
					$customer_message .= "Your serial (if applies) will be sent very soon in a separate e-mail.\r\r";
					$customer_message .= "$transaction_details\r";
					$customer_message .= "Please feel free to send us your questions, comments, or suggestions. If\r";
					$customer_message .= "you are having troubles getting started with this product, feel free to\r";
					$customer_message .= "ask us using our support inquiry form at: $supplier_support_site\r";
					$customer_message .= "Please be as descriptive as possible.\r\r";
					$customer_message .= "Thanks again for supporting our products!\r\r";
					$customer_message .= "The $supplier_name_short Team.\r";
					$customer_message .= "$supplier_web_site\r";
						
					foreach ( $cart_item as $myvalue ) {
						list($item_name, $item_number, $quantity, $item_gross) = split(';', $myvalue);
						$supplier_subject = "PayPal purchase notification";
						$supplier_message  = "\r";
						$supplier_message .= "<paypal>\r";
						$supplier_message .= "    Product purchased: $item_name\r";
						$supplier_message .= "    System: $user_system\r";
						$supplier_message .= "    SKU: $item_number\r";
						$supplier_message .= "    Quantity: $quantity\r";
						$supplier_message .= "    Registered-To: $first_name $last_name\r";
						$supplier_message .= "    Email: $payer_email\r";
						$supplier_message .= "    Total Amount Paid: $payment_currency $payment_amount\r";
						$supplier_message .= "    Profit: " . number_format(Round($item_gross - $fee*($item_gross/($payment_amount-$fee)) - $tax*($item_gross/($payment_amount-$tax)), 2), 2, ".", ",") . "\r";
						$supplier_message .= "    Fee: $fee\r";
						$supplier_message .= "    Tax: $tax\r";
						$supplier_message .= "    Date: " . date('m/d/Y') . "\r"; //$payment_date\r";
						$supplier_message .= "    TransactionID: $txn_id\r";
						$supplier_message .= "    Country: $country\r";
						$supplier_message .= "</paypal>\r\r";	
						$supplier_message .= "$transaction_details\r\r";
						$supplier_message .= "$serial_text";
									
						SendMessage($supplier_address, $supplier_subject, $supplier_message, $headers);      // Copy for Supplier
						SendMessage($customer_address, $customer_subject, $customer_message, $headers);      // Copy for customer
					}
					
					$invoice_number = "P" . date("Y") . str_pad(GetInvoiceNumber("invoice_counter.dat") , 6, "0", STR_PAD_LEFT);
					$invoice  = "$first_name $last_name,\r\r";			
					$invoice .= "Thanks for your order! A copy of your invoice is included below. If you\r";
					$invoice .= "have any questions, contact us at $supplier_support_site\r";
					$invoice .= "Give the order ID shown below as an identifier. Please note your license\r";
					$invoice .= "code is included below and a copy will also arrive via a separate email\r";
					$invoice .= "with instructions. Nothing is to be shipped to you.\r";
					$invoice .= "\r";
					$invoice .= $supplier_name_long . str_pad("Order-ID: #" . $invoice_number , 72 - 21, " ", STR_PAD_LEFT) . "\r";
					
					if ($tax <> '0' && $tax <> "") {
						$invoice .= $supplier_tax_id . str_pad("Date: " . date('m/d/Y') , 72 - strlen($supplier_tax_id), " ", STR_PAD_LEFT) . "\r";
					} else {
						$invoice .= $supplier_web_site . str_pad("Date: " . date('m/d/Y') , 72 - strlen($supplier_web_site), " ", STR_PAD_LEFT) . "\r";
					}
					
					$invoice .= "________________________________________________________________________\r\r";
					$invoice .= "Billing Information:\r\r";
					if ( $payer_business_name <> "" ) { $invoice .= "  $payer_business_name\r"; }
					$invoice .= "  $first_name $last_name\r";
					$invoice .= "  $payer_email\r";
					if ( $address_street <> "" ) { $invoice .= "  $address_street\r"; }
					if ( $address_city <> "" && $address_state <> "" ) { $invoice .= "  $address_city, $address_state $address_zip\r"; }
					if ( $address_country <> "" ) { $invoice .= "  $address_country\r"; }
					$invoice .= "\r";
					$invoice .= "Currency: $payment_currency\r"; // (Rate= $exchange_rate)\r";
					$invoice .= "Order Method: PayPal";
					$invoice .= "\r\r";
					$invoice .= "Item name                                      Price      Qty      Total\r";
					$invoice .= "------------------------------------------------------------------------\r";
					
					foreach ( $cart_item as $myvalue ) {
						list($item_name, $item_number, $quantity, $item_gross) = split(';', $myvalue);
						$invoice .= "$item_name" . str_pad(number_format(floatval($item_gross)/intval($quantity), 2, ".", ",") , 52 - strlen($item_name), " ", STR_PAD_LEFT);
						$invoice .= str_pad($quantity , 61 - 52, " ", STR_PAD_LEFT) . str_pad($item_gross , 11, " ", STR_PAD_LEFT) . "\r";
					}
					
					$invoice .= "\r\r";
					$invoice .= "------------------------------------------------------------------------\r";
					if ($tax <> '0' && $tax <> "") { $invoice .= "  Tax:" . str_pad($tax , 72 - 6, " ", STR_PAD_LEFT) . "\r"; }
					$invoice .= "Total:" . str_pad($mc_gross , 72 - 6, " ", STR_PAD_LEFT) . "\r";
					$invoice .= "------------------------------------------------------------------------\r";
					$invoice .= "\r";
					$invoice .= "We have charged your PayPal account for the total above.\r";
					$invoice .= "Thanks for your business!\r";
					$invoice .= "\r";
					$invoice .= "NOTE:  Please do not reply to this e-mail as it will not be received.\r";
					$invoice .= "Please visit our support page: $supplier_support_site\r";
					
					LogInvoice($invoice_number, "$first_name $last_name", $country, $txn_id, "Cart", $payment_currency, $exchange_rate, $payment_amount, $fee, $tax, $settle_amount);
					SaveInvoice($invoice_number, $invoice);
					
					SendMessage($supplier_address, "Invoice #" . $invoice_number, $invoice, $headers);                           // Send invoice to Supplier
					SendMessage($customer_address, "Your $supplier_name_short Order #" . $invoice_number, $invoice, $headers);   // Send invoice to customer
			
					//************************************************************************************************************************************************************************</CART>
				} else {
					// oops!!!! We should never get there...
				}
				
			} else {
				// Transaction ID already exists, this is a duplicate process
			}
			
		} else { // ERROR: The sender address *is not* the right address !!!!
		
			$subject = "PayPal transaction alert (wrong e-mail address -> $receiver_email <> $paypal_address_raw)";
			$message = $transaction_details;
					
			SendMessage($supplier_address, $subject, $message, $headers);
				
		}
		
	} else if (strcmp ($payment_status, "Refunded") == 0 || strcmp ($payment_status, "Reversed") == 0 || strcmp ($payment_status, "Partially-Refunded") == 0) {
		
		if (!CheckTransactionID($txn_id)) { // Check if it is not a duplicate transaction
			$parent_txn_id = $_POST['parent_txn_id']; // Contains the original transaction ID, the one that has been refunded or reversed
			$reason_code   = $_POST['reason_code'];   // Reason why the payment has been refunded, refund, chargeback, buyer complaint...
			
			//Prepare Refund invoice
			$invoice_number = "R" . date("Y") . str_pad(GetInvoiceNumber("refund_counter.dat") , 6, "0", STR_PAD_LEFT);
			
			//If ( $payment_status == "Refunded" ) { $invoice_number = $invoice_number . " (Refund)"; }
			//If ( $payment_status == "Partially-Refunded" ) { $invoice_number = $invoice_number . " (Refund)"; }
			//If ( $payment_status == "Reversed" ) { $invoice_number = $invoice_number . " (Chargeback)"; }
			
			$invoice  = "$first_name $last_name,\r\r";			
			$invoice .= "Your refund has been issued! A copy of your invoice is included below.\r";
			$invoice .= "If you have any questions, contact us at $supplier_support_site\r";
			$invoice .= "Give the refund ID shown below as an identifier.\r";
			$invoice .= "\r";
			$invoice .= $supplier_name_long . str_pad("Refund-ID: #" . $invoice_number , 72 - 21, " ", STR_PAD_LEFT) . "\r";
			
			if ($tax <> '0' && $tax <> "") {
				$invoice .= $supplier_tax_id . str_pad("Date: " . date('m/d/Y') , 72 - strlen($supplier_tax_id), " ", STR_PAD_LEFT) . "\r";
			} else {
				$invoice .= $supplier_web_site . str_pad("Date: " . date('m/d/Y') , 72 - strlen($supplier_web_site), " ", STR_PAD_LEFT) . "\r";
			}
			
			$invoice .= "________________________________________________________________________\r\r";
			$invoice .= "Billing Information:\r\r";
			if ( $payer_business_name <> "" ) { $invoice .= "  $payer_business_name\r"; }
			$invoice .= "  $first_name $last_name\r";
			$invoice .= "  $payer_email\r";
			if ( $address_street <> "" ) { $invoice .= "  $address_street\r"; }
			if ( $address_city <> "" && $address_state <> "" ) { $invoice .= "  $address_city, $address_state $address_zip\r"; }
			if ( $address_country <> "" ) { $invoice .= "  $address_country\r"; }
			$invoice .= "\r";
			$invoice .= "Currency: $payment_currency\r"; // (Rate= $exchange_rate)\r";
			$invoice .= "Order Method: PayPal";
			$invoice .= "\r\r";
			$invoice .= "Item name                                      Price      Qty      Total\r";
			$invoice .= "------------------------------------------------------------------------\r";
			$invoice .= "$item_name" . str_pad($payment_amount , 52 - strlen($item_name), " ", STR_PAD_LEFT);
			$invoice .= str_pad($quantity , 61 - 52, " ", STR_PAD_LEFT) . str_pad($payment_amount , 11, " ", STR_PAD_LEFT) . "\r";
			$invoice .= "\r\r";
			$invoice .= "------------------------------------------------------------------------\r";
			$invoice .= "Total:" . str_pad($payment_amount , 72 - 6, " ", STR_PAD_LEFT) . "\r";
			if ($tax <> '0' && $tax <> "") { $invoice .= "  Tax:" . str_pad($tax , 72 - 6, " ", STR_PAD_LEFT) . "\r"; }
			$invoice .= "------------------------------------------------------------------------\r";
			$invoice .= "\r";
			$invoice .= "We have credited your PayPal account for the total above.\r";
			$invoice .= "Please remove the refunded product(s) from your computer!\r";
			$invoice .= "\r";
			$invoice .= "NOTE:  Please do not reply to this e-mail as it will not be received.\r";
			$invoice .= "Please visit our support page: $supplier_support_site\r";
 
			LogInvoice($invoice_number . " *", "$first_name $last_name", $country, $txn_id, $parent_txn_id, $payment_currency, $exchange_rate, $payment_amount, $fee, $tax, $settle_amount);
			SaveInvoice($invoice_number, $invoice);	
			
			SendMessage($supplier_address, "Invoice #" . $invoice_number . " (Refund)", $invoice, $headers);              // Send refund invoice to Supplier
			SendMessage($customer_address, "Your $supplier_name_short Refund #" . $invoice_number, $invoice, $headers);   // Send refund invoice to customer
		
			$subject = "PayPal transaction #$parent_txn_id $payment_status ($reason_code)";
			$message = "$subject:\r\r";
			$message .= $transaction_details;
				
			SendMessage($supplier_address, $subject, $message, $headers);
		}
		
	} else if (strcmp ($payment_status, "Pending") == 0 ) { // The payment is pending
	
		$pending_reason = $_POST['pending_reason']; // Reason why this transaction is pending
		
		$subject = "PayPal transaction $payment_status ($pending_reason)";
		$message = "Greetings from $supplier_name_short,\r\r";
		
		if (strcmp ($pending_reason, "echeck") == 0 ) {
			$message .= "Thank you for your purchase. This e-mail confirms that you have sent an\r";
			$message .= "eCheck Payment for $payment_amount $payment_currency to us.\r\r";
			$message .= "This eCheck Payment will remain <Uncleared> until the funds have cleared\r";
			$message .= "from your account, which usually takes 4 business days.\r\r";
			$message .= "The serial numbers for the products you have purchased will be sent\r";
			$message .= "automatically as soon as the funds have cleared into our PayPal account.\r\r";
			$message .= $transaction_details;
		} else {
			$message .= "Thank you for your purchase. This e-mail confirms that you have sent a\r";
			$message .= "payment for $payment_amount $payment_currency to us.\r\r";
			$message .= "This Payment is pending (Reason: $pending_reason)\r\r";
			$message .= "The serial numbers for the products you have purchased will be sent\r";
			$message .= "automatically as soon as the funds have cleared into our PayPal account.\r\r";
			$message .= $transaction_details;
		}
		
		SendMessage($supplier_address, $subject, $message, $headers);    // Copy for Supplier
		SendMessage($customer_address, $subject, $message, $headers);    // Copy for customer
		
	} else { // Payment has *not* been successfully completed
	
		$subject = "PayPal transaction $payment_status (not handled)";
		$message = "$subject:\r\r";
		$message .= $transaction_details;
				
		SendMessage($supplier_address, $subject, $message, $headers);
		
	}
		
} else if (!$payment_verified) { // log for manual investigation
 
	$subject = "PayPal error";
	$message = "Error in processing.\r\r";
	$message .= $transaction_details;
 
	SendMessage($supplier_address, $subject, $message, $headers);
	
}
 
//--POST PAYMENT PROCESSES-------------------------------------------------------------
 
EmptyMailQueue();
DeleteFilesOlderThan("transactions", $txnid_daystokeep);
 
//--FUNCIONS---------------------------------------------------------------------------
 
// Send message and check result
function SendMessage($recipient, $subject, $message, $headers) {
	if ( stristr( $recipient, "@" ) !== FALSE ) {
		$result = mail($recipient, $subject, $message, $headers);
		if ( !$result ) { LogDeliveryError($recipient, $subject, $message, $headers); }
	}
}
 
// If message has not been sent successfully we store it to the mailqueue directory
function LogDeliveryError($recipient, $subject, $message, $headers) {
	$filename = "mailqueue/" . date('YmdHis') . ".txt";
	$counter = 1;
	while (file_exists($filename)) {
		$filename = "mailqueue/" . date('YmdHis') . $counter . ".txt";
		$counter++;
	}
	$handle   = fopen($filename, "a+");
	$contents = "<msg_recipient>$recipient</msg_recipient>\n";
	$contents .= "<msg_subject>$subject</msg_subject>\n";
	$contents .= "<msg_headers>$headers</msg_headers>\n";
	$contents .= "<msg_body>" . str_replace("\r", "\n", $message). "</msg_body>\n";
	fputs($handle, $contents);
	fclose($handle);
}
 
// Look at mailqueue directory and send all messages
function EmptyMailQueue() {
	$path = "mailqueue";
	if ($handle = opendir($path)) {
		while (false !== ($file = readdir($handle))) {
			if ( $file != ".." && $file != "." ) { 
				$filename = "$path/$file";
				$filehandle = fopen($filename, "r");
				if ($filehandle) {
   					while (!feof($filehandle)) {
       					$contents .= fgets($filehandle, 4096);
   					}
   					fclose($filehandle);
   					$xmlFieldNames = array("msg_recipient", "msg_subject", "msg_headers", "msg_body");
					$data = ParseXMLData($contents, $xmlFieldNames);
					$result = mail($data['msg_recipient'], $data['msg_subject'], $data['msg_body'], $data['msg_headers']);
					if ( $result ) { unlink($filename); }
				}			
			}
		}
	closedir($handle);
	}
}
 
function ParseXMLData ($xmlRaw, $xmlFieldNames) {
	// $xmlRaw="<order>Order data</order><label>Label data</label><control>123</control>";
	// $xmlFieldNames=array("order", "label", "control");
	foreach ($xmlFieldNames as $xmlField) {
   		if(strpos($xmlRaw,$xmlField)!==false){
       		$parsedXML[$xmlField]=substr($xmlRaw, strpos($xmlRaw,"<$xmlField>")+strlen("<$xmlField>"), strpos($xmlRaw,"</$xmlField>")-strlen("<$xmlField>")-strpos($xmlRaw,"<$xmlField>"));
		}
	}
	return($parsedXML);
}
 
// Check if a transaction ID already exists
function CheckTransactionID($trans_id) {
	$path = "transactions";
	$filename = "$path/$trans_id.txt";
	$txn_exists = file_exists($filename);
	if (!$txn_exists) {
		$handle = fopen($filename, "a+");
		fclose($handle);
		//DeleteFilesOlderThan($path, $txnid_daystokeep); // moved to post payment processes
	}
	return $txn_exists;
}
 
// Get a new invoice number
function GetInvoiceNumber($filename) {	
	if ( file_exists( $filename ) ) {
		$lastmodifiedyear  = intval( date( "Y", filemtime( $filename ) ) );
		$handle  = fopen( $filename, "r+" );
		$counter = intval( fgets( $handle, 64 ) );
	} else {
		$handle  = fopen( $filename, "a+" );
		$counter = 0;
	}
	if ( flock( $handle, LOCK_EX ) ) {
		if ( intval( date("Y") ) == $lastmodifiedyear + 1 && date( "n" ) == 1 ) {
			ftruncate( $handle, 0 );
			$counter = 0;
		}	
		$counter++;
		rewind( $handle );
		fputs( $handle, $counter );
		flock( $handle, LOCK_UN );
	}
	fclose( $handle );
	return $counter;
}
 
// Save sale to excel sheet
function LogInvoice($invoice_number, $customer_name, $customer_country, $transaction_id, $item_purchased, $currency, $exchange_rate, $amount, $fee, $taxes, $settle) {
	$filename = "sales/" . date('Y') . "-" . date('m') . "-sales-" . $currency . ".xls";
	$exists = file_exists($filename);
	$handle   = fopen($filename, "a+");
	
	if ( flock( $handle, LOCK_EX ) ) {
		if (!$exists) {
			$newentry = "Invoice\tDate\tCustomer\tCountry\tTransaction\tProduct\tCurrency\tGross\tFee\tProfit\tTax\tRate\tSettle\n";
			fputs($handle, $newentry);
		}
		if ($taxes <> '0' && $taxes <> "") {
			if ($customer_country != "") { $country_code = "($customer_country)"; }
			$customer_country = "European Union $country_code";
		} else if ($customer_country == "") {
			$customer_country = "US";
		}
		if ($taxes == "") { $taxes = "0"; }
		$profit = $amount - $fee - $taxes;
		$newentry = "$invoice_number\t" . date('m/d/Y') . "\t$customer_name\t$customer_country\t$transaction_id\t$item_purchased\t$currency\t$amount\t$fee\t$profit\t$taxes\t$exchange_rate\t$settle\n";
		fputs($handle, $newentry);
		flock( $handle, LOCK_UN );
	}
	fclose($handle);
}
 
// Save invoice
function SaveInvoice($invoice_number, $invoice) {
	$path = "invoices/" . date('Y');
	if (!file_exists($path)) { mkdir($path, 0777); }
	$path = "invoices/" . date('Y') . "/" . date('m');
	if (!file_exists($path)) { mkdir($path, 0777); }
	$filename = "invoices/" . date('Y') . "/" . date('m') . "/$invoice_number.txt";
	$handle   = fopen($filename, "a+");
	$contents = str_replace("\r", "\n", $invoice);
	fputs($handle, $contents);
	fclose($handle);
}
 
function DeleteAllFilesFromDir($path) {
	if ($handle = opendir($path)) {
		while (false !== ($file = readdir($handle))) {
			if ( $file != ".." && $file != "." ) { unlink("$path/$file"); }
		}
	closedir($handle);
	}
}
 
function DeleteFilesOlderThan($path, $days) {
	if ( is_dir("$path") ) { 
		$handle = opendir($path); 
		while (false!==($file = readdir($handle))) { 
			if ($file != "." && $file != "..") {  
				$Diff = (time() - filectime("$path/$file"))/60/60/24;
				if ($Diff > $days) unlink("$path/$file");
			} 
		}
		closedir($handle); 
	}
}
 
function round_to_penny($amount) {  
   $string = (string)($amount * 100);
   $string_array = split("\.", $string);
   $int = (int)$string_array[0];
   $return = $int / 100;
   return $return;
}
 
?>
[+][-]08/05/09 10:45 PM, ID: 25030366

Experts Exchange has a courteous staff of administrators who help members get the most out of the website by means of administrative comments like this one.

Start your 30-day free trial to view this Administrative Comment or ask the Experts your question.

 
[+][-]08/05/09 10:49 PM, ID: 25030378

At Experts Exchange, members can ask their questions to thousands of technology professionals, also known as Experts. Experts compete and collaborate to answer those questions by leaving comments like this one.

Start your 30-day free trial to view this Expert Comment or ask the Experts your question.

 
[+][-]08/06/09 03:54 AM, ID: 25031867

Often, when Experts are collaborating with members who have asked questions, they will request additional information about the problem. Askers respond with an author comment like this one.

Start your 30-day free trial to view this Author Comment or ask the Experts your question.

 
[+][-]08/06/09 04:39 AM, ID: 25032103

Often, when Experts are collaborating with members who have asked questions, they will request additional information about the problem. Askers respond with an author comment like this one.

Start your 30-day free trial to view this Author Comment or ask the Experts your question.

 
[+][-]08/06/09 06:30 AM, ID: 25033037

View this solution now by starting your 30-day free trial. Setting up your free trial is quick, easy, and secure. We will return you to this solution, unlocked, when you're done.

 

About this solution

Zones: Payment Processing Recommendation and Integrating, Internet Marketing, PHP Scripting Language
Tags: paypal ipn, php, ipn script, website payments
Sign Up Now!
Solution Provided By: Ray_Paseur
Participating Experts: 2
Solution Grade: A
 
 
[+][-]08/06/09 12:11 PM, ID: 25037008

Often, when Experts are collaborating with members who have asked questions, they will request additional information about the problem. Askers respond with an author comment like this one.

Start your 30-day free trial to view this Author Comment or ask the Experts your question.

 
[+][-]08/06/09 02:54 PM, ID: 25038487

At Experts Exchange, members can ask their questions to thousands of technology professionals, also known as Experts. Experts compete and collaborate to answer those questions by leaving comments like this one.

Start your 30-day free trial to view this Expert Comment or ask the Experts your question.

 
[+][-]08/06/09 03:02 PM, ID: 25038541

Often, when Experts are collaborating with members who have asked questions, they will request additional information about the problem. Askers respond with an author comment like this one.

Start your 30-day free trial to view this Author Comment or ask the Experts your question.

 
 
Loading Advertisement...
20091111-EE-VQP-91 - Hierarchy / EE_QW_EXPERT_20070906