最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

rest api - How to receive JSON payload from a digital device

programmeradmin0浏览0评论

I have a site with about 100 registered users. Some of the people will be receiving digital scales. The scales send their weight data to a 3rd party server that then sends a JSON Payload as an HTTP Post to a URL endpoint (my server). The message can include Basic authentication. Can anyone recommend the best approach to get the data into the WP database. Initially I just want to add the weight to their profile with user_metadata. Eventually I will process the data more. I'm good with Wordpress but can't figure out how to jump from http post into wp or even just mysql.

I have a site with about 100 registered users. Some of the people will be receiving digital scales. The scales send their weight data to a 3rd party server that then sends a JSON Payload as an HTTP Post to a URL endpoint (my server). The message can include Basic authentication. Can anyone recommend the best approach to get the data into the WP database. Initially I just want to add the weight to their profile with user_metadata. Eventually I will process the data more. I'm good with Wordpress but can't figure out how to jump from http post into wp or even just mysql.

Share Improve this question edited Jan 6, 2021 at 16:38 Johnnyboy Gomez asked May 3, 2020 at 15:12 Johnnyboy GomezJohnnyboy Gomez 333 bronze badges
Add a comment  | 

1 Answer 1

Reset to default 0

Your exact code would depend on how the HTTP notification is sent to your server and on the structure of the JSON, but the first building block is to listen for the incoming post request.

There are lots of WP hooks that would be suitable. One is init, e.g.:

add_action('init', function() {

     $user = 'the_correct_basic_auth_username';
     $password = 'the_correct_basic_auth_password';

    $has_supplied_credentials = !(empty($_SERVER['PHP_AUTH_USER']) && empty($_SERVER['PHP_AUTH_PW']));

    $is_not_authenticated = (
        !$has_supplied_credentials ||
        $_SERVER['PHP_AUTH_USER'] != $AUTH_USER ||
        $_SERVER['PHP_AUTH_PW']   != $AUTH_PASS
    );
    if ($is_not_authenticated) {
        return;
    }

    /* the rest will depend on how the data is sent and the structure of the JSON. 
    Once you have the data in the structure you want it, you can use the update_user_meta() function to add usermeta. Or, depending on what you're saving, use $wpdb or a wrapper function may suite (such as wp_insert_post()) */

});

I took the basic auth checking code from here - https://gist.github/rchrd2/c94eb4701da57ce9a0ad4d2b00794131

发布评论

评论列表(0)

  1. 暂无评论