ajax - How to get current_user_id from wordpress in node js?

admin2025-01-08  4

There is a website on wordpress, in the plugins folder I have a project on Node js. In index.html (the client part, mostly js there), there is content that I have to show only to registered users. I need to find out the data of the user registered in wordpress and transfer them to node js.

Using Ajax, I transfer the user id from php to the js file. Here is a part of my code: WP / function.php

add_action('wp_ajax_cur_user_id', 'get_cur_user_id'); 
function get_cur_user_id(){
    check_ajax_referer( 'wt_nonce', 'wt_nonce_code' );

    $wt_name = esc_attr($_POST['wt_name']);
    $wt_user_id = esc_attr($_POST['wt_user_id']);

    wp_die();
}

add_action( 'wp_enqueue_scripts', 'wt_ajax_data' );
function wt_ajax_data() {

    wp_enqueue_script('ajax_get_cur_user_id', plugins_url('/js/ajax_get_cur_user_id.js'), array( 'jquery' ));

    wp_localize_script( 'ajax_get_cur_user_id', 'wt_data_user', array(
        'ajaxurl' => admin_url('admin-ajax.php'),
        'wt_nonce' => wp_create_nonce('wt_nonce'),
        'wt_name' => wp_get_current_user()->display_name,
        'wt_user_id' => wp_get_current_user()->id
    ));
}

In the JS file, I receive the data and send it to node js, which, as I understand it, does not know about the existence of WordPress at all. Code: JS / ajax_get_cur_user_id.js

(function($) {
    $.getScript( "/socket.io/socket.io.js", function( data, textStatus, jqxhr ) {

        var socket = io('/', {path : '/trade/socket.io'});
        var data = {
            action: 'cur_user_id',
            wt_nonce_code: wt_data_user.wt_nonce,
            wt_name: wt_data_user.wt_name,
            wt_user_id: wt_data_user.wt_user_id
        };

        $.post( wt_data_user.ajaxurl, data, function(response) {
            socket.emit('validate', wt_data_user);
        });
    });
})(jQuery);

Thus, I get the ID of the registered user on the page "index.html" - (node ​​js). That was what I wanted, but when I did everything, I saw the following problem. index.html is a page, the link to which is in the personal account of each registered user. At the moment, index.html is like a common group chat room. Ie, if a user has entered the personal account, the user ID is displayed in the index.html, the last person to upload / update the wordpress page and this ID is shown to everyone on the index.html page. For my purposes this should not be. I need to ensure that on the index.html page only the active user data is displayed, that is, user_id = 1 sees only ID - 1, for user_id = 2 ID - 2 is displayed regardless of who last logged in or updated the page.

UPDATE I will clarify my task. I make a trading platform. In WordPress there are registered users who have their own personal account, balance and transaction history.

Using node js, and websocket, I implement a trading platform. In index.html (node ​​js) there is a table with currency pairs and two buttons: Buy and Sell. When the user clicks the button, I need to fix the amount at the time of clicking. For this, I need to get user_id in order to have a connection with his personal account, and be able to replenish his balance or withdraw funds from his account, depending on the outcome of the trade.

Theoretically: using wp_ajax_, I can transfer the current_user_id to a JS file, and from there I can send data to the node js server using the AJAX POST. On the server, I still need to somehow get the current user, contact the database and change his personal account. But I do not know how this can be done and with what modules.

Here is the server side: node / app.js

const redis = require('redis');
var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http, {path: '/trade/socket.io'});

const settings = {
    REDIS: {
        HOST: 'localhost'
    }
}

var mysql      = require('mysql');
var connection = mysql.createConnection({
  host     : 'localhost',
  user     : 'my_user',
  password : 'my_password',
  database : 'my_database'
});

let redisClient = new redis.createClient(settings.REDIS);

var trade = function(req, res, next) {

   function getQuote(symbol, callback) {
        redisClient.get(symbol, (error, quote) => {
            if (error) {
                throw new Error(error);
            }
            quote = JSON.parse(quote);
            callback(quote);
        });
    }
    io.on('connection', function(socket){

        var quotes = ['EURUSD','GBPUSD','USDJPY','USDCAD','EURGBP','USDCHF',
                      'AUDUSD','NZDUSD','GBPJPY','USDMXN','USDRUB','USDZAR','BTCUSD'];
        quotes.forEach(function(item, i, quotes) {
            setInterval(() => {
                getQuote(item, (q) => {io.emit('get_quote_'+item, q);});
            }, 3500);
        });
    });
    res.sendFile(__dirname + '/index.html');
}
app.get('/trade/:uid', trade);

http.listen(3000, function(){});

I first work with the js node. If I had known before that it would be so difficult for me, I would have abandoned this idea, but I’ve been working for more than two months, I don’t want to back down :) I feel that I cannot cope without help.

There is a website on wordpress, in the plugins folder I have a project on Node js. In index.html (the client part, mostly js there), there is content that I have to show only to registered users. I need to find out the data of the user registered in wordpress and transfer them to node js.

Using Ajax, I transfer the user id from php to the js file. Here is a part of my code: WP / function.php

add_action('wp_ajax_cur_user_id', 'get_cur_user_id'); 
function get_cur_user_id(){
    check_ajax_referer( 'wt_nonce', 'wt_nonce_code' );

    $wt_name = esc_attr($_POST['wt_name']);
    $wt_user_id = esc_attr($_POST['wt_user_id']);

    wp_die();
}

add_action( 'wp_enqueue_scripts', 'wt_ajax_data' );
function wt_ajax_data() {

    wp_enqueue_script('ajax_get_cur_user_id', plugins_url('/js/ajax_get_cur_user_id.js'), array( 'jquery' ));

    wp_localize_script( 'ajax_get_cur_user_id', 'wt_data_user', array(
        'ajaxurl' => admin_url('admin-ajax.php'),
        'wt_nonce' => wp_create_nonce('wt_nonce'),
        'wt_name' => wp_get_current_user()->display_name,
        'wt_user_id' => wp_get_current_user()->id
    ));
}

In the JS file, I receive the data and send it to node js, which, as I understand it, does not know about the existence of WordPress at all. Code: JS / ajax_get_cur_user_id.js

(function($) {
    $.getScript( "/socket.io/socket.io.js", function( data, textStatus, jqxhr ) {

        var socket = io('/', {path : '/trade/socket.io'});
        var data = {
            action: 'cur_user_id',
            wt_nonce_code: wt_data_user.wt_nonce,
            wt_name: wt_data_user.wt_name,
            wt_user_id: wt_data_user.wt_user_id
        };

        $.post( wt_data_user.ajaxurl, data, function(response) {
            socket.emit('validate', wt_data_user);
        });
    });
})(jQuery);

Thus, I get the ID of the registered user on the page "index.html" - (node ​​js). That was what I wanted, but when I did everything, I saw the following problem. index.html is a page, the link to which is in the personal account of each registered user. At the moment, index.html is like a common group chat room. Ie, if a user has entered the personal account, the user ID is displayed in the index.html, the last person to upload / update the wordpress page and this ID is shown to everyone on the index.html page. For my purposes this should not be. I need to ensure that on the index.html page only the active user data is displayed, that is, user_id = 1 sees only ID - 1, for user_id = 2 ID - 2 is displayed regardless of who last logged in or updated the page.

UPDATE I will clarify my task. I make a trading platform. In WordPress there are registered users who have their own personal account, balance and transaction history.

Using node js, and websocket, I implement a trading platform. In index.html (node ​​js) there is a table with currency pairs and two buttons: Buy and Sell. When the user clicks the button, I need to fix the amount at the time of clicking. For this, I need to get user_id in order to have a connection with his personal account, and be able to replenish his balance or withdraw funds from his account, depending on the outcome of the trade.

Theoretically: using wp_ajax_, I can transfer the current_user_id to a JS file, and from there I can send data to the node js server using the AJAX POST. On the server, I still need to somehow get the current user, contact the database and change his personal account. But I do not know how this can be done and with what modules.

Here is the server side: node / app.js

const redis = require('redis');
var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http, {path: '/trade/socket.io'});

const settings = {
    REDIS: {
        HOST: 'localhost'
    }
}

var mysql      = require('mysql');
var connection = mysql.createConnection({
  host     : 'localhost',
  user     : 'my_user',
  password : 'my_password',
  database : 'my_database'
});

let redisClient = new redis.createClient(settings.REDIS);

var trade = function(req, res, next) {

   function getQuote(symbol, callback) {
        redisClient.get(symbol, (error, quote) => {
            if (error) {
                throw new Error(error);
            }
            quote = JSON.parse(quote);
            callback(quote);
        });
    }
    io.on('connection', function(socket){

        var quotes = ['EURUSD','GBPUSD','USDJPY','USDCAD','EURGBP','USDCHF',
                      'AUDUSD','NZDUSD','GBPJPY','USDMXN','USDRUB','USDZAR','BTCUSD'];
        quotes.forEach(function(item, i, quotes) {
            setInterval(() => {
                getQuote(item, (q) => {io.emit('get_quote_'+item, q);});
            }, 3500);
        });
    });
    res.sendFile(__dirname + '/index.html');
}
app.get('/trade/:uid', trade);

http.listen(3000, function(){});

I first work with the js node. If I had known before that it would be so difficult for me, I would have abandoned this idea, but I’ve been working for more than two months, I don’t want to back down :) I feel that I cannot cope without help.

Share Improve this question edited Feb 17, 2019 at 19:37 VladSiy asked Feb 17, 2019 at 13:33 VladSiyVladSiy 57 bronze badges 2
  • Hi welcome to SE: Wordpress development. First of all for what is the ajax call cur_user_id? And second could you example the whole think with the index.html. Why is the user id from the last person shown on the index.html? – user141080 Commented Feb 17, 2019 at 16:35
  • @user141080 I have clarified my question, could you read it again? 2. I think the ID of the last active user is shown due to the fact that I transmitted data using a webpage. This is not correct, but I do not know what other way you can send data to the server. – VladSiy Commented Feb 17, 2019 at 19:44
Add a comment  | 

1 Answer 1

Reset to default 0

First, you should not be modifying any database values by allowing users to send an AJAX call to your server specifying the user ID to use, that would allow anybody to send an AJAX call with the nonce to modify any user's data.

If you want to make an AJAX call to get the user's ID it should be like this:

add_action( 'wp_ajax_cur_user_id', 'get_cur_user_id' );
function get_cur_user_id() {

    check_ajax_referer( 'wt_nonce', 'wt_nonce_code' );
    $user_id = get_current_user_id();

    if( empty( $user_id ) ){
        wp_send_json_error( array( 'not_logged_in' => 'User is not logged in' ) );
    } else {
        wp_send_json_success( $user_id );
    }

    die();
}

But you shouldn't be using that to send to your server to modify data, you should send the modified data to WordPress via AJAX and then use get_current_user_id to get the user's ID, not allowing it to be sent via AJAX

UPDATE:

Here's an example of how I would do this, making the AJAX call from node, not allowing the user id to be passed, but checking it internally in WordPress.

This assumes that you would send a POST in AJAX with the amount to buy in buy or amount to sell in sell

This also assumes that balance is saved in the user's meta

add_action( 'wp_ajax_update_cur_user_balance', 'update_cur_user_balance' );
function update_cur_user_balance() {
    global $wpdb;

    check_ajax_referer( 'wt_nonce', 'wt_nonce_code' );
    $user_id = get_current_user_id();

    if ( empty( $user_id ) ) {
        wp_send_json_error( array( 'not_logged_in' => 'User is not logged in' ) );
        return;
    }

    $buy  = array_key_exists( 'buy', $_POST ) ? floatval( $_POST['buy'] ) : false;
    $sell = array_key_exists( 'sell', $_POST ) ? floatval( $_POST['sell'] ) : false;

    $user_balance = get_user_meta( $user_id, 'user_balance', true );
    $user_balance_float = $user_balance ? floatval( $user_balance ) : 0;
    $transacted = false;

    if( $buy ){

        if( $buy > $user_balance_float ){
            wp_send_json_error( array( 'not_enough_funds' => 'Not enough funds to buy!' ) );
            return;
        }

        // Subtract buy amount from balance
        $user_balance_float = $user_balance_float - $buy;
        $transacted = true;
    } elseif( $sell ){

        // Add to user balance
        $user_balance_float = $user_balance_float + $sell;
        $transacted = true;
    }


    if( $transacted ){
        update_user_meta( $user_id, 'user_balance', $user_balance_float );
        wp_send_json_success( array( 'completed' => 'Transaction Completed', 'new_balance' => $user_balance_float ) );
        return;
    }

    wp_send_json_error( array( 'no_transact' => 'No transaction was completed!' ) );
    die();
}

You of course would need to come up with some way to make sure that user's don't just POST their own buy/sell using your nonce, but that would be outside the scope of this question.

Or if doing a SQL query, something like this:

 // For doing a custom SQL query in WordPress (just an example, needs to match table, field, value, etc)
$some_table = 'your_table';
$something = '123456789';
$query = $wpdb->prepare( "UPDATE `%s` SET something='%s' WHERE `userid` = %d", array( $some_table, $something, $user_id ) );
$wpdb->query( $query );
转载请注明原文地址:http://conceptsofalgorithm.com/Algorithm/1736268201a1256.html

最新回复(0)