* A {@see WP_Error} instance can be returned if an error occurs, and
* this should match the format used by API methods internally (that is,
* the `status` data should be used). A callback can return `true` to
* indicate that the authentication method was used, and it succeeded.
*
* @param WP_Error|null|boolean WP_Error if authentication error, null if authentication method wasn't used, true if authentication succeeded
*/
return apply_filters( 'json_authentication_errors', null );
}
基于上面的這個函數以及其被調用位置,我們可以加進去一個hook,以確認認證是否成功:
/**
* WP JSON API 認證檢查
* @param null
* @return boolean 是否認證成功
* @author suifengtec coolwp.com
*/
function coolwp_rest_api_auth_check( $result ){
if(
!isset($_GET['id'])
// ||!isset($_GET['app_key'])
||!isset($_GET['app_token'])
||empty($_GET['id'])
// ||empty($_GET['app_key'])
||empty($_GET['app_token'])
){
return false;
}
//獲取從應用GET過來的用戶id、app_key和app_token,當然了,你也可以只用一個去app_key和app_token中的任何一個去檢查
$user_id = (int)$_GET['id'];
// $app_key = sanitize_text_field($_GET['app_key']);
$app_token = sanitize_text_field($_GET['app_token']);
//查詢app_key和app_token,當然了,你也可以自定義一種算法,
//$wp_key = get_user_meta( $user_id, 'app_key', true);
$wp_token = get_user_meta( $user_id, 'app_token', true);
//將從應用客戶端獲取到的值與數據庫存儲的值進行對比
if(
( $wp_token == $app_token )
// &&( $wp_key == $app_key )
){
return true;
}
return false;
}
add_filter('json_authentication_errors', 'coolwp_rest_api_auth_check');
結論
加入 rest api 的 WordPress 甚至可以讓你做一個在線支付網站,有了這組 api ,基于 WordPress 的原生安卓應用和IOS應用可以更好的與 WordPress 站點進行交互。
新聞熱點
疑難解答