Laravel Guzzle Http Auth无法正常工作

时间:2016-11-09 09:13:39

标签: php http

我尝试使用API发送短信。我已经按照此示例中的代码进行了操作,但转换为Guzzle

PHP中用于POST Rest请求的实现示例

<?php
…....
try
{

//POST
$httpClient = new Zend_Http_Client();
$httpClient->setUri("http://www.web2sms.ro/prepaid/message");
$httpClient->setMethod(Zend_Http_Client::POST);
$httpClient->setHeaders("Content-Type", "application/json");

//method param
$crtDate = new Zend_Date();
$apiKey = ""; //value provided
$nonce = $crtDate->get(Zend_Date::TIMESTAMP);
$method = "POST";
$url = "/prepaid/message";
$sender = "";
$recipient = "07xxxxxxxx";//To be fill in !
$message = "";
$visibleMessage = "How the message do you want to appear on the interface. If empty string than $message value will be shown";
$scheduleDate = ''; //Format yyyy-MM-dd HH:mm:ss
$validityDate = ''; //Format yyyy-MM-dd HH:mm:ss
$callbackUrl = '';
$secret = ""; // value provided

$string = $apiKey . $nonce . $method . $url . $sender . $recipient . $message . $visibleMessage . $scheduleDate . $validityDate . $callbackUrl . $secret;

$signature = hash('sha512', $string);
$httpClient->setAuth($apiKey, $signature);

$data = array(
"apiKey" => $apiKey,
"sender" => $sender,
"recipient" => $recipient,
 message" => $message,
"scheduleDatetime" => $scheduleDate,
"validityDatetime" => $validityDate,
"callbackUrl" => $callbackUrl,
"userData" => "",
"visibleMessage" => $visibleMessage,
"nonce" => $nonce);
$httpClient->setRawData(Zend_Json::encode($data));

$httpResponse = $httpClient->request();
var_dump($httpResponse);
var_dump($httpResponse->getBody());
var_dump(json_decode($httpResponse->getBody()));
}
catch (Zend_Http_Client_Exception $e)
{
//
}

我的代码与Guzzle:

$apiKey = "xxxxxxxxx";
$nonce = time();
$method = "POST";
$url = "http://www.web2sms.ro/prepaid/message";
$sender = "XXXXXXXX";
$recipient = "0768814244";
$message = "Un mesaj";
$visibleMessage = "How the message do you want to appear on the interface. If empty string than value will be shown";
$secret = "xxxxxxxxxx";

$string = $apiKey . $nonce . $method . $url . $sender . $recipient . $message . $visibleMessage . $secret;

$signature = hash('sha512', $string);

$client = new GuzzleHttp\Client([
    'headers' => ['Content-Type' => 'application/json']
]);

$data = array(
    "apiKey" => $apiKey,
    "sender" => $sender,
    "recipient" => $recipient,
    "message" => $message,
    "visibleMessage" => $visibleMessage,
    "nonce" => $nonce);

$body = GuzzleHttp\json_encode($data);

$request = $client->request('POST', 'http://www.web2sms.ro/prepaid/message', ['auth' => [$apiKey, $signature], 'body' => $body]);

但仍然没有工作; 我收到此错误:

Client error: `POST http://www.web2sms.ro/prepaid/message` resulted in a `401 Unauthorized` response:

{ “错误”:{ “代码”:268435459, “消息”: “IDS_App_Controller_Rest_Message__E_INVALID_REQUEST_DATA_WRONG_SIGNATURE”}}

我错了什么?

1 个答案:

答案 0 :(得分:1)

我可以通过将$url更改为/prepaid/message来解决此问题。