从 WordPress 调用 API 时出现 405 错误

时间:2021-04-30 22:22:48

标签: php wordpress wordpress-rest-api

我需要使用访问令牌和正文从 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
 }
}

但是,我遇到的问题是,当我获得访问令牌然后去提出我的请求去获取用户时,我会从 API 收到一条 405 错误消息。我已经尝试通过 Postman 手动发出相同的请求并且请求有效,那么我的 WordPress 代码是否有问题?

1 个答案:

答案 0 :(得分:0)

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

相关问题