Google Checkout API

XML API Developer's Guide

HTML API Developer's Guide

Using Google Analytics

Third-Party Conversion Tracking

Terms and Conditions

Sample Code

XML Schema

Developer's Cookbook

Checkout Button URL Generator

Acceptance logos

FAQ

Developer's Forum

Blog

Sample Code for GlobalAPIFunctions.asp

 

The GlobalAPIFunctions.asp library contains a set of functions that might be used to create more than one type of Google Checkout API request. This page automatically executes the setGlobalVariables function, which sets values, such as your merchant ID and merchant key, that are used throughout the Google Checkout sample code.

The GlobalAPIFunctions.asp includes functions that send and receive API requests as well as error handling functions that are used to create and handle different types of API requests.

This document includes an explanation of each function in the GlobalAPIFunctions.asp file. Each explanation includes a list of the parameters that are passed to the function, links to other functions that call the function, and links to the sample API implementations that call the function.

Note: To use these functions in your web application, you need to update the return values of the getMerchantId and getMerchantKey functions. These functions should return the merchant ID and merchant key, respectively, that Google has assigned to you.

Please refer to the CheckoutShoppingCartDemo.asp and OrderProcessingDemo.asp implementations to see sample usages of these functions.

Global Functions

setGlobalVariables
 
getMerchantId
 
getMerchantKey
 
sendRequest
 
createHttpBasicAuthentication
 
displayDiagnoseResponse
 
checkForError
 
errorHandler
 
logMessage
 

setGlobalVariables

Definition:

The setGlobalVariables function sets global variables that are accessed by functions throughout the Google Checkout ASP sample code. Note: This function executes when you include the GlobalAPIFunctions.asp file in your ASP code:

Code:

Function setGlobalVariables

    ' +++ CHANGE ME +++
    ' The logFilename variable identifies the file where messages
    ' will be logged. You can change the variable's value to change
    ' the log file's location.
    '
    ' WARNING: Please remember to change the file access permissions for
    ' this log file to ensure that its contents cannot be accessed through
    ' a web browser.
    logFilename = "log.out"

    ' +++ CHANGE ME +++
    ' The errorReportType variable specifies the
    ' manner in which errors will be reported. There are three
    ' possible values:
    ' 1 = Log the error message to the IIS log file
    ' 2 = Display the error message in the browser
    ' 3 = Log the error message to the IIS log file
    '         and also display it in the browser
    '
    ' Error messages are for debugging purposes only. When you are
    ' done with integration, change the errorReportType variable to 1
    ' so that no error messages will be displayed to the end user.
    errorReportType = "3"

    ' +++ CHANGE ME +++
    ' The attrcurrency variable specifies a default currency that
    ' is used in several places throughout the ASP libraries. You
    ' will need to update this value if you sell products in
    ' currencies other than U.S. dollars. The variable's value should
    ' be a three-letter ISO 4217 currency code:
    ' http://www.iso.org/en/prods-services/popstds/currencycodeslist.html
    '
    ' If you sell products in multiple currencies, you may need to
    ' implement a function that returns the appropriate currency code
    ' for each user.
    '
    ' Note: Google Checkout only supports USD at this time.
    attrCurrency = "USD"

    ' This constant identifies the location of the Google Checkout XML schema
    strXmlns = "http://checkout.google.com/schema/2"

    ' These two function calls set global variables for your
    ' merchant ID and merchant key
    strMerchantId = getMerchantId
    strMerchantKey = getMerchantKey

    ' These constants specify the URLs to which Google Checkout API requests
    ' are sent
    ' +++ CHANGE ME +++
    ' Please remember that your production systems must send requests to
    ' https://checkout.google.com
    baseUrl = "https://sandbox.google.com/checkout/cws/v2/Merchant/" & strMerchantId
    checkoutUrl = baseUrl & "/checkout"
    checkoutDiagnoseUrl = baseUrl & "/checkout/diagnose"
    requestUrl = baseUrl & "/request"
    requestDiagnoseUrl = baseUrl & "/request/diagnose"

    ' DomDocument Version
    strMsxmlDomDocument = "Msxml2.DOMDocument.3.0"

    ' XML Version and Encoding info
    strXmlVersionEncoding = "version=""1.0"" encoding=""UTF-8"""

    ' Cryptography COM Object
    Set cryptObj = Server.CreateObject("GCrypt.g_crypt.2")

End Function

getMerchantId

Definition:

The getMerchantId function returns your Google Checkout merchant ID. You will need to set the proper return value before this sample code will work for your site.

Functions that call getMerchantId:

setGlobalVariables

Code:

Function getMerchantId()

    ' +++ CHANGE ME +++
    ' Please set the return value to your Google Checkout merchant ID.
    ' This change is mandatory or this code will not work.

    getMerchantId = ""

End Function

getMerchantKey

Definition:

The getMerchantKey function returns your Google Checkout merchant key. You need to modify this function to securely fetch and return your merchant key from a location that cannot be reached through a web browser. For example, the function could extract the merchant key from a database or secure config file.

You will need to set the proper return value before this sample code will work for your site.

Functions that call getMerchantKey:

setGlobalVariables

Code:

Function getMerchantKey()

    Dim myMerchantKey

    ' +++ CHANGE ME +++
    ' Please set the return value to your Google Checkout merchant key.
    '
    ' WARNING: You need to modify this function to securely fetch and return
    ' your merchant key from a location that cannot be reached through
    ' a web browser. For example, the function could extract the
    ' merchant key from a database or secure config file.
    ' This change is mandatory or this code will not work.

    getMerchantKey = ""

End Function

sendRequest

Definition:

The sendRequest function verifies that you have provided values for all of the parameters needed to send a Google Checkout Checkout or Order Processing API request. It then logs the request, executes the request, and logs the response.

Parameters:

Parameter Name Definition
request Required. This parameter contains the XML document that will be submitted in a Google Checkout API request.
strPostUrl Required. This parameter contains the URL to which an API request should be submitted.

See Sample Usage:

OrderProcessingDemo

Functions that call sendRequest:

displayDiagnoseResponse

Code:

Function sendRequest(request, strPostUrl)

    ' Check for errors
    Dim strFunctionName
    Dim errorType

    strFunctionName = "sendRequest()"

    ' Check for missing parameters
    errorType = "MISSING_PARAM"
    checkForError errorType, strFunctionName, "request", request
    checkForError errorType, strFunctionName, "strPostUrl", strPostUrl
    checkForError errorType, strFunctionName, "strMerchantId", strMerchantId
    checkForError errorType, strFunctionName, "strMerchantKey", strMerchantKey

    ' Define objects used to send the HTTP request
    Dim xmlHttp
    Dim strAuthentication
    Dim bRequest

    ' Log the outgoing message
    logMessage logFilename, request

    ' Create the XMLHttpRequest object
    Set xmlHttp = Server.CreateObject("Msxml2.ServerXMLHTTP.3.0")

    ' The HTTP request method is POST
    xmlHttp.open "POST", strPostUrl, False

    ' Do NOT ignore Server SSL Cert Errors
    Const SXH_OPTION_IGNORE_SERVER_SSL_CERT_ERROR_FLAGS = 2
    Const SXH_SERVER_CERT_IGNORE_ALL_SERVER_ERRORS = 13056
    xmlHttp.setOption SXH_OPTION_IGNORE_SERVER_SSL_CERT_ERROR_FLAGS, _
        (xmlHttp.getOption(SXH_OPTION_IGNORE_SERVER_SSL_CERT_ERROR_FLAGS) - _
        SXH_SERVER_CERT_IGNORE_ALL_SERVER_ERRORS)

    bRequest = InStr(strPostUrl, "request")

    ' This "if" block, which sets the HTTP Basic Authentication scheme
    ' and HTTP headers, only executes for Order Processing API requests
    ' and for server-to-server Checkout API requests.
    If bRequest <> 0 Then

        ' Build HTTP Basic Authentication scheme
        strAuthentication = createHttpBasicAuthentication(strMerchantId, _
            strMerchantKey)

        ' Set HTTP headers
        xmlHttp.SetRequestHeader "Authorization", strAuthentication
        xmlHttp.SetRequestHeader "Content-Type", "application/xml"
        xmlHttp.SetRequestHeader "Accept", "application/xml"

    ' This block executes if this is a Checkout API request
    Else

        ' Set HTTP header
        xmlHttp.setRequestHeader "Content-Type", _
            "application/x-www-form-urlencoded"

    End If

    ' Transmit the request
    xmlHttp.send request

    ' Log the HTTP response
    logMessage logFilename, xmlHttp.responseText

    ' Return the response from the Google server
    sendRequest = xmlHttp.responseText

    ' Release the object used to send the request
    Set xmlHttp = Nothing

End Function

createHttpBasicAuthentication

Definition:

The createHttpBasicAuthentication creates a string in the format merchantId:merchantKey and then base64 encodes that string. This string is used to send Google Checkout API requests that are not Checkout API requests.

Functions that call createHttpBasicAuthentication:

sendRequest

Code:

Function createHttpBasicAuthentication(strMerchantId, strMerchantKey)

    Dim strCredential
    Dim b64credential
    Dim strAuthentication

    ' Create "userid:password"
    strCredential = strMerchantId & ":" & strMerchantKey

    ' Base64-encode "userid:password"
    b64credential = cryptObj.base64Encode(strCredential)

    ' Create "Basic dXNlcmlkOnBhc3N3b3Jk"
    strAuthentication = "Basic " & b64credential

    ' Return the HTTP Basic Authentication string
    createHttpBasicAuthentication = strAuthentication

End Function

displayDiagnoseResponse

Definition:

The displayDiagnoseResponse function is a debugging function that sends a Google Checkout API request and then evaluates the Google Checkout response to determine whether the request used valid XML. If the request did not use valid XML, the function displays an error message and a link where you can edit the XML and then try to validate it again.

Parameters:

Parameter Name Definition
request Required. This parameter contains the XML document that will be submitted in a Google Checkout API request.
strPostUrl Required. This parameter contains the URL to which an API request should be submitted.

xml Required. This parameter contains the unencoded XML document that will be submitted in a Google Checkout API request.
action Required. The action parameter indicates whether to display a link to a page where the user can debug an XML request.

See Sample Usage:

CheckoutShoppingCartDemo
OrderProcessingDemo

Code:

Function displayDiagnoseResponse(request, strPostUrl, xml, action)

    ' Define objects used to diagnose the API response
    Dim diagnoseResponse
    Dim bValidated
    Dim domResponse
    Dim strRootTag
    Dim nodeList
    Dim strResult

    ' Execute the API request and capture the Google Checkout server's response
    diagnoseResponse = sendRequest(request, strPostUrl)

    ' If the function finds that the request contained valid XML, the
    ' $validated variable will be set to true
    bValidated = false

    Set domResponse = Server.CreateObject("Msxml2.DOMDocument.3.0")
    domResponse.loadXml diagnoseResponse

    strRootTag = domResponse.documentElement.tagName

    ' This if-else block determines whether the API response indicates
    ' that the response contained invalid XML or if there was some other
    ' problem associated with the request, such as an invalid signature.
    If strRootTag = "diagnosis" Then
        Set nodeList = _
            domResponse.documentElement.getElementsByTagName("string")
        If nodeList.length > 0 Then
            strResult = nodeList(0).text
        Else
            bValidated = True
        End If
    Elseif strRootTag = "error" Then
        Set nodeList = _
            domResponse.documentElement.getElementsByTagName("error-message")
        strResult = nodeList(0).text
    ElseIf strRootTag = "request-received" Then
        bValidated = true
    End If

    ' If the request is invalid, print the reason that the request is
    ' invalid if the errorReportType variable indicates that errors
    ' should be displayed in the user's browser. Also display a link
    ' to a tool where the user can edit the XML request unless the
    ' validation request was submitted from that tool.
    If bValidated = False And (errorReportType = 2 Or errorReportType = 3) Then
        Response.write "<tr><td style=""color:red""><p>" & _
            "<span style=""text-align:center""><h2>" & _
            "This XML is NOT Validated!</h2></span></p>"
        Response.write "<p style=""text-align:left""><b>" & _
            Server.HTMLEncode(strResult) & "</b></p>"
        If action = "debug" Then
            Response.write "<p><form method=POST action=DebuggingTool.asp>"
            Response.write "<input type=""hidden"" name=""xml"" value=""" & _
                Server.HTMLEncode(xml) & """/>"
            Response.write "<input type=""hidden"" name=""toolType"" " & _
                "value=""Validate XML""/>"
            Response.write "<input type=""submit"" name=""Debug"" " & _
                "value=""Debug XML""/>"
            Response.write "</form></p></td></tr>"
        End If
    End If

    ' Return a Boolean value indicating whether the request
    ' contained valid XML.
    displayDiagnoseResponse = bValidated
End Function

checkForError

Definition:

The CheckForError function determines whether a parameter has a null value and prints the appropriate error message if the parameter does have a null value.

Parameters:

Parameter Name Definition
errorType Required. The errorType parameter identifies the type of error that the function is supposed to identify. This value is passed through to the errorHandler function.
strFunctionName Required. This parameter identifies the function that is being checked for an error.
strParamName Required. This parameter contains text that, in this sample code, is used to identify the parameter that is being checked for an error.
strParamValue Required. This parameter identifies the parameter value that is being checked for an error.

Functions that call checkForError:

changeOrderState
changeShippingInfo
createAddMerchantOrderNumber
createAlternateTaxRule
createAlternateTaxTable
createDefaultTaxRule
createItem
createMerchantCalculations
createSendBuyerMessage
createShipping
createTaxArea
createTaxTables
createUsPlaceArea
sendRequest

Code:

Function checkForError(errorType, strFunctionName, strParamName, strParamValue)
    If strParamValue = "" Then
        errorHandler errorType, strFunctionName, strParamName, strParamValue
    End If
End Function

errorHandler

Definition:

The errorHandler function returns the error message that should be logged for the specified errorType.

Functions that call errorHandler:

addAreas
changeOrderState
changeShippingInfo
checkForError
createAlternateTaxRule
createAlternateTaxTable
createCheckoutShoppingCart
createDefaultTaxRule
createShoppingCart

Code:

Function errorHandler(errorType, errorFunctionName, errorParamName, _
    errorParamValue)

    Dim errstr

    Select Case errorType

        ' MISSING_PARAM error
        ' A function call omits a required parameter.
        Case "MISSING_PARAM"
            errstr = "Error calling Function """ & errorFunctionName _
                & """: Missing Parameter: """ & errorParamName _
                & """ must be provided."

        ' MISSING_PARAM_NONE error
        ' A function call must have a value for at least one parameter.
        Case "MISSING_PARAM_NONE"
            errstr = "Error calling Function """ & errorFunctionName _
                & """: Missing Parameter: " _
                & "At least one parameter should be provided."

        ' INVALID_INPUT_ARRAY error
        ' AddAreas() function called with invalid value for
        ' $state_areas or $zip_areas parameter
        Case "INVALID_INPUT_ARRAY"
            errstr = "Error calling Function """ & errorFunctionName _
                & """: Invalid Input: """ & errorParamName _
                & """ should be an array."

        ' MISSING_CURRENCY error
        ' The attrCurrency value is empty.
        Case "MISSING_CURRENCY"
            errstr = "Error calling Function """ & errorFunctionName _
                & """: Missing Parameter: ""attrCurrency"" " _
                & "should be set when the ""elemAmount"" is set."

        ' MISSING_TRACKING error
        ' The ChangeShippingInfo() function in
        ' OrderProcessingAPIFunctions.asp is being called without
        ' specifying a tracking number even though a shipping
        ' carrier is specified.
        Case "MISSING_TRACKING"
            errstr = "Error calling Function """ & errorFunctionName _
                & """: Missing Parameter: ""elemTrackingNumber"" " _
                & "should be set when the ""elemCarrier"" is set."

        Case Else

    End Select

    ' Print the error message to the screen
    If (errorReportType = 2) Or (errorReportType = 3) Then

        Dim errstrHtml
        errstrHtml = errstr & "<br><br>"

        Response.write errstrHtml

    End If

    ' Write out the error message to the IIS Log File
    If (errorReportType = 1) Or (errorReportType = 3) Then

        Response.appendToLog errstr

    End If

    Response.End

End Function

logMessage

Definition:

The LogMessage function logs a message to a local file. The function also logs the time that the message is logged.

Parameters:

Parameter Name Definition
logFilename Required. This parameter identifies the file to which a message should be logged.
message Required. This parameter contains the message XML request to be logged.

See Sample Usage:

CheckoutShoppingCartDemo
ResponseHandler

Functions that call logMessage:

processMerchantCalculationCallback
sendNotificationAcknowledgment
sendRequest

Code:

Function logMessage(logFilename, message)

    Dim oFs
    Dim oTextFile

    ' Print out the notification message to a local file
    Set oFs = Server.createobject("Scripting.FileSystemObject")
    Const ioMode = 8
    Set oTextFile = oFs.openTextFile(logFilename, ioMode, True)
    oTextFile.writeLine now
    oTextFile.writeLine message
    oTextFile.close

    ' Free object
    Set oTextFile = Nothing
    Set oFS = Nothing

End Function