Help with Schedule Segment Creation (PHP)

So having recently discovered you can update the Twitch schedule via script, I decided to have a go at it (scope has been updated to include this), however it’s not going very well and I’d appreciate a qualified pair of eyeballs to help identify the problem.

Here is my code minus the auth token look up and other queries to grab the schedule details and game info from our database. The original times are in unix timestamps.

// database look up stuffs
    $title = "Shambo plays ".$game;
    $timein = date("Y-m-d\TH:i:s\Z", $newstart); // 2022-09-06T21:00:00Z
    $timeout = date("Y-m-d\TH:i:s\Z", $newend);
    $zone = 'Europe/London';
    $hours = ($newend - $newstart)/60;
    
    $segdata = array(   
        'start_time' => $timein,
        'timezone' => $zone,
        'is_recurring' => false,
        'duration' => $hours,
        'category_id' => $catID,
        'title' => $title
    ); 
    
    var_dump($segdata);
    
    $CCR = curl_init();
    curl_setopt($CCR, CURLOPT_URL, "https://api.twitch.tv/helix/schedule/segment?broadcaster_id=501071947");
    curl_setopt($CCR, CURLOPT_RETURNTRANSFER, true); 
    curl_setopt($CCR, CURLOPT_FOLLOWLOCATION, true);
    curl_setopt($CCR, CURLOPT_HTTPHEADER, array(  
        'Content-type: application/json',
        'Authorization: Bearer '.$authtoken,     
        'Client-ID: '.$clientid, 
    ));   
    curl_setopt($CCR, CURLOPT_POST,true);
    curl_setopt($CCR, CURLOPT_POSTFIELDS,$segdata);
    $segresult = json_decode(curl_exec($CCR),true);
    echo curl_error($CCR);
    curl_close($CCR);  
    
    var_dump($segresult);

The preview array contains all the correct information from our database and preview looks like this:

array(6) {
  ["start_time"]=>
  string(20) "2022-09-06T21:00:00Z"
  ["timezone"]=>
  string(13) "Europe/London"
  ["is_recurring"]=>
  bool(false)
  ["duration"]=>
  string(3) "120"
  ["category_id"]=>
  string(5) "66082"
  ["title"]=>
  string(52) "Shambo plays I Went on The Internet and I Found This"
}

The result I’m getting back from Twitch is as follows:

array(3) {
  ["error"]=>
  string(11) "Bad Request"
  ["status"]=>
  int(400)
  ["message"]=>
  string(73) "Request body was not parsable. Attempted Content-Type: "application/json""
}

You declared a content-type header of application/json
But your POST body is not JSON encoded.

Simplest fix

curl_setopt($CCR, CURLOPT_POSTFIELDS,$segdata);

becomes

curl_setopt($CCR, CURLOPT_POSTFIELDS, json_encode($segdata));
1 Like

This topic was automatically closed 30 days after the last reply. New replies are no longer allowed.