使用-d命令进行卷曲请求

时间:2019-12-30 12:37:14

标签: php curl libcurl

我想用-d执行curl命令以使用Africa Talking API发送短信,很遗憾,我无法从服务器获得任何响应,而是在响应正文中找到了false,请帮助我如何发送该请求是新的。

这是https://build.at-labs.io/docs/sms%2Fsending

中的卷曲样本
curl -X POST \
    https://api.sandbox.africastalking.com/version1/messaging \
    -H 'Accept: application/json' \
    -H 'Content-Type: application/x-www-form-urlencoded' \
    -H 'apiKey: MyAppApiKey' \
    -d 'username=MyAppUsername&to=%2B254711XXXYYY,%2B254733YYYZZZ&message=Hello%20World!&from=myShortCode'

据我了解,这是我实施的

$messages = array(
    'username'=>'sandbox', //rather my username
    'to'=>$phone, // 266XXXXXXX,266XXXXXX
    'message'=>$text,//Hello
    'from'=>$from //Sandbox
);

$url = "https://api.sandbox.africastalking.com/version1/messaging";
//$url="https://api.africastalking.com/version1/messaging";
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
    'Content-Type:application/x-www-form-urlencoded',
    'apiKey:my-api-key'
));

curl_setopt($ch, CURLOPT_POSTFIELDS, ($messages)); //json_encode($messages)

$server_output = curl_exec($ch);
curl_close($ch);

var_dump($server_output);

输出false

2 个答案:

答案 0 :(得分:0)

卷曲没问题。...我认为问题出在AfricasTalking文档上。但是,这为我工作。

 curl -X POST https://api.sandbox.africastalking.com/version1/messaging -H 'Accept: application/json' -H 'Content-Type: application/x-www-form-urlencoded' -H 'apiKey: MyAppApiKey' -d username=MyAppUsername&to=%2B254711XXXYYY,%2B254733YYYZZZ&message=Hello%20World!&from=myShortCode' 

如果您不使用沙盒应用程序,则应使用实时版本,如下所示。

curl -X POST https://api.africastalking.com/version1/messaging -H 'Accept: application/json' -H 'Content-Type: application/x-www-form-urlencoded' -H 'apiKey: MyAppApiKey' -d username=MyAppUsername&to=%2B254711XXXYYY,%2B254733YYYZZZ&message=Hello%20World!&from=myShortCode'

答案 1 :(得分:0)

您需要构建查询字符串,才能成功将数据发送到端点。那意味着改变

curl_setopt($ch, CURLOPT_POSTFIELDS, ($messages)); //json_encode($messages)

curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($messages)); //json_encode($messages)