api_key = get_option( 'wpthemoon_api_key' ); $this->base_url = 'https://www.wpthemoon.com/api/open/v1'; } /** * 获取用户积分 * @return array|WP_Error */ public function get_credits() { return $this->remote_get( '/user/points' ); } /** * POST 请求到开放接口。 * * @param string $endpoint * @param array $data * @return array|WP_Error */ public function post( $endpoint, $data = array() ) { return $this->remote_request( 'POST', $endpoint, $data ); } /** * GET 请求到开放接口。 * * @param string $endpoint * @param array $query * @return array|WP_Error */ public function get( $endpoint, $query = array() ) { if ( ! empty( $query ) ) { $endpoint = add_query_arg( $query, $endpoint ); } return $this->remote_request( 'GET', $endpoint ); } /** * 测试连接 * @return array|WP_Error */ public function ping() { return $this->remote_get( '/ping' ); } /** * 内部辅助函数:执行远程 GET 请求 */ private function remote_get( $endpoint ) { return $this->remote_request( 'GET', $endpoint ); } /** * 内部辅助函数:执行远程请求。 * * @param string $method * @param string $endpoint * @param array|null $body * @return array|WP_Error */ private function remote_request( $method, $endpoint, $body = null ) { if ( empty( $this->api_key ) ) { return new WP_Error( 'missing_api_key', __( 'Please configure the API Key in the settings', 'wpthemoon' ) ); } $args = array( 'timeout' => 300, 'method' => $method, 'headers' => array( 'x-api-key' => $this->api_key, 'Accept' => 'application/json', 'Content-Type' => 'application/json', ), ); if ( null !== $body ) { $args['body'] = wp_json_encode( $body ); } $response = wp_remote_request( $this->base_url . $endpoint, $args ); return $this->handle_response( $response ); } /** * 处理 API 响应 */ private function handle_response( $response ) { if ( is_wp_error( $response ) ) { return $response; } $status_code = wp_remote_retrieve_response_code( $response ); $body = json_decode( wp_remote_retrieve_body( $response ), true ); if ( 200 !== $status_code ) { $message = isset( $body['error']['message'] ) ? $body['error']['message'] : __( 'Unknown error', 'wpthemoon' ) . ' (HTTP ' . $status_code . ')'; $error_code = isset( $body['error']['code'] ) ? $body['error']['code'] : 'api_error'; return new WP_Error( $error_code, $message, array( 'status' => $status_code, 'error_code' => $error_code, ) ); } if ( isset( $body['success'] ) && true === $body['success'] ) { return $body['data']; } if ( isset( $body['code'] ) && 0 === intval( $body['code'] ) ) { return isset( $body['data'] ) ? $body['data'] : array(); } if ( isset( $body['code'] ) && 0 !== intval( $body['code'] ) ) { $message = isset( $body['message'] ) ? $body['message'] : __( 'Unknown error', 'wpthemoon' ); return new WP_Error( 'api_error', $message, array( 'status' => 400, 'error_code' => 'api_error', ) ); } return new WP_Error( 'invalid_response', __( 'Invalid API response format', 'wpthemoon' ) ); } }