我正在使用Godaddy api构建一个简单的域可用性检查器。
我用的是Laravel 9。
它给出了可用的和已经注册的结果,但是如果我添加一个没有域扩展名的字符串,如:somename所以没有。com或。org等然后我得到一个("Undefined array key "available")错误信息
在我的视图文件中,我只有一个简单的表单,其中用户可以输入要检查的域名。
在我的控制器中我验证输入:
$validator = Validator::make($request->all(), [
'userDomain' => ['required', 'string', 'max:191']
]);
我也有我的API密钥和基础url存储在变量:
$API_KEY_OTE = "apikey";
$API_SECRET_OTE = "apisecret";
$OTE_BASE_URL = "https://api.ote-godaddy.com";
然后我从输入
中删除一些不需要的字符$request->userDomain = str_replace('www.', '', $request->userDomain);
$request->userDomain = str_replace('http://', '', $request->userDomain);
$request->userDomain = str_replace('https://', '', $request->userDomain);
我把curl的url放在一起,像这样:
$url = $OTE_BASE_URL . "/v1/domains/available?domain=" . $request->userDomain;
旋度设置如下:
$header = array(
'Authorization: sso-key '.$API_KEY_OTE.':'.$API_SECRET_OTE.''
);
$ch = curl_init();
$timeout = 60;
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER,false);
curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
$result = curl_exec($ch);
curl_close($ch);
$checkDomain = json_decode($result, true);
然后我用一系列if/else if语句检查结果:
if($checkDomain['available'] == 1 || $checkDomain['available'] == true) {
return redirect()->back()->with('successMsg', 'The domain name ' . $request->userDomain . ' is available! <a href="https://godaddy.com" target="_blank">Click here</a> to register it on Godaddy!');
} else if($checkDomain['available'] == '' || $checkDomain['available'] == 0 || $checkDomain['available'] == false) {
return redirect()->back()->with('failureMsg', 'Sorry! The domain name ' . $request->userDomain . ' is already registered! Try a different name.');
}
else if($checkDomain['code']) {
return redirect()->back()->with('failureMsg', $checkDomain['fields'][0]['message']);
} else {
return redirect()->back()->with('failureMsg', 'Please enter a valid domain name!');
}
这是一个成功的响应体,来自godaddy:
{
"available": true,
"currency": "USD",
"definitive": true,
"domain": "string",
"period": 0,
"price": 0
}
,这是一个无效的响应体:
{
"code": "string",
"fields": [
{
"code": "string",
"message": "string",
"path": "string",
"pathRelated": "string"
}
],
"message": "string"
}
您必须首先检查它是错误响应还是成功响应,然后才尝试使用它的一个键:
if (isset($checkDomain['available'])) {
if (!empty($checkDomain['available'])) {
return redirect()->back()->with('successMsg', 'The domain name ' . $request->userDomain . ' is available! <a href="https://godaddy.com" target="_blank">Click here</a> to register it on Godaddy!');
}
return redirect()->back()->with('failureMsg', 'Sorry! The domain name ' . $request->userDomain . ' is already registered! Try a different name.');
} elseif (isset($checkDomain['code'])) {
return redirect()->back()->with('failureMsg', $checkDomain['fields'][0]['message']);
}
return redirect()->back()->with('failureMsg', 'Please enter a valid domain name!');