Yes, thanks for the update.
I decided to handle the calls to the API completely in javascript. I add the stored id_token using wp_localize_script(). The wordpress module is now very simple:
function dhm_hook_auth0_user_login( $user_id, $userinfo, $is_new, $id_token, $access_token, $refresh_token ) {
update_user_meta( $user_id, 'auth0_id_token', $id_token );
}
add_action( 'auth0_user_login', 'dhm_hook_auth0_user_login', 10, 6 );
function dhm_scripts() {
wp_enqueue_script( 'dhm_api', plugin_dir_url( __FILE__ ) . '/js/api.js', array( 'jquery' ), '1.0.11', true );
$user_id = get_current_user_id();
$data = array(
'url' => 'https://**.localtunnel.me', // Todo: configuration options
'user_id' => $user_id,
'id_token' => get_user_meta( $user_id, 'auth0_id_token', true )
);
wp_localize_script( 'dhm_api', 'php_vars', $data );
}
add_action( 'wp_enqueue_scripts', 'dhm_scripts' );
And the javascript (/js/api.js):
jQuery(document).ready(function( $ ) {
if (!php_vars) { return; }
// Todo: check conditions ( user_id, id_token present )
// fetch current balance
function fetchCurrentBalance() {
$.ajax({
url: php_vars.url,
type: 'GET',
dataType: 'json',
headers: {
'Authorization': 'Bearer ' + php_vars.id_token
},
contentType: 'application/json; charset=utf-8',
success: function(response) {
console.log(response);
let html = 'Balance: ' + response;
$('#dhm-balance').html( html );
},
error: function(errorThrown) {
console.log(errorThrown);
$('#dhm-balance').html( 'error' );
}
});
}
// Fetch widget from API if needed (div id="dhm-xxx")
if ( $('#dhm_balance') ) { fetchCurrentBalance(); }
});
In this case the drawback is that there is an API-request for every page-load where this div is rendered. But at this time the API can handle this easily.