我在这里面临一个小问题。我将这些代码保存在 send-sms.php 文件中,尝试在我的网站上使用 wp_remote_post 设置 SMS API。作为我的试验的一部分,每次我运行下面的代码时,我都会得到我不明白的响应。
这些是代码
<?php
require_once 'wp-load.php';
$url = 'https://api.sprintsmsservice.com/api/SendSMS';
$response = wp_remote_post( $url, array(
'method' => 'POST',
'timeout' => 45,
'redirection' => 5,
'httpversion' => '1.0',
'blocking' => true,
'headers' => array(),
'body' => array(
'api_id'=>'xxxxxx',
'api_password'=>'xxxxxx',
'sms_type'=>'T',
'encoding'=>'T',
'sender_id'=>'ChonryOTP',
'phonenumber'=>255714812XXX,
'templateid'=>null,
'textmessage'=>'Hello, This is a test message',
),
'cookies' => array()
)
);
if ( is_wp_error( $response ) ) {
$error_message = $response->get_error_message();
echo "Something went wrong: $error_message";
} else {
echo 'Response:<pre>';
print_r( $response );
echo '</pre>';
}
?>
这些是我运行 send-sms.php 文件时的结果(您可以在此LINK中查看完整结果)
[status_code] => 415
[protocol_version] => 1.1
[success] =>
[redirects] => 0
[url] => https://api.sprintsmsservice.com/api/SendSMS/
[history] => Array
(
)
[cookies] => WpOrg\Requests\Cookie\Jar Object
(
[cookies:protected] => Array
(
)
)
)
[filename:protected] =>
)
)
我哪里做错了?因为如果我重新加载此文件,则不会向我的号码发送短信
我已经解决了这个问题,为了将来的参考,你可以查看下面的代码
$api_url = 'https://xxxxxxxx/api/SendSMS/'; // Replace with your API URL
$body = json_encode([
'api_id'=>'xxxxxxxxxxx',
'api_password'=>'xxxxxxxxxxx',
'sms_type'=>'T',
'encoding'=>'T',
'sender_id'=>'xxxxx',
'phonenumber'=>'xxxxxx',
'templateid'=>null,
'textmessage'=>'Robson, This is test message'
//'api_key' => $api_key,
]);
$response = wp_remote_post($api_url, [
'method' => 'POST',
'body' => $body,
'headers' => [
'Content-Type' => 'application/json',
],
]);
// Check for errors
if (is_wp_error($response)) {
error_log('SMS API Error: ' . $response->get_error_message());
return false;
}
// Handle the response
$response_body = wp_remote_retrieve_body($response);
$decoded_response = json_decode($response_body, true);
if (isset($decoded_response['success']) && $decoded_response['success'] === true) {
return true; // SMS sent successfully
}
error_log('SMS API failed with response: ' . $response_body);
return false;