Sample code: VB.NET

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 the contributor or a developer familiar with this particular language as we will be unable to assist you.

The sample code was kindly contributed by Jose Heitor.


  1. 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 to order, but didn’t go through with the process).
  2. Redirect to PayFast.
  3. When PayFast is done it will redirect to your site (return_url or cancel_url).
  4. You get a notification (ITN) with payment results.
  5. Validate that the notification is valid (security checks and validation checks)
  6. 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).



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).


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 :)


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
            ' 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
            ' 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"), ",")
                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
            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
                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
                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
        ' Log any errors or warnings to the database
    End If
End Sub


    <add key="OpMode" value="Test"></add>   
    <add key="PayFast_Live_Payments" value=""></add>
    <add key="PayFast_Live_Validations" value=""></add>
    <add key="PayFast_Live_Servers" value=","></add>   
    <add key="PayFast_Test_ReturnURL" value=""></add>
    <add key="PayFast_Test_CancelURL" value=""></add>
    <add key="PayFast_Test_NotifyURL" value=""></add>
    <add key="PayFast_Test_MerchantId" value="10000100"></add>
    <add key="PayFast_Test_MerchantKey" value="46f0cd694581a"></add>
    <add key="PayFast_Test_Payments" value=""></add>
    <add key="PayFast_Test_Validations" value=""></add>
    <add key="PayFast_Test_Servers" value=","></add>