我正在尝试使用Twilio api,就在这里:https://www.twilio.com/lookup
它说如果我称之为:
curl -XGET "https://lookups.twilio.com/v1/PhoneNumbers/(405)%20555-1212?Type=carrier&Type=caller-name" -u "{AccountSid}:{AuthToken}"
它会回复这样的数据:
{
"country_code": "US",
"phone_number": "+14055551212",
"national_format": "(405) 555-1212",
"url": "https://lookups.twilio.com/v1/PhoneNumber/+14055551212",
"caller_name": {
"caller_name": null,
"caller_type": null,
"error_code": null,
}, "carrier": {
"type": "mobile",
"error_code": null,
"mobile_network_code": null,
"mobile_country_code": "310",
"name": null
}
}
所以在PHP中如何将其称为变量?
我试过了:
$res = curl -XGET "https://lookups.twilio.com/v1/PhoneNumbers/(405)%20555-1212?Type=carrier&Type=caller-name" -u "{AccountSid}:{AuthToken}";
但我得到错误。
我尝试创建一个像这样的卷曲函数:
function url_get_contents($_turl) {
if (!function_exists('curl_init')) {
die('CURL is not installed!');
}
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $_turl);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$output = curl_exec($ch);
if ($output === false) { die(curl_error($ch)); }
curl_close($ch);
return $output;
}
然后将其称为:
$res = url_get_contents("https://lookups.twilio.com/v1/PhoneNumbers/4055551212?Type=carrier&Type=caller-name -u AccountSID:AccountAuth");
和
$res = url_get_contents("https://lookups.twilio.com/v1/PhoneNumbers/4055551212?Type=carrier&Type=caller-name");
但第一个不起作用。第二个工作,但它说我没有通过有效的sid和auth ......
那么,有没有办法让这项工作没有大量的代码?
答案 0 :(得分:1)
我最近不得不这样做。您似乎正在尝试错误地传递Curl身份验证参数。试试这个功能:
function lookup($number){
// Twilio Account Info
$acct_sid = "xxxxx";
$auth_token = "yyyyy";
// Fetch the Lookup data
$curl = curl_init("https://lookups.twilio.com/v1/PhoneNumbers/".$number);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
curl_setopt($curl, CURLOPT_USERPWD, $acct_sid.":".$auth_token);
$response_data = curl_exec($curl);
curl_close($curl);
// Handle the Data
$lookup_data_array = json_decode($response_data,true); // Convert to array
print_r($lookup_data_array);die();
}
然后你只需要传递你想要查找的号码:
$this->lookup("650-319-8930");
然后您应该得到这样的回复:
Array
(
[caller_name] => Array
(
[caller_name] => CLOUDFLARE, INC
[caller_type] => BUSINESS
[error_code] =>
)
[country_code] => US
[phone_number] => +16503198930
[national_format] => (650) 319-8930
[carrier] => Array
(
[mobile_country_code] =>
[mobile_network_code] =>
[name] => Proximiti Mobility 2
[type] => voip
[error_code] =>
)
[url] => https://lookups.twilio.com/v1/PhoneNumbers/+16503198930?Type=carrier&Type=caller-name
)
祝你好运!