使用JSON API插件在WordPress中从混合移动应用程序创建新帖子

时间:2017-06-16 作者:Kaushik Rajbongshi

因此,我正在使用cordova和jquery mobile开发一个混合应用程序。我需要登录wordpress博客网站,并在我的混合应用程序中创建新帖子。我正在使用JSON Api插件(https://wordpress.org/plugins/json-api/) 执行AJAX post。问题是当我尝试使用create_post method,我得到以下错误:

POST http//some_localhost_ip/wordpress/api/create_post/? 403(Forbidden)

我还使用了JSON Api用户插件(https://wordpress.org/plugins/json-api-user/) 对于用户身份验证,在中,我使用generate_auth_cookie 方法

authentication-controller.js

$.ajax({
    url: SERVER_URL + "/api/get_nonce/?controller=user&method=generate_auth_cookie",
    type: "POST",
    headers: {
        \'Access-Control-Allow-Headers\': \'Content-Type, Accept\',
        \'Access-Control-Allow-Methods\': \'GET, POST, OPTIONS\'
    },
    crossDomain: true,
    cache: true,
    success: function(result) {
        if (result.status == "ok") {
            var url = SERVER_URL + "/api/user/generate_auth_cookie/?"
            var dataString = {};
            dataString["nonce"] = result.nonce;
            dataString["username"] = username;
            dataString["password"] = password;
            if (!checkBox.is(\':checked\')) {
                dataString["seconds"] = SESSION_TIMEOUT;
            }
            dataString["insecure"] = "cool"; // remove this if SSL certificate is installed and the url is HTTPS
            $.ajax({
                url: url,
                type: "POST",
                headers: {
                    \'Access-Control-Allow-Headers\': \'Content-Type, Accept\',
                    \'Access-Control-Allow-Methods\': \'GET, POST, OPTIONS\'
                },
                data: dataString,
                crossDomain: true,
                cache: false,
                success: function(result) {
                    if (result.status == "ok") {
                        window.localStorage.setItem("USERDATA", JSON.stringify(result.user));
                        window.localStorage.setItem("USERCOOKIE", result.cookie);
                        console
                        switch (result.user.role[0]) {
                            case "subscriber":
                                $.mobile.navigate("#page-subscriber-allposts");
                                break;
                            case "author":
                                $.mobile.navigate("#page-author-allposts");
                                break;
                            case "editor":
                                $.mobile.navigate("#page-editor-allposts");
                                break;
                            default:
                                $.mobile.navigate("#page-contributor-allposts");
                                break;
                        }
                    } else {
                        navigator.notification.alert(result.error, function doNothing() {}, "ERROR!", "OK");
                    }
                    return;
                },
                error: function(error) {
                    navigator.notification.alert("There is some issue in connecting to Authentication server", function doNothing() {}, "Breath In! Breath Out!", "Try Again");
                    return;
                }
            });
        } else {
            navigator.notification.alert("There is some issue in connecting to Authentication server", function doNothing() {}, "Breath In! Breath Out!", "Try Again");
            return;
        }
    },
    error: function(error) {
        navigator.notification.alert("There is some issue in connecting to Authentication server", function doNothing() {}, "Breath In! Breath Out!", "Try Again");
        return;
    }
});

workflow-controller.js

var url = SERVER_URL;
if (null != postId && typeof postId != "undefined") {
    url += "/api/get_nonce/?controller=posts&method=update_post";
} else {
    url += "/api/get_nonce/?controller=posts&method=create_post";
}
$.ajax({
    url: url,
    type: "POST",
    headers: {
        \'Access-Control-Allow-Headers\': \'Content-Type, Accept\',
        \'Access-Control-Allow-Methods\': \'GET, POST, OPTIONS\'
    },
    crossDomain: true,
    cache: false,
    success: function(result) {
        alert(JSON.stringify(result));
        if (result.status == "ok") {
            var dataString = {};
            if (null != postId && typeof postId != "undefined") {
                url = SERVER_URL + "/api/update_post/?";
            } else {
                url = SERVER_URL + "/api/create_post/?";
                dataString["post_id"] = postId;
            }
            dataString["nonce"] = result.nonce;
            dataString["cookie"] = window.localStorage.getItem("USERCOOKIE");
            dataString["author"] = author;
            dataString["title"] = title;
            dataString["content"] = news;
            $.ajax({
                url: url,
                type: "POST",
                headers: {
                    \'Access-Control-Allow-Headers\': \'Content-Type, Accept\',
                    \'Access-Control-Allow-Methods\': \'GET, POST, OPTIONS\'
                },
                data: dataString,
                crossDomain: true,
                cache: false,
                success: function(result) {
                    alert(JSON.stringify(result));
                    if (result.status == "ok") {
                        navigator.notification.alert("Your post was successfully submitted and is pending for review", function doNothing() {}, "Hurray!!", "Ok");
                        $.mobile.navigate("#page-author-allposts");
                        return;
                    }else {
                         navigator.notification.alert("There is some issue in submitting your post", function doNothing() {}, "Breath In! Breath Out!", "Try Again");
                         return;
                     }
                },
                error: function(error) {
                    navigator.notification.alert("There is some issue in submitting your post", function doNothing() {}, "Breath In! Breath Out!", "Try Again");
                    return;
                }
            });
        }else {
             navigator.notification.alert("There is some issue in submitting your post", function doNothing() {}, "Breath In! Breath Out!", "Try Again");
             return;
         }
    },
    error: function(error) {
        navigator.notification.alert("There is some issue in submitting your post", function doNothing() {}, "Breath In! Breath Out!", "Try Again");
        return;
    }
});

2 个回复
最合适的回答,由SO网友:Kaushik Rajbongshi 整理而成

我放弃了JSON Api,现在使用的是WP Rest Api V2。此外,对我之前使用的基本auth插件有一点小小的更改“WP Basic Auth“。它有故障。请尝试使用插件。”https://github.com/WP-API/Basic-Auth.

我更改了ajax调用,如下所示:

$.ajax({
    url: SERVER_URL + "/wp-json/wp/v2/posts",
    type: "POST",
    headers: {
        \'Access-Control-Allow-Headers\': \'Content-Type, Accept\',
        \'Access-Control-Allow-Methods\': \'GET, POST, OPTIONS, DELETE\',
        \'Authorization\': \'Basic \' + btoa(username + ":" + password)
    },
    data: dataString,
    crossDomain: true,
    cache: false,
    beforeSend: function() {
        SpinnerPlugin.activityStart("Please wait...", {dimBackground: true});
    },
    complete: function() {
        SpinnerPlugin.activityStop();
    },
    success: function(result) {
       navigator.notification.alert(successMsg, function doNothing() {}, "Success!!", "Ok");
       $.mobile.navigate("#page-author-allposts");
       return;
    },
    error: function(error) {
        console.log(error);
        navigator.notification.alert(errMsg, function doNothing() {}, "Error", "OK");
        return;
    }
});
然而,这种Basic Authenticating is only for development environment. 我想我以后需要实现更复杂的oAuth身份验证:/

SO网友:Gnanasekaran Loganathan

您可以使用以下插件进行身份验证,https://wordpress.org/plugins/jwt-authentication-for-wp-rest-api/

或者您需要通过以下方法实现身份验证,https://developer.wordpress.org/rest-api/using-the-rest-api/authentication/

当您发送带有用户名和密码的请求时,您可以获得令牌作为响应。然后,为了进行身份验证,您需要在每个请求中发送此令牌,请求头如下所示,

syntax : 授权:持票人<;空间>标记

Example:授权:持有人eyJ0eXAiOiJKV1QiLCJhbGciOiJINiJ9。Eyjpioijodhrwolwvxc9hchbzlm9wzw50zxn0zhjpdmuuy29tojgwodbcl21hz25pzmljzw50iiwif0ijoxndmjk1lcjuymyioje0otgxotyotusimv4cci6mtq5odiwmzq5nswizgf0ysi6eyj1c2vyijp7imlimsj9fx 0。ngBJaXmtKAaBULSUtQZ7eHhqB8YSPjeHuIenter image description here

结束

相关推荐