在 php 中编写curl 代码的正确方法是什么

问题描述 投票:0回答:1

我想使用curl来使用api。 要使用的卷曲是

curl -X POST \
  'https://api.messente.com/v1/omnimessage' \
  -u YOUR_MESSENTE_API_USERNAME:YOUR_MESSENTE_API_PASSWORD \
  -H 'Content-Type: application/json' \
  -d '{
    "to": "<recipient_phone_number>",
    "messages": [
      {
        "channel": "sms",
        "sender": "<sender name (optional)>",
        "text": "hello sms"
      }
    ]
  }'

我写道:

$url = 'https://api.messente.com/v1/omnimessage';

$c = curl_init();
curl_setopt($c, CURLOPT_URL, $url);
curl_setopt($c, CURLOPT_POST, true);
curl_setopt($c, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));
$data = array (
        "to" => "00353894215730", 
         "messages" => array("channel"=> "sms",
                    "sender"=> "00353894215730",
                    "text"=> "test message",
    ),
);
$post = http_build_query($data);
curl_setopt( $c, CURLOPT_POSTFIELDS, $post);
curl_setopt($c, CURLOPT_RETURNTRANSFER, true);
$AccountSid='xxxxx';
$AuthToken = 'xxxxx';
$auth = $AccountSid.':'.$AuthToken ;
curl_setopt( $c, CURLOPT_USERPWD, $auth ); // authenticate
$response = curl_exec ($c);
curl_close ($c);

这给出了错误代码:说无效的 JSON。

php curl
1个回答
0
投票

我可以看到两个问题:

首先

http_build_query
将数据编码为查询,您可能需要
json_encode

其次,你的数组结构不太匹配。 您需要将消息数组嵌套在另一个数组中:

//...
"messages" => [
  [
    "channel" => "sms",                                       
    "sender" => "00353894215730",
    "text" => "test message",
  ],
];
© www.soinside.com 2019 - 2024. All rights reserved.