PHP fails to POST to Web API using curl

Asked 1 years ago, Updated 1 years ago, 92 views

I can't skip the message to chatwork even if I execute the code below.
I added var_dump to the option settings, but I didn't know the cause because they were all true.

Could you give me some advice about the cause?

//***Create Chatbot: [Send msg to your chatwork board once members are registered in mikan's DB]
    header("Content-type:text/html; charset=utf-8"; // To prevent garbled characters when displaying a response browser
    $header=array('Content-Type: application/x-www-form-urlencoded', 'X-ChatWorkToken: My API Token');
    $url="https://www.chatwork.com/v2/rooms/ {room_id}/messages"; // My room room_id
    $ch = curl_init($url);
    $body=array(
      'body' = > 'API collaboration completed',
      'self_unread' = > '0'
    );
    $body_data=$data=http_build_query($body, "", "&");

    // Configuring [TODO] HTTP Request Header Information
    curl_setopt($ch,CURLOPT_POST,TRUE);
    curl_setopt($ch,CURLOPT_POSTFIELDS,$body_data);
    curl_setopt($ch,CURLOPT_HTTPHEADER,$header);
    curl_setopt($ch,CURLOPT_RETURNTRANSFER,TRUE); // To string to display status code on error

    $response=curl_exec($ch); 
    $statusCode=curl_getinfo($ch,CURLINFO_RESPONSE_CODE);

    $result=json_decode($response);
    if(curl_errno($ch)){
      echo 'Curl error'.curl_error($ch);
      $err_msg[] = 'chatwork collaboration failed'; // This variable is defined elsewhere from the code listed.
    }

    curl_close($ch);
    //****** Create Chatbot So far****

php api php-curl

2022-09-30 11:16

1 Answers

The URL to the Chatwork API was incorrect!

https://www.chatwork.com/v2/rooms/ {room_id}/messages

Remove the room_id parentheses {} from the above URL

https://www.chatwork.com/v2/rooms/room_id/messages

After correcting the description, the request has been accepted!


2022-09-30 11:16

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.