API 7 PHP Examples

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • Micl
    Junior Member
    • May 2013
    • 5

    #1

    API 7 PHP Examples

    Hi, our developer is coding on the new API and is struggling to connect. We've been told that we can use a session ID made through the old API and then connect with it, but we're not sure how to connect once we've got it.

    If anyone can provide just some simple connection and data call examples in PHP I would be very grateful and I'm sure we can work from there.

    Many thanks
  • AlgoTrader
    Junior Member
    • Mar 2012
    • 243

    #2
    You just need to set following HTTP headers

    headers: {
    'X-Application': applicationKey,
    'X-Authentication': '"' + self.sessionKey + '"',
    'Content-Type': 'application/json',
    'Content-Length': self.jsonRequestBody.length,
    'Connection': 'keep-alive'
    }

    Use " to embrace X-Authentication. The endpoint is "https://beta-api.betfair.com:443/json-rpc"
    Betfair Bots Made Easy

    Comment

    • AlgoTrader
      Junior Member
      • Mar 2012
      • 243

      #3
      You need to POST there (with proper HTTP headers) something like this:
      Code:
      {
        "jsonrpc": "2.0",
        "id": 2,
        "method": "SportsAPING/v1.0/placeOrders",
        "params": {
          "marketId": "1.109541416",
          "instructions": [
            {
              "orderType": "LIMIT",
              "selectionId": 2264531,
              "side": "LAY",
              "limitOrder": {
                "price": 1.01,
                "size": 5,
                "persistenceType": "LAPSE"
              }
            },
            {
              "orderType": "LIMIT",
              "selectionId": 2264531,
              "side": "BACK",
              "limitOrder": {
                "price": 1000,
                "size": 5,
                "persistenceType": "LAPSE"
              }
            }
          ],
          "customerRef": "MyFirstPlaceOrders"
        }
      }
      Betfair should reply with response line this:
      Code:
      {
        "jsonrpc": "2.0",
        "result": {
          "customerRef": "MyFirstPlaceOrders",
          "status": "SUCCESS",
          "marketId": "1.109541416",
          "instructionReports": [
            {
              "status": "SUCCESS",
              "instruction": {
                "orderType": "LIMIT",
                "selectionId": 2264531,
                "side": "LAY",
                "limitOrder": {
                  "size": 5,
                  "price": 1.01,
                  "persistenceType": "LAPSE"
                }
              },
              "betId": "27274638053",
              "placedDate": "2013-05-22T11:53:18.000Z",
              "averagePriceMatched": 0,
              "sizeMatched": 0
            },
            {
              "status": "SUCCESS",
              "instruction": {
                "orderType": "LIMIT",
                "selectionId": 2264531,
                "side": "BACK",
                "limitOrder": {
                  "size": 5,
                  "price": 1000,
                  "persistenceType": "LAPSE"
                }
              },
              "betId": "27274638054",
              "placedDate": "2013-05-22T11:53:18.000Z",
              "averagePriceMatched": 0,
              "sizeMatched": 0
            }
          ]
        },
        "id": 2
      }
      If your developer has problems with sending HTTP POST then... you know what to do
      Last edited by AlgoTrader; 23-05-2013, 06:16 PM.
      Betfair Bots Made Easy

      Comment

      • BetfairDeveloperProgram
        Administrator
        • Oct 2008
        • 635

        #4
        PHP Example

        Hi Micl

        Please see a PHP example below:


        Code:
        <?php
        
        if (count($argv) != 3) {
            echo 'usage: php -f jsonrpc.php AppKey SessionToken';
            exit(-1);
        }
        
        
        $APP_KEY = $argv[1];
        $SESSION_TOKEN = $argv[2];
        
        // Setting DEBUG to true will output all request / responses to api-ng.
        $DEBUG = False;
        
        echo "1. Get all Event Types....\n";
        $allEventTypes = getAllEventTypes($APP_KEY, $SESSION_TOKEN);
        
        echo "\n2. Extract Event Type Id for Horse Racing....\n";
        $horseRacingEventTypeId = extractHorseRacingEventTypeId($allEventTypes);
        
        echo "\n3. EventTypeId for Horse Racing is: $horseRacingEventTypeId \n";
        
        echo "\n4. Get next horse racing market in the UK....\n";
        $nextHorseRacingMarket = getNextUkHorseRacingMarket($APP_KEY, $SESSION_TOKEN, $horseRacingEventTypeId);
        
        echo "\n5. Print static marketId, name and runners....\n";
        printMarketIdAndRunners($nextHorseRacingMarket);
        
        echo "\n6. Get volatile info for Market including best 3 exchange prices available...\n";
        $marketBook = getMarketBook($APP_KEY, $SESSION_TOKEN, $nextHorseRacingMarket->marketId);
        
        echo "\n7. Print volatile price data along with static runner info....\n";
        printMarketIdRunnersAndPrices($nextHorseRacingMarket, $marketBook);
        
        echo "\n\n8. Place a bet below minimum stake to prevent the bet actually being placed....\n";
        $betResult = placeBet($APP_KEY, $SESSION_TOKEN, $nextHorseRacingMarket->marketId, $nextHorseRacingMarket->runners[0]->selectionId);
        
        echo "\n9. Print result of bet....\n\n";
        printBetResult($betResult);
        
        
        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;
                }
            }
        
        }
        
        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[0]->result[0];
        }
        
        function printMarketIdAndRunners($nextHorseRacingMarket)
        {
        
            echo "MarketId: " . $nextHorseRacingMarket->marketId . "\n";
            echo "MarketName: " . $nextHorseRacingMarket->marketName . "\n\n";
        
            foreach ($nextHorseRacingMarket->runners as $runner) {
                echo "SelectionId: " . $runner->selectionId . " RunnerName: " . $runner->runnerName . "\n";
            }
        
        }
        
        
        function getMarketBook($appKey, $sessionToken, $marketId)
        {
            $params = '{"marketIds":["' . $marketId . '"], "priceProjection":{"priceData":["EX_BEST_OFFERS"]}}';
        
            $jsonResponse = sportsApingRequest($appKey, $sessionToken, 'listMarketBook', $params);
        
            return $jsonResponse[0]->result[0];
        }
        
        
        function printMarketIdRunnersAndPrices($nextHorseRacingMarket, $marketBook)
        {
        
            function printAvailablePrices($selectionId, $marketBook)
            {
        
                // Get selection
                foreach ($marketBook->runners as $runner)
                    if ($runner->selectionId == $selectionId) break;
        
                echo "\nAvailable to Back: \n";
                foreach ($runner->ex->availableToBack as $availableToBack)
                    echo $availableToBack->size . "@" . $availableToBack->price . " | ";
        
                echo "\n\nAvailable to Lay: \n";
                foreach ($runner->ex->availableToLay as $availableToLay)
                    echo $availableToLay->size . "@" . $availableToLay->price . " | ";
        
            }
        
        
            echo "MarketId: " . $nextHorseRacingMarket->marketId . "\n";
            echo "MarketName: " . $nextHorseRacingMarket->marketName;
        
            foreach ($nextHorseRacingMarket->runners as $runner) {
                echo "\n\n\n===============================================================================\n";
        
                echo "SelectionId: " . $runner->selectionId . " RunnerName: " . $runner->runnerName . "\n";
                echo printAvailablePrices($runner->selectionId, $marketBook);
            }
        }
        
        function placeBet($appKey, $sessionToken, $marketId, $selectionId)
        {
        
            $params = '{"marketId":"' . $marketId . '",
                        "instructions":
                             [{"selectionId":"' . $selectionId . '",
                               "handicap":"0",
                               "side":"BACK",
                               "orderType":
                               "LIMIT",
                               "limitOrder":{"size":"1",
                                            "price":"1000",
                                            "persistenceType":"LAPSE"}
                               }], "customerRef":"fsdf"}';
        
            $jsonResponse = sportsApingRequest($appKey, $sessionToken, 'placeOrders', $params);
        
            return $jsonResponse[0]->result;
        
        }
        
        function printBetResult($betResult)
        {
            echo "Status: " . $betResult->status;
        
            if ($betResult->status == 'FAILURE') {
                echo "\nErrorCode: " . $betResult->errorCode;
                echo "\n\nInstruction Status: " . $betResult->instructionReports[0]->status;
                echo "\nInstruction ErrorCode: " . $betResult->instructionReports[0]->errorCode;
            } else
                echo "Warning!!! Bet placement succeeded !!!";
        }
        
        
        function sportsApingRequest($appKey, $sessionToken, $operation, $params)
        {
            $ch = curl_init();
            curl_setopt($ch, CURLOPT_URL, "https://beta-api.betfair.com/json-rpc");
            curl_setopt($ch, CURLOPT_POST, 1);
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
            curl_setopt($ch, CURLOPT_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($ch, CURLOPT_POSTFIELDS, $postData);
        
            debug('Post Data: ' . $postData);
            $response = json_decode(curl_exec($ch));
            debug('Response: ' . json_encode($response));
        
            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 debug($debugString)
        {
            global $DEBUG;
            if ($DEBUG)
                echo $debugString . "\n\n";
        }
        
        ?>

        Comment

        • Micl
          Junior Member
          • May 2013
          • 5

          #5
          Thank you very much for the samples.

          Comment

          • Fred77
            Junior Member
            • Jan 2009
            • 37

            #6
            Great to see some example PHP code. I've not got around to looking at the new API yet so it's good to know that I'm not going to have to reinvent the wheel when the time comes!

            Comment

            • denimen.
              Junior Member
              • Feb 2013
              • 14

              #7
              For all of you having problems with the curl_exec($ch) from the betfair example, just add these two curl transfer options in the sportsApingRequest(... function:

              PHP Code:
              curl_setopt($chCURLOPT_SSL_VERIFYPEERfalse);
              curl_setopt($chCURLOPT_SSL_VERIFYHOST0); 
              And the script works..

              Comment

              Working...
              X