Application key passed is invalid

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • OliasOfSunhillow
    Junior Member
    • Feb 2013
    • 57

    #1

    Application key passed is invalid

    Hi

    I have got the Login working fine using Python but when I call up GetEventypes using the sample python code provided here, it fails with Application key passed is invalid. This seems odd as the App key worked fine with the login. If anyone has any suggestions I would be grateful.
  • Guest

    #2
    Hi the login process does not require a session token, however all other calls will. Therefore what this means is that once you login successfully you need to grab that Session token and use it with your Key (live or delayed) to make any calls.

    Here is the code to login and grab session token (SSOID).
    Code:
      Public Function LoginSessionBetfair(username As String, password As String) As String
            'OK SO THIS FUNCTION TAKES THE USERNAME AND PWD AND RETURNS A SESSION ID (SSOID)
    
            Dim ssoid As String = [String].Empty
            Dim info As String()
            Dim sessToken As String = ""
    
            Try
                Dim uri As String = String.Format("https://identitysso.betfair.com/api/login?username={0}&password={1}&login=true&redirectMethod=POST&product=home.betfair.int&url=https://www.betfair.com/", username, password)
                Dim myRequest As HttpWebRequest = DirectCast(WebRequest.Create(uri), HttpWebRequest)
                myRequest.Method = "POST"
                myRequest.Timeout = 5000
    
                Dim thePage As WebResponse = myRequest.GetResponse()
                info = thePage.Headers.GetValues("Set-Cookie")
    
                Dim i As Integer = 0
                While ssoid = [String].Empty AndAlso i < info.Length
                    If info(i).Contains("ssoid=") Then
                        ssoid = info(i)
                    End If
                    i += 1
                End While
                'This returns text like ssoid=KY8FBhBU26jP3M9EDE4NogOm9XfH5xJDR49BlJI0lac=; Domain=.betfair.com; Path=/
                sessToken = ssoid.Replace("ssoid=", "") 'Dump front string
                sessToken = sessToken.Replace("; Domain=.betfair.com; Path=/", "") 'dump rear string
    
                If sessToken.Length <> 0 Then
                    frmBetBot.txtLog.Text = ("Login successful")
                    frmBetBot.tsbBetfairConnect.Image = My.Resources.star_green
                    myBFdata.Connection = ENUM_BETFAIR_CONNECTION.Connected
                Else
                    frmBetBot.txtErrorLog.Text = ("Login Problem")
                    frmBetBot.tsbBetfairConnect.Image = My.Resources.star_red
                    myBFdata.Connection = ENUM_BETFAIR_CONNECTION.NotConnected
                End If
    
            Catch ex As System.Exception
                frmBetBot.txtErrorLog.Text = ("Login Problem" & vbCrLf & ex.Message)
                frmBetBot.tsbBetfairConnect.Image = My.Resources.star_red
                myBFdata.Connection = ENUM_BETFAIR_CONNECTION.NotConnected
    
            End Try
            Return sessToken '~~> Should work ok if Login a success
        End Function 'Session Token and Login
    Here is code to get ListEvents where we are passing in Application Key (myBFdata.sKeyInUse) and Session Token (myBFdata.sSessionID)

    Code:
        '##############################################################################################
        '###  LIST EVENTS BETFAIR     WORKS WELL BUT I RARELY USE THIS                              ###
        '##############################################################################################
        Public Sub ListEventsForBetfair(Optional ByVal bWriteToLogBox As Boolean = False)
    
        Dim client As JsonRpcClient = Nothing  
            frmBetBot.clbListBetfairEvents.Items.Clear()
            clientBF = New JsonRpcClient(myBFdata.URL, myBFdata.sKeyInUse, myBFdata.sSessionID)
    
            Try
                Dim marketFilterBF = New MarketFilter()
                Dim eventTypesBF = clientBF.listEventTypes(marketFilterBF)
    
                'Dim eventypeIds As ISet(Of String) = New HashSet(Of String)()              'RECORDS 
    
                For Each item As EventTypeResult In eventTypesBF
                    If item.EventType.Name.Equals("Horse Racing") Then
                        '    txtLog.Text = txtLog.Text & vbCrLf & ("Found event type for Horse Racing: " & JsonConvert.Serialize(Of EventTypeResult)(eventType))
                        '    eventypeIds.Add(eventType.EventType.Id)
                        frmBetBot.clbListBetfairEvents.Items.Add(item.EventType.Name & " (ID=" & item.EventType.Id & ")", True)
                    Else
                        frmBetBot.clbListBetfairEvents.Items.Add(item.EventType.Name & " (ID=" & item.EventType.Id & ")", False)
                    End If
                    If bWriteToLogBox = True Then frmBetBot.txtLog.Text = frmBetBot.txtLog.Text & vbCrLf & item.EventType.Name & " (ID=" & item.EventType.Id & ")"
                Next item
                myBFdata.Connection = ENUM_BETFAIR_CONNECTION.Connected
                frmBetBot.tsbBetfairConnect.Image = My.Resources.star_green
    
            Catch ex As System.Exception
                'The session token passed is invalid
                frmBetBot.txtErrorLog.Text = "Market Filter Problem - Not connected"
                myBFdata.Connection = ENUM_BETFAIR_CONNECTION.Connected
                frmBetBot.tsbBetfairConnect.Image = My.Resources.star_green
            End Try
        End Sub

    Comment

    • OliasOfSunhillow
      Junior Member
      • Feb 2013
      • 57

      #3
      Thanks for getting back to me. Here is my Python code lifted from the sample on here. Yes you are correct the app code is not needed for login. My code however fails at the Print 'Exception from API-NG' line in GetEventypes despite the fact that I am using the app code I generated via the visualizer on here


      #!/usr/bin/env python

      #A simple program.

      import requests

      import urllib
      import urllib.request
      import urllib.error
      import json
      import datetime
      import sys

      def callAping(jsonrpc_req):
      try:
      req = urllib.request.Request(url, jsonrpc_req.encode('utf-8'), headers)
      response = urllib.request.urlopen(req)
      jsonResponse = response.read()
      return jsonResponse.decode('utf-8')
      except urllib.error.URLError as e:
      print (e.reason)
      print ('Oops no service available at ' + str(url))
      exit()
      except urllib.error.HTTPError:
      print ('Oops not a valid operation from the service ' + str(url))
      exit()

      ################################################

      def getEventTypes():
      event_type_req = '{"jsonrpc": "2.0", "method": "SportsAPING/v1.0/listEventTypes", "params": {"filter":{ }}, "id": 1}'
      print ('Calling listEventTypes to get event Type ID')
      print (headers)
      print (' done')
      eventTypesResponse = callAping(event_type_req)
      eventTypeLoads = json.loads(eventTypesResponse)

      try:
      eventTypeResults = eventTypeLoads['result']
      return eventTypeResults
      except:
      print ('Exception from API-NG' + str(eventTypeLoads['error']))
      exit()

      ################################################

      appKey = 'xxxxx'

      payload = 'username=xxxxx&password=xxxxxxxx'
      headers = {'X-Application': appKey, 'Content-Type': 'application/x-www-form-urlencoded'}

      resp = requests.post('https://identitysso.betfair.com/api/certlogin', data=payload, cert=('client-2048.crt', 'client-2048.key'), headers=headers)

      if resp.status_code == 200:
      resp_json = resp.json()
      print ("login OK")

      sessionToken = resp_json['sessionToken']

      else:
      print ("Request failed.")


      url = "https://api.betfair.com/exchange/betting/json-rpc/v1"

      headers = {'X-Application': appKey, 'X-Authentication': sessionToken, 'content-type': 'application/json'}

      eventTypesResult = getEventTypes()

      #horseRacingEventTypeID = getEventTypeIDForEventTypeName(eventTypesResult, 'Horse Racing')

      #print ('Eventype Id for Horse Racing is :' + str(horseRacingEventTypeID))

      Comment

      • OliasOfSunhillow
        Junior Member
        • Feb 2013
        • 57

        #4
        Manage to solve it myself, it was one of those Homer Simpson mistakes. I was using the app key ID and not the Appkey code. I suppose this is easily done as the only thing displayed in the visualizer is the ID, you have to click on it to get the codes. I wonder if others have fallen foul of this simple error. Oh well onwards and upwards

        Comment

        Working...
        X