php - 从 WordPress 调用 API 时出现 405 错误
问题描述
我需要使用访问令牌和正文从 API 获取一些数据,所以我做了以下操作(随机键和 id):
add_action('rest_api_init', 'wp_rest_user_endpoints');
function wp_rest_user_endpoints($request) {
register_rest_route('wp/v2', 'users/register', array(
'methods' => 'POST',
'callback' => 'wc_rest_user_endpoint_handler',
));
}
function wc_rest_user_endpoint_handler($request = null) {
$response = array();
$parameters = $request->get_json_params();
$userid = sanitize_text_field($parameters['data[attendeeid]']);
$body = array(
'accountid' => '121209102910',
'key' => 'asjkajskauweiajksakajsakjsaks',
);
$args = array(
'body' => $body,
);
$response = wp_remote_post( 'https://api-na.eventscloud.com/api/v2/global/authorize.json', $args );
$body = wp_remote_retrieve_body( $response );
$data = json_decode( $body );
$accesstoken = $data->accesstoken;
if($accesstoken ) {
$body = array(
'accesstoken' => $accesstoken,
'eventid' => '29102901920129',
'attendeeid' => '1212121902910920',
);
$args = array(
'body' => $body,
);
$response = wp_remote_post( 'https://api-na.eventscloud.com/api/v2/ereg/getAttendee.json', $args );
//Do something with this
}
}
但是,我遇到的问题是,当我获取 accesstoken 然后去发出我的请求去获取用户时,我从 API 收到一条 405 错误消息。我尝试通过 Postman 手动发出相同的请求,并且请求有效,所以我的 WordPress 代码是否有问题?
解决方案
意识到我使用的是 wp_remote_post 而不是 wp_remote_request (所以做一个 POST 而不仅仅是一个 GET)。一旦我这样做了,它工作得很好。
推荐阅读
- ruby-on-rails - 关于将选项传递给特征的工厂女孩语法的问题
- c++ - 我正在尝试为我的程序执行搜索功能以从我的文本文件中搜索记录
- python - Python:带有线程的 PubSub 和 WxPython 是否需要 wx.CallAfter?
- javascript - 如何停止 if 语句
- api - 如何在应用程序洞察资源之前部署 APIManagement Service Logger?
- angular - Angular 8 行为主题
- python - 实现验证规则时的双重变量分配
- r - 在ggplot上绘制均值的置信区间
- matplotlib - Ipywidgets的水平对齐/交互式绘图
- reactjs - 无需导入即可反应内联 css 类