====== VB.NET ======
^ Please note |
| While we strive to ensure that all code we publish is accurate and well documented, the sample code given below is **user contributed code** and is provided as is, without any guarantees as to its correctness or valid operation. If you have any queries concerning this code and debugging or further development thereof, please contact a developer familiar with this particular language as we will be unable to assist you. |
===== Contributor =====
The following sample code was very kindly contributed by Jose Heitor, Owner [[http://www.heitorprojects.co.za|www.heitorprojects.co.za]]
===== Notes =====
- Insert an order into your database and get the orderid. This step is optional, but will help you keep track of your orders and abandoned carts (people who were trying ot order, but didn't go through with the process).
- Redirect to PayFast.
- When PayFast is done it will redirect to your site (return_url or cancel_url).
- You get a notification (ITN) with payment results.
- Validate that the notification is valid (security checks and validation checks)
- If notification is valid and status is COMPLETE, update the order you created in 1 (set some field like Paid to true). If you did not insert the order in 1, then you could just do the insert here (again, optional).
===== Files =====
==== checkout.aspx ====
Private Sub buttonPay_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles buttonPay.Click
Dim sRef As String
Dim sPayVars As String
' Create new order with goods currently in 'basket' and obtain unique order number
' (the new order will be initially set with Status = 'PROVISIONAL')
sRef = CreateOrder()
' prepare payment variables and append as query string parameters to payment redirection
If System.Configuration.ConfigurationSettings.AppSettings.Get("OpMode") = "Test" Then
sPayVars =
System.Configuration.ConfigurationSettings.AppSettings.Get("PayFast_Test_Payments") & "?" & _
"merchant_id=" & HttpUtility.UrlEncode(System.Configuration.ConfigurationSettings.AppSettings.Get("PayFast_Test_MerchantId")) & "&" & _
"merchant_key=" & HttpUtility.UrlEncode(System.Configuration.ConfigurationSettings.AppSettings.Get("PayFast_Test_MerchantKey")) & "&" & _
"return_url=" & HttpUtility.UrlEncode(System.Configuration.ConfigurationSettings.AppSettings.Get("PayFast_Test_ReturnURL")) & "&" & _
"cancel_url=" & HttpUtility.UrlEncode(System.Configuration.ConfigurationSettings.AppSettings.Get("PayFast_Test_CancelURL")) & "&" & _
"notify_url=" & HttpUtility.UrlEncode(System.Configuration.ConfigurationSettings.AppSettings.Get("PayFast_Test_NotifyURL")) & "&"
Else
sPayVars =
System.Configuration.ConfigurationSettings.AppSettings.Get("PayFast_Live_Payments") & "?" & _
"merchant_id=" & HttpUtility.UrlEncode(System.Configuration.ConfigurationSettings.AppSettings.Get("PayFast_Live_MerchantId")) & "&" & _
"merchant_key=" & HttpUtility.UrlEncode(System.Configuration.ConfigurationSettings.AppSettings.Get("PayFast_Live_MerchantKey")) & "&" & _
"return_url=" & HttpUtility.UrlEncode(System.Configuration.ConfigurationSettings.AppSettings.Get("PayFast_Live_ReturnURL")) & "&" & _
"cancel_url=" & HttpUtility.UrlEncode(System.Configuration.ConfigurationSettings.AppSettings.Get("PayFast_Live_CancelURL")) & "&" & _
"notify_url=" & HttpUtility.UrlEncode(System.Configuration.ConfigurationSettings.AppSettings.Get("PayFast_Live_NotifyURL")) & "&"
End If
sPayVars =
sPayVars & _
"name_first=" & HttpUtility.UrlEncode(Session.Item("FirstName")) & "&" & _
"name_last=" & HttpUtility.UrlEncode(Session.Item("LastName")) & "&" & _
"email_address=" & HttpUtility.UrlEncode(Session.Item("Email")) & "&" & _
"m_payment_id=" & HttpUtility.UrlEncode(sRef) & "&" & _
"amount=" & HttpUtility.UrlEncode(Session.Item("TotalDue")) & "&" & _
"item_name=" & HttpUtility.UrlEncode("Online Sale - " & sRef) & "&" & _
"item_description=" & HttpUtility.UrlEncode(Session.Item("SaleDescription"))
' Redirect the client
Session.Item("LastRequest") = "Paying"
Response.Redirect(sPayVars)
End Sub
==== return.aspx ====
This page is specified by the //return_url// field in the original form post to PayFast.
Just thank the user and tell them you are processing their order (should already be done or take a few more seconds with ITN)
==== cancel.aspx ====
This page is specified by the //cancel_url// field in the original form post to PayFast.
Just thank the user and tell them that they cancelled the order (encourage them to email you if they have problems paying :)
==== notify.aspx ====
This page is specified by the //notify_url// field in the original form post to PayFast.
Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
' This page never posts back
If Not Page.IsPostBack Then
Dim bOrderValid As Boolean = False
Dim sLogError As String = ""
' Validate payment
Dim orderId As String
Dim processorOrderId As String
Dim strPostedVariables As String
Dim arrPostedVariables As New System.Collections.Specialized.NameValueCollection
Try
' Get the posted variables. Exclude the signature (it must be excluded when we hash and also when we validate)
Dim req As System.Collections.Specialized.NameValueCollection = Request.Form
Dim key, value As String
Dim i As Integer
For i = 0 To req.Count - 1
key = req.Keys(i)
value = req(i)
If key <> "signature" Then
strPostedVariables = strPostedVariables & key & "=" & HttpUtility.UrlEncode(value) & "&"
arrPostedVariables.Add(key, value)
End If
Next
' Remove the last &
strPostedVariables = strPostedVariables.TrimEnd("&"c)
orderId = Request.Form("m_payment_id")
processorOrderId = Request.Form("pf_payment_id")
' Are we testing or making live payments
Dim query As System.Collections.Specialized.NameValueCollection = Me.Request.QueryString
Dim site, merchant_id, paymentMode As String
Dim arrStr() As String
If System.Configuration.ConfigurationSettings.AppSettings.Get("OpMode") = "Test" Then
paymentMode = "Test"
site = System.Configuration.ConfigurationSettings.AppSettings.Get("PayFast_Test_Validations")
merchant_id = System.Configuration.ConfigurationSettings.AppSettings.Get("PayFast_Test_MerchantId")
arrStr = Split(System.Configuration.ConfigurationSettings.AppSettings.Get("PayFast_Test_Servers"), ",")
Else
paymentMode = "Live"
site = System.Configuration.ConfigurationSettings.AppSettings.Get("PayFast_Live_Validations")
merchant_id = System.Configuration.ConfigurationSettings.AppSettings.Get("PayFast_Live_MerchantId")
arrStr = Split(System.Configuration.ConfigurationSettings.AppSettings.Get("PayFast_Live_Servers"), ",")
End If
' Get the posted signature from the form
Dim postedSignature As String = Request.Form("signature")
If postedSignature = "" Then
sLogError = "Warning: " & orderId & " :: " & processorOrderId & " :: " & "Missing Signature."
GoTo Bail
End If
' Verify that we are the intended merchant
If arrPostedVariables("merchant_id") <> merchant_id Then
sLogError = "Warning: " & orderId & " :: " & processorOrderId & " :: " & "Invalid merchantId."
GoTo Bail
End If
' Check if this is a legitimate request from the payment processor
Dim sServer As String = CStr(Request.UserHostAddress)
Dim bIp As Boolean = False
For i = LBound(arrStr) To UBound(arrStr)
If sServer = arrStr(i) Then
bIp = True
Exit For
End If
Next
If Not bIp Then
sLogError = "Warning: " & orderId & " :: " & processorOrderId & " :: " & "Invalid notification source."
GoTo Bail
End If
' Check if order already processed
If CheckOrderStatus(orderId) <> "PROVISIONAL" Then
sLogError = "Warning: " & orderId & " :: " & processorOrderId & " :: " & "Order already processed."
GoTo Bail
End If
' The request is legitimate. Post back to payment processor to validate the data received
Dim wc As System.Net.WebClient
Try
wc = New System.Net.WebClient
Dim arrResponse As Byte() = wc.UploadValues(site, "POST", arrPostedVariables)
Dim result As String = System.Text.Encoding.ASCII.GetString(arrResponse)
' Get the response and replace the line breaks with spaces
result = result.Replace(vbCrLf, " ").Replace(vbCr, " ").Replace(vbLf, " ")
' Was the data valid?
If Not result.StartsWith("VALID") Then
sLogError = "Warning: " & orderId & " :: " & processorOrderId & " :: " & "Validation failed."
GoTo Bail
End If
Catch ex As Exception
sLogError = "Error (PayFastNotify_Page_Load): " & ex.Source & " :: " & ex.Message & vbCrLf & ex.StackTrace
Finally
wc.Dispose()
If sLogError <> "" Then
GoTo Bail
End If
End Try
Catch ex As Exception
sLogError = "Error (PayFastNotify_Page_Load): " & ex.Source & " :: " & ex.Message & vbCrLf & ex.StackTrace
GoTo Bail
End Try
' Confirm order
' Add some parameters to the arrPostedVariables collection to pass to the ConfirmOrder Sub
arrPostedVariables.Add("signature", Request.Form("signature").ToString)
arrPostedVariables.Add("pf_server_ip", CStr(Request.UserHostAddress))
ConfirmOrder(orderId, arrPostedVariables)
Exit Sub
Bail:
' Log any errors or warnings to the database
UpdateLog(sErrorLog)
End If
End Sub
==== web.config ====