首页 > 解决方案 > 从 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 代码是否有问题?

标签: phpwordpresswordpress-rest-api

解决方案


意识到我使用的是 wp_remote_post 而不是 wp_remote_request (所以做一个 POST 而不仅仅是一个 GET)。一旦我这样做了,它工作得很好。


推荐阅读