首页建站经验 WordPress教程:自定义WP REST API (WP API)授权

WordPress教程:自定义WP REST API (WP API)授权

* 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 s…

* 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 站点进行交互。

本文来自网络,不代表1号站长-站长学院|资讯交流平台立场。转载请注明出处: https://www.1cn.cc/jianzhan/jingyan/18175.html
上一篇ecshop首页商品显示购买过的次数
下一篇 解决wordpress使用wp_redirect函数出现Warning: Cannot modify header information的方 ...
admin

作者: admin

这里可以再内容模板定义一些文字和说明,也可以调用对应作者的简介!或者做一些网站的描述之类的文字或者HTML!

为您推荐

评论列表()

    联系我们

    联系我们

    0898-88888888

    在线咨询: QQ交谈

    邮箱: email@wangzhan.com

    工作时间:周一至周五,9:00-17:30,节假日休息

    关注微信
    微信扫一扫关注我们

    微信扫一扫关注我们

    关注微博
    返回顶部