I am looking for some help concerning WordPress plugin development. My plugin queries an API which requires an Authentication Token, that token is fetched via a Token delivery APi. The token expire every 3600 seconds.
I would like to store the Token, in a persistent way (for all sessions , like server side caching) and update it only when needed. Multiple Api call could be done with the same token. The problem is, if I store the token in a global variable, it gets reset each time a user reload a page which uses my plugin. https://wordpress.stackexchange.com/questions/89263/how-to-set-and-use-global-variables-or-why-not-to-use-them-at-all
After looking for answer I found:
-WP_CACHE , but it is not persistent.
-I know I can store the token in the Database, but a Token in Database is not a use case I found elegant
-Tool such as Redis Object Cache for PHP but I found it to be really complicated , installing etc...
Is there any good practice or easy way of doing this? I only need to keep a string for an hour and access it within the plugin in PHP.
Thank you.
https://wordpress.stackexchange.com/questions/89263/how-to-set-and-use-global-variables-or-why-not-to-use-them-at-all
In this case, I would work with WordPress transients:
https://developer.wordpress.org/reference/functions/set_transient/ https://developer.wordpress.org/reference/functions/get_transient/
To set a transient, you can use this code:
$transient = 'your_token_name';
$value = 'your_token'
$expiration = 3600
set_transient( $transient, $value, $expiration );
To receive the value of your transient again, you can use:
$token = get_transient( $transient );
Using these methods is better than update_option or get_option since WordPress manages the expiration (deletion) of transients completely, so you don't have to implement your own logic for this.
Before you pass the value to the transient method, you can encrypt and decrypt it by storing a salt/key in your wp-config.php. You can find more infos about this topic here:
http://php.net/manual/es/function.openssl-encrypt.php http://php.net/manual/es/function.openssl-decrypt.php
To define a constant in WordPress you need to go to your wp-config.php file and add it between the "you can edit" words:
define( 'YOUR_SALT', '12345678' );
You can read it again as a normal constant in WordPress:
$salt = YOUR_SALT;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With