Using PayPal IPNs
asp.net using VB
On your site you want to accept payment using PayPal (credit card or a PayPal account). The code below will be executed as soon as your customer has successfully paid. Whether your customer returns to your site or not doesn’t matter. The value in the html form below will take your customer to a thankyou.aspx page after he clicks the “Return to merchant” button on PayPal after he’s paid.
This bit of html goes into your payment page eg payments.aspx. Here you would have a summary of what it is he’s paying for etc.
The asp literals are set in the payments.aspx.vb page.
[B] ////This would hold the member ID or customer ID etc[/B]The process_payment.aspx has just this
<%@ Page CodeBehind=“process_payment.aspx.vb” Language=“vb” AutoEventWireup=“false” Inherits=“mynamespace.process_payment” %>
It is not displayed to the customer at all but just runs as a result of the PayPal IPN process.
Below is the process_payment.aspx.vb page.
Imports System.Net
Imports System.IO
Public Class process_payment
Inherits System.Web.UI.Page
Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
'Put user code to initialize the page here
'// Step 1a: Modify the POST string.
Dim formPostData As String = "cmd=_notify-validate"
Dim postValue As String
Dim postKey As String
Dim postByteArray As Byte()
Dim responseArray As Byte()
Dim PayPalResponse As String
Dim MemID As String = Request.Form("item_number") [B]'//This comes from the <input id="item_number" type="hidden" value="<asp:Literal" name="item_number" runat="server"> line of html above which would have the customer ID or member ID etc.[/B]
For Each postKey In Request.Form
postValue = Encode(Request.Form(postKey))
formPostData += String.Format("&{0}={1}", postKey, postValue)
Next
'// Step 1b: POST the data back to PayPal.
Dim client As New System.Net.WebClient
client.Headers.Add("Content-Type", "application/x-www-form-urlencoded")
postByteArray = System.Text.Encoding.ASCII.GetBytes(formPostData)
responseArray = client.UploadData("https://www.paypal.com/cgi-bin/webscr", "POST", postByteArray)
PayPalResponse = System.Text.Encoding.ASCII.GetString(responseArray)
''// Step 1c: Process the response from PayPal.
Select Case PayPalResponse
Case "VERIFIED"
'// code here to update your database, send confirmatory email to customer and so on. You have the MemID value from above so you know which customer it is.
Case Else
'// Possible fraud. Log for investigation.
End Select
End Sub
Private Function Encode(ByVal OldValue as String) As String
' This helper method encodes a string correctly for an HTTP POST
Dim newValue As String
newValue = OldValue.Replace("\", "")
newValue = System.Web.HttpUtility.UrlEncode(newValue)
newValue = newValue.Replace("%2f", "/")
Return newValue
End Function
End Class