PHP - problem with sample script

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • pukkafish
    Junior Member
    • Mar 2014
    • 10

    #1

    PHP - problem with sample script

    Hi,

    I've managed to create an app and I can get my token, but run into problem when trying the sample codes using PHP.

    1-

    PHP Code:
    <?php

    ob_start
    ();
    $sessionToken getACookie();
    ob_end_clean();

    echo 
    $sessionToken;

    function 
    getACookie(){
        
        
    $loginEndpoint"https://identitysso.betfair.com/api/login";
        
        
    $cookie "";
        
        
    $username "myusername";
        
    $password "mypassword";

        
        
    $login "true";
        
    $redirectmethod "POST";
        
    $product "home.betfair.int";
        
    $url "https://www.betfair.com/";

        
    $fields = array
            (
                
    'username' => urlencode($username),
                
    'password' => urlencode($password),
                
    'login' => urlencode($login),
                
    'redirectmethod' => urlencode($redirectmethod),
                
    'product' => urlencode($product),
                
    'url' => urlencode($url)
            );

        
    //open connection
        
    $ch curl_init($loginEndpoint);
        
    //url-ify the data for the POST
        
    $counter 0;
        
    $fields_string "&";
        
        foreach(
    $fields as $key=>$value
            { 
                if (
    $counter 0
                    {
                        
    $fields_string .= '&';
                    }
                
    $fields_string .= $key.'='.$value
                
    $counter++;
            }

        
    rtrim($fields_string,'&');

        
    curl_setopt($chCURLOPT_URL$loginEndpoint);
        
    curl_setopt($chCURLOPT_SSL_VERIFYPEERfalse);
        
    curl_setopt($chCURLOPT_POSTtrue);
        
    curl_setopt($chCURLOPT_POSTFIELDS,$fields_string);
        
    curl_setopt($chCURLOPT_HEADERtrue);  // DO  RETURN HTTP HEADERS
        
    curl_setopt($chCURLOPT_RETURNTRANSFERtrue);  // DO RETURN THE CONTENTS OF THE CALL

        //execute post

        
    $result curl_exec($ch);


        echo 
    $result;

        if(
    $result == false
            {
                    echo 
    'Curl error: ' curl_error($ch);
            } 
        
        else 
            {
                
    $temp explode(";"$result);
                
    $result $temp[0];
                
                
    $end strlen($result);
                
    $start strpos($result'ssoid=');
                
    $start $start 6;
            
                
    $cookie substr($result$start$end);
                            
            }
        
    curl_close($ch);
        
        return 
    $cookie;
    }

    function 
    sportsApingRequest($appKey$sessionToken$operation$params)
    {
        
    $ch curl_init();
        
    curl_setopt($chCURLOPT_URL"https://beta-api.betfair.com/rest/v1/$operation/");
        
    curl_setopt($chCURLOPT_POST1);
        
    curl_setopt($chCURLOPT_RETURNTRANSFER1);
        
    curl_setopt($chCURLOPT_HTTPHEADER, array(
            
    'X-Application: ' $appKey,
            
    'X-Authentication: ' $sessionToken,
            
    'Accept: application/json',
            
    'Content-Type: application/json'
        
    ));
     
        
    curl_setopt($chCURLOPT_POSTFIELDS$params);
     
        
    $response json_decode(curl_exec($ch));
     
        
    $http_status curl_getinfo($chCURLINFO_HTTP_CODE);
        
    curl_close($ch);
     
        if (
    $http_status == 200) {
            return 
    $response;
        } else {
            echo 
    'Call to api-ng failed: ' "\n";
            echo  
    'Response: ' json_encode($response);
            exit(-
    1);
        }
    }



     
    function 
    getAllEventTypes($appKey$sessionToken)
    {
     
        
    $jsonResponse sportsApingRequest($appKey$sessionToken'listEventTypes''{"filter":{}}');
     
        return 
    $jsonResponse[0]->result;
    }
     
    function 
    extractHorseRacingEventTypeId($allEventTypes)
    {
        foreach (
    $allEventTypes as $eventType) {
            if (
    $eventType->eventType->name == 'Horse Racing') {
                return 
    $eventType->eventType->id;
            }
        }
    }




    //echo getAllEventTypes('Yr69P8uXBTYjI2S7', $cookie);
    echo getAllEventTypes('aK4fhFsx3z0bswsq'$cookie);


    echo 
    extractHorseRacingEventTypeId(getAllEventTypes('aK4fhFsx3z0bswsq'$cookie));


    ?>

    I have the following result:

    GsNSk/Y5OeQ064mwpZYBqpbCJVbSnJp5v7/89cLz78s=
    Call to api-ng failed:
    Response: null

    2- with this one:

    PHP Code:
    <?php

    ob_start
    ();
    $sessionToken getACookie();
    ob_end_clean();

    echo 
    $sessionToken;

    function 
    getACookie(){
        
        
    $loginEndpoint"https://identitysso.betfair.com/api/login";
        
        
    $cookie "";
        
        
    $username "myusername";
        
    $password "mypassword";

        
        
    $login "true";
        
    $redirectmethod "POST";
        
    $product "home.betfair.int";
        
    $url "https://www.betfair.com/";

        
    $fields = array
            (
                
    'username' => urlencode($username),
                
    'password' => urlencode($password),
                
    'login' => urlencode($login),
                
    'redirectmethod' => urlencode($redirectmethod),
                
    'product' => urlencode($product),
                
    'url' => urlencode($url)
            );

        
    //open connection
        
    $ch curl_init($loginEndpoint);
        
    //url-ify the data for the POST
        
    $counter 0;
        
    $fields_string "&";
        
        foreach(
    $fields as $key=>$value
            { 
                if (
    $counter 0
                    {
                        
    $fields_string .= '&';
                    }
                
    $fields_string .= $key.'='.$value
                
    $counter++;
            }

        
    rtrim($fields_string,'&');

        
    curl_setopt($chCURLOPT_URL$loginEndpoint);
        
    curl_setopt($chCURLOPT_SSL_VERIFYPEERfalse);
        
    curl_setopt($chCURLOPT_POSTtrue);
        
    curl_setopt($chCURLOPT_POSTFIELDS,$fields_string);
        
    curl_setopt($chCURLOPT_HEADERtrue);  // DO  RETURN HTTP HEADERS
        
    curl_setopt($chCURLOPT_RETURNTRANSFERtrue);  // DO RETURN THE CONTENTS OF THE CALL

        //execute post

        
    $result curl_exec($ch);


        echo 
    $result;

        if(
    $result == false
            {
                    echo 
    'Curl error: ' curl_error($ch);
            } 
        
        else 
            {
                
    $temp explode(";"$result);
                
    $result $temp[0];
                
                
    $end strlen($result);
                
    $start strpos($result'ssoid=');
                
    $start $start 6;
            
                
    $cookie substr($result$start$end);
                            
            }
        
    curl_close($ch);
        
        return 
    $cookie;
    }

    function 
    sportsApingRequest($appKey$sessionToken$operation$params)
    {
        
    $ch curl_init();
        
    curl_setopt($chCURLOPT_URL"https://beta-api.betfair.com/json-rpc");
        
    curl_setopt($chCURLOPT_POST1);
        
    curl_setopt($chCURLOPT_RETURNTRANSFER1);
        
    curl_setopt($chCURLOPT_HTTPHEADER, array(
            
    'X-Application: ' $appKey,
            
    'X-Authentication: ' $sessionToken,
            
    'Accept: application/json',
            
    'Content-Type: application/json'
        
    ));
     
        
    $postData =
            
    '[{ "jsonrpc": "2.0", "method": "SportsAPING/v1.0/' $operation '", "params" :' $params ', "id": 1}]';
     
        
        
    curl_setopt($chCURLOPT_POSTFIELDS$postData);
     
        
    $response json_decode(curl_exec($ch));
        
    curl_close($ch);
     
        if (isset(
    $response[0]->error)) {
            echo 
    'Call to api-ng failed: ' "\n";
            echo  
    'Response: ' json_encode($response);
            exit(-
    1);
        } else {
            return 
    $response;
        }
     
    }



     
    function 
    getAllEventTypes($appKey$sessionToken)
    {
     
        
    $jsonResponse sportsApingRequest($appKey$sessionToken'listEventTypes''{"filter":{}}');

        return 
    $jsonResponse;
    }
     
    function 
    extractHorseRacingEventTypeId($allEventTypes)
    {
        foreach (
    $allEventTypes as $eventType) {
            if (
    $eventType->eventType->name == 'Horse Racing') {
                return 
    $eventType->eventType->id;
            }
        }
    }


    echo 
    extractHorseRacingEventTypeId(getAllEventTypes('aK4fhFsx3z0bswsq',$cookie));

    ?>
    The result is:

    vWVGgzautsE2/QFoaaDGRvbYJAWJQqMF6nRoPh0bS04=
    Warning: Invalid argument supplied for foreach() in /homepages/16/d408779085/htdocs/pukkanewb/listEventType.php on line 133

    Any idea?

    Thank you
  • gus
    Senior Member
    • Jan 2009
    • 134

    #2
    In your first sample .php you are using REST (as opposed to RPC), and recently all calls to the REST API were chenged to require a slash '/' at the end of the end of all operation names.

    Try changing:

    Code:
     $jsonResponse = sportsApingRequest($appKey, $sessionToken, 'listEventTypes', '{"filter":{}}');
    
    to  $jsonResponse = sportsApingRequest($appKey, $sessionToken, 'listEventTypes/', '{"filter":{}}');
    dunno about your second script because in that one you appear to be using RPC.

    Comment

    • gus
      Senior Member
      • Jan 2009
      • 134

      #3
      Ooops, sorry, scrub that. I see you're adding a slash where you have:

      Code:
      curl_setopt($ch, CURLOPT_URL, "https://beta-api.betfair.com/rest/v1/$operation/");
      Last edited by gus; 07-03-2014, 11:53 AM.

      Comment

      • gus
        Senior Member
        • Jan 2009
        • 134

        #4
        But you seem to be calling the beta api, and I'm not sure that still works

        here's a script that does work, tho all it does is get the eventId for Horse Racing.
        assuming you have the script (and json.php) in a directory called c:\php then usage is:

        c:\php>php callbf.php Username Password


        Code:
        <?php
        
        require_once("json.php");
        error_reporting(E_ALL);
        
        $sessionToken = "";
        $thisPage = $_SERVER['PHP_SELF'];
        $appKey = "YOUR_APPKEY";
        
        $username = $argv[1];
        $password = $argv[2];
        $option = "0";
        
        
        
        ob_start();
        $sessionToken = getACookie($username, $password);
        ob_end_clean();
        
        if($sessionToken === "")
        	{
        		echo  "We had a problem Logging on to the Betfair API\r\n";
        		echo "Please Try again in a few moments.";
        	}
        	
        else
        	{
        		echo "Cookie: ".$sessionToken."\r\n";
        		
        		while($option != "2")
        			{
        				echo "\r\n";
        				echo "1. Get Horse Racing eventId\r\n";
        				
        				echo "2. Exit\r\n";
        		
        				$option = read_stdin();
        				
        				if($option == "1")
        					echo "Horse Racing: ".extractHorseRacingEventTypeId(getAllEventTypes($appKey, $sessionToken));
        				
        				
        				
        				elseif($option == "2")
        					exit(-1);
        					
        					
        				else
        					{
        						echo "No Option ".$option;
        						exit(-1);
        					}
        				}
        	}
        	
        
        
        
        
        	
        function getACookie($username, $password){
        	
        	$loginEndpoint= "https://identitysso.betfair.com/api/login";
        	
        	$cookie = "";
        	
        	$login = "true";
        	$redirectmethod = "POST";
        	$product = "home.betfair.int";
        	$url = "https://www.betfair.com/";
        
        	$fields = array
        		(
        			'username' => urlencode($username),
        			'password' => urlencode($password),
        			'login' => urlencode($login),
        			'redirectmethod' => urlencode($redirectmethod),
        			'product' => urlencode($product),
        			'url' => urlencode($url)
        		);
        
        	//open connection
        	$ch = curl_init($loginEndpoint);
        
        
        	//url-ify the data for the POST
        	$counter = 0;
        	$fields_string = "&";
        	
        	foreach($fields as $key=>$value) 
        		{ 
        			if ($counter > 0) 
        				{
        					$fields_string .= '&';
        				}
        			$fields_string .= $key.'='.$value; 
        			$counter++;
        		}
        
        	rtrim($fields_string,'&');
        
        	curl_setopt($ch, CURLOPT_URL, $loginEndpoint);
        	curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        	curl_setopt($ch, CURLOPT_POST, true);
        	curl_setopt($ch, CURLOPT_POSTFIELDS,$fields_string);
        	curl_setopt($ch, CURLOPT_HEADER, true);  // DO  RETURN HTTP HEADERS
        	curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);  // DO RETURN THE CONTENTS OF THE CALL
        
        	//execute post
        
        	$result = curl_exec($ch);
        
        
        	echo $result;
        
        	if($result == false) 
        		{
           	 		echo 'Curl error: ' . curl_error($ch);
        		} 
        	
        	else 
        		{
        			$temp = explode(";", $result);
        			$result = $temp[0];
        			
        			$end = strlen($result);
        			$start = strpos($result, 'ssoid=');
        			$start = $start + 6;
        		
        			$result = substr($result, $start, $end);
        		}
        	curl_close($ch);
        	
        	return $result;
        }
        
        
        //SPORTSAPI
        
        function getAllEventTypes($appKey, $sessionToken)
        {
         
            $jsonResponse = sportsApingRequest($appKey, $sessionToken, 'listEventTypes/', '{"filter":{}}');
         
            return $jsonResponse;
        }
         
        function extractHorseRacingEventTypeId($allEventTypes)
        {
            foreach ($allEventTypes as $eventType) {
                if ($eventType->eventType->name == 'Horse Racing') {
                    return $eventType->eventType->id;
                }
            }
        }
        
        function sportsApingRequest($appKey, $sessionToken, $operation, $params)
        {
        	$endpoint = "https://api.betfair.com/exchange/betting/rest/v1.0/";
        	$url = $endpoint.$operation;
        	echo "URL: ".$url."\r\n";
        	
            $ch = curl_init();
            curl_setopt($ch, CURLOPT_URL, $url);
            curl_setopt($ch, CURLOPT_POST, 1);
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        	curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        	curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
            curl_setopt($ch, CURLOPT_HTTPHEADER, array(
                'X-Application: ' . $appKey,
                'X-Authentication: ' . $sessionToken,
                'Accept: application/json',
                'Content-Type: application/json'
            ));
         	
        	if($params != "")
        		{
            		curl_setopt($ch, CURLOPT_POSTFIELDS, $params);
        		}
         
            $response = json_decode(curl_exec($ch));
         
            $http_status = curl_getinfo($ch, CURLINFO_HTTP_CODE);
            curl_close($ch);
         
            if ($http_status == 200) {
                return $response;
            } else {
                echo 'Call to api-ng failed: ' . "\n";
               
                echo  'Response: ' . json_encode($response);
                
            }
        }
        
        function read_stdin()
        
        {
        	$fr=fopen("php://stdin","r"); 
        	$input = fgets($fr,128); 
        	$input = rtrim($input);  
        	fclose ($fr); 
        	return $input;                  // return the text entered
        }
        
        function debug($debugString)
        {
            global $DEBUG;
            if ($DEBUG)
                echo $debugString . "\n\n";
        }
        
        
        
        
        	
        ?>
        Last edited by gus; 07-03-2014, 11:54 AM.

        Comment

        • pukkafish
          Junior Member
          • Mar 2014
          • 10

          #5
          @gus Thanks for the code. Working well. Now I need to get the non runners for a race horse!

          Comment

          • RicHep365
            Junior Member
            • Apr 2012
            • 5

            #6
            Hi there

            Using the code above with code below added.

            I get the following error:

            Call to api-ng failed:
            Response: {"detail":{},"faultcode":"Client","faultstring":"D SC-0021"}


            Code:
            $horseRacingEventTypeId = 7;
            
            $nextHorseRacingMarket = getNextUkHorseRacingMarket($appKey, $sessionToken, $horseRacingEventTypeId);
            
            function getNextUkHorseRacingMarket($appKey, $sessionToken, $horseRacingEventTypeId)
            {
            
                $params = '{"filter":{"eventTypeIds":["' . $horseRacingEventTypeId . '"],
                          "marketCountries":["GB"],
                          "marketTypeCodes":["WIN"],
                          "marketStartTime":{"from":"' . date('c') . '"}},
                          "sort":"FIRST_TO_START",
                          "maxResults":"1",
                          "marketProjection":["RUNNER_DESCRIPTION"]}';
            	
                $jsonResponse = sportsApingRequest($appKey, $sessionToken, 'listMarketCatalogue', $params);
            
                return $jsonResponse;
            	//return $jsonResponse[0]->result[0];
            }
            params = {"filter":{"eventTypeIds":["7"], "marketCountries":["GB"], "marketTypeCodes":["WIN"], "marketStartTime":{"from":"2014-10-01T15:31:00+00:00"}}, "sort":"FIRST_TO_START", "maxResults":"1", "marketProjection":["RUNNER_DESCRIPTION"]}

            These Params seem to produce results in the Visualiser if I am replicating it correctly.

            Any ideas?
            Last edited by RicHep365; 01-10-2014, 04:39 PM.

            Comment

            • RicHep365
              Junior Member
              • Apr 2012
              • 5

              #7
              Ok, solved it.

              Was a missing "/" after listMarketCatalogue...Doh...!!

              $jsonResponse = sportsApingRequest($appKey, $sessionToken, 'listMarketCatalogue/', $params);

              Comment

              Working...
              X