Introduction to Paypal for C# Asp.Net Developers

elderlyscatteredInternet and Web Development

Jul 5, 2012 (5 years and 4 months ago)

2,715 views

WebDevelopment
»
ASP.NET
»
General
 License:
TheCodeProjectOpenLicense(CPOL)


Introduction to PayPal for C# - ASP.NET
developers
By
Predrag Tomasevic


OverviewthatpresentsallPayPalintegrationoptions,targetedespeciallyatC#developers
C#,.NET(.NET2.0,.NET3.0,.NET
3.5),ASP.NET,Architect,Dev
Posted:6 Oct 2009
Views:678
Bookmarked:10 times
2votesforthisarticle.
Popularity:1.38
Rating:4.60outof5

1

2

3

4

5
Downloadsource6170KB
Index
PayPalIntroduction

GettingstartedwithPayPal

Settinguptestaccount

WebsitePaymentsStandard(HTML)

PostPaymentprocessing

AutoReturn

DirectPayment(PDT)

InstantPaymentNotification(IPN)

PayPalAPI

ExpressCheckout

DirectPayment(WebsitePaymentsPro)

Conclusion

History

Introduction
PayPalisprobablyoneofthefirstthingsthatgetsmentionedoncediscussionononlinepaymentsstarts.
It’snotsowithoutreason–in2008PayPalmovedover60billiondollarsbetweenaccountswhichis,you’ll
agree,respectableamount.Andalso,alltrendsshowthatthisgrowthwillcontinue–withhugenumberof
newaccounts(over184millionaccountsin2008comparedto96.2millionin2005),withnewplatform
named
PayPalX
andwithmorecoolapplicationsthatinvolvepaying(like
Twitpay
)youcanbetthatPayPal
isheretostay.So,howcanyoujoinwholePayPalDevelopmentmovement?
Unfortunately,Iwouldsay–notsoeasily.WhenIfirststartedwithPayPalintegration6itwashard,really
hard.IfyouwishtoseewhatImean,justjumpto
PayPalDeveloperCenter
.Thereisnowayyou’lleasily
fishoutwhatyouneedfromthatsiteifyouarePayPalnewbie;simply6therearetoomanylinks,toomany
resourcesandtoomanymixingsofimportantandnot6so6importantinformation.So,howshouldyoustart?

Getting started with PayPal
TothosewhoreallywanttogetintoPayPalandarewillingtoshelloutsomebuck,Iwouldrecommend
Pro
PayPalE6Commerce
book6that’showIeventuallygotintounderstandingconceptsbehindPayPal
integration.Forthosewhoarenotsoeagertopay–don’tworry,that’swhythisarticleishere...I'llgoover
mostofthestuffthatbookcovers,butinmorebriefandconcisemanner.
Firstandforemost6understandingwhatkindsofintegrationPayPaloffersis,Iwouldsay,mostimportant
thinginordertosuccessfullystartyourdevelopmentjourney.Commonmistake,thathappenedtomealso,
istostartatoncewithPayPalAPIandExpressCheckout.Imeanit’snatural6wearedevelopersandwhen
theytellustointegratewithsomething,thefirstthingwelookforisSDK&API…PayPalAPIcomesupasa
result…wesay“That’sit”toourselves…andstartworking.Theproblemis–majorityofpaymentscenarios
canbehandledwithwaysimplerapproach6HTMLformsthatarepartofWebsitePaymentsStandard.
So,withoutfurtherado,hereisclassificationofPayPalintegrations:
Pagina
1
di
14
CodeProject: Introduction to PayPal for C#
-
ASP.NET developers. Free source code and programm
...
07/10/2009
http://www.codeproject.com/KB/aspnet/aspnet_c_aspnet.aspx?display=Print
WebsitePaymentsStandard(HTML)•
PostpaymentProcessing•
AutoReturn

PaymentDataTransfer(PDT)

InstantPaymentNotification(IPN)

PayPalAPI•
ExpressCheckout

DirectPayment(WebsitePaymentsPro)

PayflowGateway•
ItemsinclassificationarealsoorderedinawayIwouldsuggestforeveryonetofollow.So,ifyouarenew
toPayPal–firstlearnalloftheoptionsthatyouhavewithWebsitePaymentsStandard(HTML).Then,if
youneedtoaddsomebasicpost6paymentprocessing,seeifAuto6ReturnorPDTwillsolveyourproblem…
if
not,IPNismorerobustoptionyouhaveatyourdisposal.
NextlevelwouldinvolvePayPalAPIandimplementingExpressCheckout,whichisthemostflexiblePayPal
integrationsolution.Andfinally,ifyoulongforabilitytodirectlyprocesscreditcardsonyourwebsite,you’
ll
paymonthlyfeetoPayPalandimplementDirectPayment(effectivelygettingwhatiscalledWebsite
PaymentsPro).
Lastitemfromourclassification6PayflowGatewayis,ontheotherhand,differentbeast.Itdoesn’t“
update
thestack”inawaypreviouslymentionedtechnologiesdo.Itissolutionaimedspecificallyatthose
businessesthathave/wantInternetMerchantAccount(IMA)andjustneedpaymentgateway.Inorderto
keeparticleconsistentI’llskipexplainingdetailsofPayflowGateway.However,ifyouhaveanyquestion
relatedtoit,feelfreetoleavemessageincommentsandI’lltrytoanswer.
Thatsaid;let’sgettosettinguptestingPayPalaccountandthenwe’lldelvedeeperintodescribing
mentionedintegrations.
Setting up test account
Wordofnotice–you’llwanttofollowthisstepevenifyoualreadyhavelivePayPalaccount.Therearetwo
reasonsforusingtestaccounts:
youdon’twanttotestandplaywithrealmoney•
youwanttohaveaccesstodifferent
typesofPayPalaccounts
•
Personalaccount–mostpeoplehavethese;justaccountthatallowsyoutousePayPalwhen
payingforstuffonline.Theoretically,youcanusePersonalaccounttoacceptmoney;justknow
thatyou’llbeseverelyconstrained–thereis$500receivinglimitpermonthandyouareonly
abletoacceptonetimepaymentsusingWebsitePaymentsStandard(HTML).Thebig
advantageofPersonalaccountisthatyoudon’tneedtopayanytransactionfeewhenreceiving
money.Notehowever,thatifyoureceivemorethan$500inonemonthyou’llbepromptedto
eitherupgradetoPremier/Businessaccountorrejectpayment.

Premieraccount–stepupfrompersonalaccount;foranyonethatwantstorunpersonalonline
business.Thistypeofaccounthasalloftheintegrationoptions(acceptingcreditcards,
recurringpayments,PayPalAPI).However,mostpeopleskipdirectlyfromPersonaltoBusiness
accountasPremieraccounthassame
transactionfees
(inmostcases2.9%+$0.30per
transaction)whilelackingreporting,multi6useraccessandotheradvanced
merchantservicesof
Businessaccount.

Businessaccount–ithasallofthefeaturesofPremieraccountplusfewmore(abilityto
operateunderyourbusiness’snameisoneofthem).Ifyouaredevelopingwebsitethatneeds
toacceptpaymentsin99%ofsituationsyou’llgowiththistypeofaccount.

Tostart,visitPayPalSandboxandsign6upfornewaccount.Theprocessisstraightforwardandmost
developersshouldhavenotroublefinishingit.However,herearethepicturesthatwillhelpyounavigate
throughprocess:
Pagina
2
di
14
CodeProject: Introduction to PayPal for C#
-
ASP.NET developers. Free source code and programm
...
07/10/2009
http://www.codeproject.com/KB/aspnet/aspnet_c_aspnet.aspx?display=Print

Signing up for sandbox account

Filling in details of your sandbox account
Oncedonewithenteringdetailsforyoursandboxaccount,you'llneedtocheckemailyouprovidedinorder
tocompleteregistration.Afterthat,you'llbeabletologinandstartcreatingsandboxPayPalaccounts.
ClickingonTest Accounts(menuontheleft),andthenCreateAccount:Preconfigured6willgetyou
formliketheoneonimagebelow:
Pagina
3
di
14
CodeProject: Introduction to PayPal for C#
-
ASP.NET developers. Free source code and programm
...
07/10/2009
http://www.codeproject.com/KB/aspnet/aspnet_c_aspnet.aspx?display=Print

Creating a Sandbox Test Account
ClarificationofAccoutTyperadiobuttons:byselectingBuyeryou'llcreatePersonalaccountandby
selectingSelleryou'llcreateBusinessaccount.Fortestingmostintegrationscenariosyou'llneedboth
accountssobesuretocreatethem.Hereiswhatyoushouldeventuallyhaveonyourscreenafteryouclick
onTest Accounts.

Overview of your testing accounts
CheckingradiobuttonnexttoanyoftheaccountsfromlistandclickingonEnterSandboxTestSiteshould
bringupSandboxPayPalsitewhichwillallowyoutologinandadministeryouraccountinsamewayaswith
regularPayPalaccount.Theonlydifferenceisthatyou'llhavehugePayPalSandboxheaderandtextthat
displaysemailaddressofyourdeveloperaccount.ToseewhatI'mtalkingabout,checkimagebelow:
Pagina
4
di
14
CodeProject: Introduction to PayPal for C#
-
ASP.NET developers. Free source code and programm
...
07/10/2009
http://www.codeproject.com/KB/aspnet/aspnet_c_aspnet.aspx?display=Print


Administering PayPal Sandbox account
Lastbutnotleast6inordertouseyourSandboxaccountfortestingyouneedtobeloggedinwithyour
developeraccount
.Ifyouarenotloggedinandyoufollowsomepaymentlinkyou'llgetfollowingscreen:

Login to use the PayPal Sandbox features
Website Payments Standard (HTML)
InthissectionI'llprovideyouwithnumberofexamplesthatwillshowhowtocreateyourownHTMLform
forreceivingmoneyoverPayPal.You'llseehowtousedifferentvariablesinordertoinfluencepayment
details.Beforewedelveintodetails,let'stakealookattwomostbasicvariables:
Pagina
5
di
14
CodeProject: Introduction to PayPal for C#
-
ASP.NET developers. Free source code and programm
...
07/10/2009
http://www.codeproject.com/KB/aspnet/aspnet_c_aspnet.aspx?display=Print
form'sactionattribute6inmostcasesitshouldbehttps://www.paypal.com/cgi-bin/webscr.If
youareusingSandboxfortestingpaymentsyou'llchangeitto
https://www.sandbox.paypal.com/cgi-bin/webscr6effectivelyyoujustinsertwordsandbox
intourl(thisisalsotrueforsomeotherintegrations;e.g.PayPalAPI).Forcomingexamples,Iwon't
beusingSandboxurlbecausemostofyouwouldjustgetthat"LogintousethePayPalSandbox
features"screen(lookupforimage).

form'sbusinesschild6I'lluseyouremailaddress@yourdomain.comformostexamples;ifyou
copy6pastecode,you'llwanttoreplacethatwithemailofyourPayPalaccount.

Basic payment
OK,let’ssayyouhaveopenedPayPalaccountandyoujustwishtobeabletoaccept$10paymentfor
paintingyouaresellingthroughyoursite.JustinsertfollowingHTMLintoyourpageandyouaresettogo:
<form action="https://www.paypal.com/cgi-bin/webscr" method="post">
<input type="hidden" name="cmd" value="_xclick" />
<input type="hidden" name="business" value="youremailaddress@yourdomain.com" />
<input type="hidden" name="item_name" value="My painting" />
<input type="hidden" name="amount" value="10.00" />
<input type="submit" value="Buy!" />
</form>
Shipping & handling
Nextthingthatcomestomindisthatyou'llwishtoaddshippingand/orhandlingfeestoyourform.It's
easy6justaddmoreparameters:
<form action="https://www.paypal.com/cgi-bin/webscr" method="post">
<input type="hidden" name="cmd" value="_xclick" />
<input type="hidden" name="business" value="youremailaddress@yourdomain.com" />
<input type="hidden" name="item_name" value="My painting" />
<input type="hidden" name="amount" value="10.00" />
<input type="hidden" name="shipping" value="3.00" />
<input type="hidden" name="handling" value="2.00" />
<input type="submit" value="Buy with additional parameters!" />
</form>
Donations & Textual links
Ifyouaren'tsellinganythingbutratheracceptingdonationsforsomecause6you'lljustneedtochange
valueofcmdvariableto_donations.Ifwecombinethiswithcommonrequirementtohavehyperlink
insteadofbutton6wegetfollowingURL(ofcourseyoucanusethismethodofURLcreationforother
PayPalpaymenttypes):
https://www.paypal.com/cgi6bin/webscr?
cmd=_donations&business=youremailaddress@yourdomain.com&item_name=SavePolarBears!
&amount=10.00
RESULT:
SavePolarBears!
Cart system
Ifyouhavebunchdifferentproductstoofferandyoujustwantsimplecartsystemwithoutimplementing
anythingPayPalhasyoucovered.Basically,you'lljustplaywith
cmdvariablewhilekeepingrestoftheform
sameasforBasicPayment.Let'sseehowyoushoulddothisfortwoproducts;onepricedat$10without
shippingfeesandonepricedat$5with$1shippingfee.WewillalsoneedViewCartbutton:
My Cart Item 1:
<form action="https://www.paypal.com/cgi-bin/webscr" method="post" target="paypal">
<input type="hidden" name="cmd" value="_cart">
<input type="hidden" name="add" value="1">
<input type="hidden" name="business" value="youremailaddress@yourdomain.com">
<input type="hidden" name="item_name" value="My Cart Item 1">
<input type="hidden" name="amount" value="10.00">
<input type="hidden" name="shopping_url" value="http://www.yourwebsite.com/shoppingpage.html">
<input type="hidden" name="return" value="http://www.yourwebsite.com/success.html">
Pagina
6
di
14
CodeProject: Introduction to PayPal for C#
-
ASP.NET developers. Free source code and programm
...
07/10/2009
http://www.codeproject.com/KB/aspnet/aspnet_c_aspnet.aspx?display=Print
<input type="hidden" name="cancel_return" value="http://www.yourwebsite.com/cancel.html">
<input type="hidden" name="bn" value="PP-ShopCartBF:x-click-but22.gif:NonHosted">
<input type="image" src="https://www.paypal.com/en_US/i/btn/x-click-but22.gif" border="0"
name="submit" alt="Make payments with PayPal - it's fast, free and secure!">
<img alt="" border="0" src="https://www.paypal.com/en_US/i/scr/pixel.gif" width="1"
height="1">
</form>
My Cart Item 2:
<form action="https://www.paypal.com/cgi-bin/webscr" method="post" target="paypal">
<input type="hidden" name="cmd" value="_cart">
<input type="hidden" name="add" value="1">
<input type="hidden" name="business" value="youremailaddress@yourdomain.com">
<input type="hidden" name="item_name" value="My Cart Item 2">
<input type="hidden" name="amount" value="5.00">
<input type="hidden" name="shipping" value="1.00">
<input type="hidden" name="shopping_url" value="http://www.yourwebsite.com/shoppingpage.html">
<input type="hidden" name="return" value="http://www.yourwebsite.com/success.html">
<input type="hidden" name="cancel_return" value="http://www.yourwebsite.com/cancel.html">
<input type="hidden" name="bn" value="PP-ShopCartBF:x-click-but22.gif:NonHosted">
<input type="image" src="https://www.paypal.com/en_US/i/btn/x-click-but22.gif" border="0"
name="submit" alt="Make payments with PayPal - it's fast, free and secure!">
<img alt="" border="0" src="https://www.paypal.com/en_US/i/scr/pixel.gif" width="1"
height="1">
</form>
View Cart:
<form action="https://www.paypal.com/cgi-bin/webscr" method="post" target="paypal">
<input type="hidden" name="cmd" value="_cart">
<input type="hidden" name="display" value="1">
<input type="hidden" name="business" value="youremailaddress@yourdomain.com">
<input type="hidden" name="shopping_url" value="http://www.yourwebsite.com/shoppingpage.html">
<input type="image" src="https://www.paypal.com/en_US/i/btn/view_cart_02.gif" name="submit"
alt="Make payments with PayPal - it's fast, free and secure!">
</form>
Recurring payments
Ifyouaresellingmonthlyserviceratherthanproduct,you'llbeinterestinginrecurringpaymentoptions
PayPalprovides.Again,it'splayingwithdifferentvariablesthathavedifferentmeaning.Let'ssayyouwish
toset3dayfreetrialafterwhichuserwillhavetopayyou$10.00permonthtokeepusingservice.
FollowingHTMLformshoulddothetrick:
<form action="https://www.paypal.com/cgi-bin/webscr" method="post">
<input type="hidden" name="cmd" value="_xclick-subscriptions"/>
<input type="hidden" name="business" value="youremailaddress@yourdomain.com"/>
<input type="hidden" name="item_name" value="Something"/>
<input type="submit" value="Subscribe!" />
<input type="hidden" name="a1" value="0"/>
<input type="hidden" name="p1" value="3"/>
<input type="hidden" name="t1" value="D"/>
<input type="hidden" name="a3" value="10.00"/>
<input type="hidden" name="p3" value="1"/>
<input type="hidden" name="t3" value="M"/>
<input type="hidden" name="src" value="1"/>
<input type="hidden" name="srt" value="0"/>
<input type="hidden" name="sra" value="1"/>
</form>
HTML variables & Resources
Afterreadingpreviousexampleyoumaybewonderingwhatcertainvariablesdo(a1?p1?srt?).Luckily,
PayPalprovides"
HTMLVariablesforWebsitePaymentsStandard
"pageonwhichyoucanreadaboutany
variablethatyouareinterestedin.
Also,anothergreatresource(towhichIwishsomeonepointedmewhenIfirststartedwithPPintegration)
is"
skier'sPayPalexamples
".You'llfindexampleforalmostanypaymentscenarioyoucanthinkof6so
insteadofclutteringthisarticlewithmoreexamples,I'llencourageyoutovisitthatpageshouldyouwishto
implementsomemoreadvancedPayPalHTMLform.
Pagina
7
di
14
CodeProject: Introduction to PayPal for C#
-
ASP.NET developers. Free source code and programm
...
07/10/2009
http://www.codeproject.com/KB/aspnet/aspnet_c_aspnet.aspx?display=Print
PostPayment processing
WhenyousetupyourPayPalHTMLformthefirstquestionyou'llprobablyaskis6
afteruserpayscanIhave
somepost6paymentsprocessinglogic?Itisnotsowithoutreason;therearenumerouspost6payments
scenarioswecanthinkof6fromsendingsimple"Thankyou"emailtoupdatingsitedatabaseandallowing
useraccesstorestrictedresourcesforwhichhepaid.Dependingonyourknowledgeanddesiredlevelof
robustnessforpost6processinglogic,therearethreewaysyoucango;andthegoodthingisyoucan
combinethem.
AutoReturn
AutoReturnisthesimplestPostPaymentprocessingsolutionthatyouhave6afteruserpaysheis
automatically*redirectedtospecifiedpageonyourwebsiteonwhichyoucandisplaysomeconfirmation
text.Ifyoucarefullywentthrough
"HTMLVariablesforWebsitePaymentsStandard"youknowthatyoucan
usereturnvariabletospecifyAutoReturnurlinHTMLform.IfyouwishtohavedefaultAutoReturnurl,
followthesesteps:
LogintoyourPremierorBusinessaccount1.
ClicktheProfilesubtab2.
ClickWebsitePaymentPreferencesintheSellingPreferencescolumn3.
ClicktheOnradiobuttonnexttotheAutoReturnlabel4.
EntertheURLwhereyouwantyouruserstoreturninthetextboxlabeledReturnURL5.
ClicktheSavebuttonatthebottomofthepage6.

Providing AutoReturl url in your PayPal profile
KnowthatifyouhavebothAutoReturnurlinyourprofileandprovidereturnvariableinyourHTMLform,
thereturnvariablewilloverwriteprofileurlvalue.
Now,whenyourreturnpageishit,you'llbegettingvariablesthatshouldallowyoutocustomizepage
displayandlogpayment:
tx6TransactionID•
st6Paymentstatus•
amt6Paymentamount•
cc6Currencycode•
Beforeclosingthissection,onemorething.ThereasonwhyI'veitalicizedword"automatically"infirst
sentenceis:ifuserusescreditcardtopayyou,hewon'tbeautomaticallyredirectedtoyourreturnurl;
he'llratherneedtoclickon"ReturntoMerchant"button.Ifthissoundsweirdtoyou
knowthatyou'renot
alone
;however,becauseoflegalissuesPayPalrefusedandstillrefusestochangethewaycreditcard
paymentsarehandledwithAutoReturn.
Pagina
8
di
14
CodeProject: Introduction to PayPal for C#
-
ASP.NET developers. Free source code and programm
...
07/10/2009
http://www.codeproject.com/KB/aspnet/aspnet_c_aspnet.aspx?display=Print
Payment Data Transfer

(PDT)
AfterlookingoverthelistofvariablesthatAutoReturnprovides,youprobablywondered6canIgetmore
detailsabouttransactionthatoccurred?ThisisexactlywherePDTjumpsin6buildingonAutoReturn
functionality.Forthatreason,you'llneedtoenablebothAutoReturnandthenPDTinyourprofile;hereis
howtodothat:
LogintoyourPremierorBusinessaccount1.
ClicktheProfilesubtab2.
ClickWebsitePaymentPreferencesintheSellingPreferencescolumn3.
ClicktheOnradiobuttonnexttotheAutoReturnlabel4.
EntertheURLofthescriptthatwillprocessthePDTHTTPrequestsentfromPayPal5.
UnderPaymentDataTransfer,clicktheOnradiobutton6.
ClickSave.7.
Afterfollowingthesesteps,youshouldgetPDTIdentityTokenthatisneededforqueryingPayPal.Ifyou
don'tcopy6pastetokenafterclickingSave,knowthatyoucanalwaysseeitinyourWebsitePayment
Preferences:

Payment Data Transfer and Identity Token
NowthatyouhaveIdentityTokenyoucanqueryPayPalformoredetailsafteryourreturnurlhasbeenhit.
HereishowthingsflowwhenutilizingPDT:
UserpaysandisredirectedtoyourAutoReturnpage,forexample:
http://www.yourdomain.com/Thanks.aspx?tx=[TransactionID]
1.
Fromcode6behindofThanks.aspxyou'llparsetxvalueandmakeHTTPPOSTto
https://www.paypal.com/cgi-bin/webscrwithfollowingparameters:cmd=_notify-
synch&tx=[TransactionID]&at=[PDTIdentityToken].(IfyouareusingSandboxyou'llofcourse
makeHTTPPOSTtohttps://www.sandbox.paypal.com/cgi-bin/webscr)
2.
PayPalwillrespondtoyourHTTPPOSTinfollowingformat:
SUCCESS
first_name=Firstname
last_name=Lastname
payment_status=Completed
payer_email=firstname%40lastname.com
payment_gross=50.00
mc_currency=USD
custom=Custom+value+you+passed+with+your+HTML+form
etc.
3.
Dowithdatawhateveryouwish4.
Pagina
9
di
14
CodeProject: Introduction to PayPal for C#
-
ASP.NET developers. Free source code and programm
...
07/10/2009
http://www.codeproject.com/KB/aspnet/aspnet_c_aspnet.aspx?display=Print
IncodeI'mattachingwitharticleunderPDTdirectoryyou'llfindexampleaspxandclassesthatwillhelp
yououtinfollowingpreviouslymentionedflow.
And,aswithAutoReturn,onenoticebeforeclosingsubject6takealookatcustomvariableinPayPal's
responsetoyourHTTPPOST.You'llprobablywanttoutilizethisvariableasitallowsyoutopasssome
informationfromyourpaymentpagetoyourpost6processingpagewithoutpresentingittouser.Toname
oneuse,insomeofmyPayPalimplementationsItrackuserwithit6whenhestartedpaymentprocessand
when/ifhefinishedit.
Instant Payment

Notification (IPN)
OnebigshortcomingofPDTisthatitisuser6drivenprocess,meaning6ifuserclosesbrowserafter
performingpaymentandbeforebeingredirectedtoyoursite6you'llloseopportunitytorunyourpost
processinglogic.That'swhyyouareadvisedtocombinePDTwithIPNforanyseriousintegrationwith
PayPal.
IPNisaback6endmechanismthatmakes
HTTPPOSTstoyourpage,notifyingyouofimportantevents.Itis
usednotonlyforPostPaymentprocessing,butalsoforthingsthatcomeafter,likehandlinguser
cancelationofrecurringpayments.
Beingback6endtechnologyitissomewhathardertoimplementanddebugthanPDT.Therearecoupleof
thingsyoushouldbeawareofbeforestartingtoimplementIPN:
IPNmessagescanbedelayedsometimes.Iknow,Iknow...thatbeatsword"Instant"inIPN,but
that'showthingsare.

ThereisknownhistoryofproblemswithIPNservice;twolatestincidentshappenedon
October2nd
2009
(2hourdelay)andon
September6th2009
(6hourdelay).

WheneveryouhaveproblemswithIPNbesuretocheck
Live Status
pageandseeifthereis
incident
notificationbeforediggingintodebuggingandchangingyourscript.Thereisalsosimilarpagefor
Sandbox Status
.

BeforebeingabletoreceiveIPNmessagesyou'llneedtoactivatethisservice;followthesesteps:
LogintoyourPremierorBusinessaccount1.
ClicktheProfilesubtab2.
ClickInstantPaymentNotificationintheSellingPreferencescolumn.3.
Clickthe'EditIPNSettings'buttontoupdateyoursettings.4.
Select'ReceiveIPNmessages(Enabled)andenterURLofyourIPNhandler.5.
ClickSave,andyoushouldgetamessagethatyouhavesuccessfullyactivatedIPN.6.

Activating Instant Payment Notification
Pagina
10
di
14
CodeProject: Introduction to PayPal for C#
-
ASP.NET developers. Free source code and progra
...
07/10/2009
http://www.codeproject.com/KB/aspnet/aspnet_c_aspnet.aspx?display=Print
AswithAutoReturn,youcanoverwriteIPNhandlerurlsetinprofileinindividualformsbyadding
notify_urlvariable(see
HTMLVariablesreference
).KnowthatthiswillinfluencenotonlyinitialIPN
messagebutallfuturemessagesrelatedtothattransaction(theywillallgotonotify_url).
TohandleIPNmessagesyou'llneedtocreateHTTPhandlersomewhereonyourwebsite.Whensignificant
eventoccurs(e.g.userperformspayment)followingflowtakesplace:
PayPalwillsendHTTPPOSTtoyourIPNhandlerwithnumberofvariables1.
AfterreceivingHTTPPOSTandparsingit,youneedtosubmitcompletebodyofthemessagebackto
https://www.paypal.com/cgi-bin/webscr(orhttps://www.sandbox.paypal.com/cgi-
bin/webscrforSandboxaccount).Whenyouaredoingthisbesuretosendmessagebackinexact
formatinwhichyoureceivedit;theonlythingyouareallowedtodoisaddingcmd=_notify-
validate.ThisisalldoneinordertoverifythatHTTPPOSTwasauthenticandsentfromPayPal
2.
PayPalwillrespondwitheitherVERIFIEDorINVALID.Afteryoureceivethisresponse,besureto
send
200OKtopreventadditionalattemptsfromPayPaltosendIPN.Ifyoudon'tcloseloopwith200OK,
PayPalwillstartresendingIPN(startingfrom4secondsanddoubling68seconds,16seconds,32
seconds...upto4days).
3.
IfyoureceivedINVALIDresponsethatcouldmeantwothings:
SomeonetriedtosendmaliciousmessagetoyourIPNhandler•
Yourimplementationisn'tperfect.•
Incaseofmaliciousmessageyou'reonyourown(logIP,takeappropriateaction),butforimperfect
implementationsvisitthis
IPNtroubleshootingtopic
onPayPalDeveloperforums;itisfullofusefultipsthat
shouldhelpyousolveINVALIDresponses.
Also,beforegoingonlinewithyourIPNhandler,besuretotestitthoroughlywith
InstantPayment
Notification(IPN)simulator
.AsIPNhandlerwillworkinbackgroundyou'llwanttotestitasmuchasyou
canbeforegoingliveandrelayingonitsprocessing.
Anotherthingyou'llwanttovisitifyouareimplementingIPNis
ScriptGenerator2page
...itcanquickly
generateIPNhandlerinlanguageofyourchoice.Funnything6theyaremissinggeneratorfor
ASP.NET/C#;
forthatcheckoutIPNdirectoryincode6archiveI'veattachedtothisarticleand
theseCodeSamples
.
Finally,onPayPalDeveloperCenterthereisthisnice
pagethatlistsmostoftheIPNandPDTvariables
.I'm
sayingmostbecausetherearesomevariablesmissingonit(checkcommentson
thispage
),butlistisfar
beyondbeinguseless.
PayPal API
Assaidinintroduction,mostdevelopers,eveniftheyhavenopreviousexperiencewithPayPal,start
directlywithAPI.Googlesearchbringsupeither
APIReference
or
SDKsandDownloads
pageandthen
browsingthrough
Documentation
starts.Idon'twanttosaythatthereissomethingwrongwithusing
PayPalAPIforpayments;Iwanttosaythatinmostofthecasesit'snotnecessarytogodownthatpath.
PayPalAPIismuchmorethanjustamechanismforpayment6ifyoulookatprovided
APIReference
page,
you'llseethattherearelotsofmethodsnottieddirectlyto"userperformingpayment".YoucanuseAPIto
browsethroughhistoryofyourtransactions,issuerefundorupdaterecurringpaymentsprofile.Sohowdo
youstartusingit?
Firstandforemost,you'llneedtoenableAPIaccessinyouraccount;followthesesteps:
LogintoyourPremierorBusiness1.
ClicktheProfilesubtab.2.
ClicktheAPIAccesslinkundertheAccountInformationheader.3.
ClickthelinkthatsaysRequestAPICredentials/ViewAPICertificate.4.
SelecteitherAPISignatureorAPICertificate.5.
Pagina
11
di
14
CodeProject: Introduction to PayPal for C#
-
ASP.NET developers. Free source code and progra
...
07/10/2009
http://www.codeproject.com/KB/aspnet/aspnet_c_aspnet.aspx?display=Print

Step 5 from activating API Access
IrecommendthatyouselectAPISignatureandexamplesthatfollowwillassumeyoumadethischoice.
ThereisnothingwrongwithselectingAPICertificate;Ijustfinditmoredemandingfromsetupperspective.
NowthatyouhavecredentialstomakeAPIcalls,howdoyouperformthem?Theapproachthatwillwork
equallywellwithallplatformsisto
downloadSDK
,target
appropriateAPIendpoint
,andstartmakingHTTP
callswitheitherName6ValuepairsorSOAP.
However,for.NETdevelopersIrecommenddifferentapproach.ConsideringthatVisualStudiohas
awesomeWSDLparser,IurgeyoutojustaddWebServiceReferenceto
hhttps://www.paypal.com/wsdl/PayPalSvc.wsdl
.Afterfewmomentsyou'llhaveup6to6dateclassreadyto
serveyouwithallbenefitsofstrongtyping6nobuildingofHTTPrequests,nocopy6pastingfieldnamesand
nocumbersomeparsingofresponses.YouhavesamethingavailableforSandboxaturl
https://www.sandbox.paypal.com/wsdl/PayPalSvc.wsdl
.
Express Checkout
ExpressCheckoutisthemostflexiblePayPalintegrationsolution.UserisredirectedtoPayPaljustfor
authenticationandconfirmationthathewantstopayforyourservicesandafterthateverythingisdoneon
yourwebsite;you'llmakecallstoPayPalAPIinbackground.Followingpicturedescribesprocess(taken
from
thispage
):
Pagina
12
di
14
CodeProject: Introduction to PayPal for C#
-
ASP.NET developers. Free source code and progra
...
07/10/2009
http://www.codeproject.com/KB/aspnet/aspnet_c_aspnet.aspx?display=Print

Express Checkout flow
You'lladdPayPalCheckoutbuttonthatinvokes
SetExpressCheckout
methodofPayPalAPIafteritis
clicked.
1.
Ifyouareinvokingthismethodforonetimepayment,it'llbevalidifyouincludeonlyrequired
fields.SettingNOSHIPPINGvariableto1isimportantifyouaresellingsomeonlineservice(it'll
helpyouskipShippinginfopage).
1.
Ifyouareinvokingthismethodinordertosetrecurringpayments,besuretoset
L_BILLINGTYPE0toRecurringPaymentsandL_BILLINGAGREEMENTDESCRIPTION0tovalid
descriptionofyourservice.
2.
SetExpressCheckoutwillreturn20chartoken
thatwilluniquelyidentifyyourtransaction.Thistoken
isvalidfor3hours.Afteryoureceiveit,redirectuserto
https://www.paypal.com/cgi6bin/webscr?
cmd=_express6checkout&token=[TOKEN]
(youcanguesswhatisurlforsandbox,right?)
2.
UserwillreviewpaymentinformationandifeverythingisOKenterhislogincredentials.Afterthis
PayPalwillredirecthimtourlyouspecifiedwithRETURNURLwhenyoucalledSetExpressCheckout
3.
WhenyourRETURNURLishityouneedtoinvoke
GetExpressCheckoutDetails
methodandseedetails
ofactualtransaction;verifythateverythingisinorder.
4.
Now,allthatisleftistocommittransaction.Dependingonwhatyoudidinstep1,therearetwo
thingsthatcanbedone.
5.
Foronetimepaymentsyou'lljustinvoke
DoExpressCheckoutPayment
andforwardappropriate
variables.
1.
Forrecurringpaymentsyou'llinvoke
CreateRecurringPayments
method.Itisrequiredthatyou
includeDESCfieldandmatchittovalueenteredinL_BILLINGAGREEMENTDESCRIPTION0when
youcalledSetExpressCheckout.
2.
Inanutshell6that'sit.Again,Iprovidedcodeexamplesthatfollowpreviouslyspecifiedflowinarchive
accompanyingthisarticle(underAPIdirectory).Ifyouwish,youcanalsouse
PayPalExpressCheckout
IntegrationWizard
forgeneratingreferencecode.
Direct Payment (Website Payments Pro)
Mostdevelopersaren'tawarethatPayPalplatformcanbeusedforjustCreditCardprocessing.Thispartof
PayPalAPIiscalledDirectPaymentandwhencombinedwithExpressCheckout(whichonlyservices
customerswithPayPalaccounts)yougetwhatisreferredas
WebsitePaymentsPro
onPayPalDeveloper
Center.
TobeabletocallmethodsthatarepartofDirectPayment(
DoDirectPayment
and
CreateRecurringPayments
)youfirstneedtosatisfysomeconditions:
HaveBusinessaccountthatisbasedinUS,UKorCanada1.
Obligethatyou'llimplementbothExpressCheckoutandDirectPaymentonyourwebsite2.
SubmitapplicationforWebsitePaymentsProthroughyourPayPalaccountandhaveitapproved3.
Paymonthlyfee(currently$30permonth)4.
Pagina
13
di
14
CodeProject: Introduction to PayPal for C#
-
ASP.NET developers. Free source code and progra
...
07/10/2009
http://www.codeproject.com/KB/aspnet/aspnet_c_aspnet.aspx?display=Print