* 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 );
}
基于上面的這個(gè)函數(shù)以及其被調(diào)用位置,我們可以加進(jìn)去一個(gè)hook,以確認(rèn)認(rèn)證是否成功:
/**
* WP JSON API 認(rèn)證檢查
* @param null
* @return boolean 是否認(rèn)證成功
* @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;
}
//獲取從應(yīng)用GET過來的用戶id、app_key和app_token,當(dāng)然了,你也可以只用一個(gè)去app_key和app_token中的任何一個(gè)去檢查
$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,當(dāng)然了,你也可以自定義一種算法,
//$wp_key = get_user_meta( $user_id, 'app_key', true);
$wp_token = get_user_meta( $user_id, 'app_token', true);
//將從應(yīng)用客戶端獲取到的值與數(shù)據(jù)庫存儲(chǔ)的值進(jìn)行對(duì)比
if(
( $wp_token == $app_token )
// &&( $wp_key == $app_key )
){
return true;
}
return false;
}
add_filter('json_authentication_errors', 'coolwp_rest_api_auth_check');
結(jié)論
加入 rest api 的 WordPress 甚至可以讓你做一個(gè)在線支付網(wǎng)站,有了這組 api ,基于 WordPress 的原生安卓應(yīng)用和IOS應(yīng)用可以更好的與 WordPress 站點(diǎn)進(jìn)行交互。
|
新聞熱點(diǎn)
疑難解答
圖片精選