Table of Contents
VB.NET
The following sample code was very kindly contributed by Jose Heitor, Owner 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
- 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.
- notify.aspx
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
- web.config
<appSettings> <!-- ############################################################################## # INSTRUCTIONS # # - Modify the fields below under "LIVE settings" # - Enter your Merchant ID and Merchant Key from PayFast # - Modify the URLs to be correct for your site # - Modify the fields below under "TEST settings" # - Modify the URLs to be correct for your site ############################################################################## --> <!-- ############################################################################## # Whether to use "Live" (Production) or "Test" (Sandbox) mode ############################################################################## --> <add key="OpMode" value="Test" /> <!-- ############################################################################## # LIVE settings ############################################################################## --> <!-- MODIFY these fields with your LIVE settings <add key="PayFast_Live_MerchantId" value="##YOUR_MERCHANT_ID##" /> <add key="PayFast_Live_MerchantKey" value="##YOUR_MERCHANT_KEY##" /> <add key="PayFast_Live_ReturnURL" value="http://www.mywebsite.com/confirm.aspx" /> <add key="PayFast_Live_CancelURL" value="http://www.mywebsite.com/cancel.aspx" /> <add key="PayFast_Live_NotifyURL" value="http://www.mywebsite.com/notify.aspx" /> <!-- Leave these fields as they are --> <add key="PayFast_Live_Payments" value="https://www.payfast.co.za/eng/process" /> <add key="PayFast_Live_Validations" value="https://www.payfast.co.za/eng/query/validate" /> <add key="PayFast_Live_Servers" value="196.33.227.224,196.33.27.225" /> <!-- ############################################################################## # TEST settings ############################################################################## --> <!-- MODIFY the fields to the correct urls for your situation <add key="PayFast_Test_ReturnURL" value="http://www.mywebsite.com/confirm.aspx" /> <add key="PayFast_Test_CancelURL" value="http://www.mywebsite.com/cancel.aspx" /> <add key="PayFast_Test_NotifyURL" value="http://www.mywebsite.com/notify.aspx" /> <!-- Leave these fields as they are --> <add key="PayFast_Test_MerchantId" value="10000100" /> <add key="PayFast_Test_MerchantKey" value="46f0cd694581a" /> <add key="PayFast_Test_Payments" value="https://sandbox.payfast.co.za/eng/process" /> <add key="PayFast_Test_Validations" value="https://sandbox.payfast.co.za/eng/query/validate" /> <add key="PayFast_Test_Servers" value="196.33.227.224,196.33.27.225" /> </appSettings>
Trace: » c_sharp.net » payfast_vouchers » vb.net