0

I am building a plugin that displays a button on the page through a shortcode. When the button is clicked, it's supposed to send a request to an external API and retrieve an audio file. Since the API url includes an API key, I don't think I can use AJAX to send a request - this will reveal the API key in the page source.

So how do I achieve this?

Receiving response from the API is pretty straightforward with PHP. I have done something like this:

function my_plugin_func() { .... $apikey = '123456789abcdef'; $apiurl = 'http://api.url/rest?apikey='.$apikey.'&opt1=val1&opt2=val2'; $response = wp_remote_get($apiurl); $results = wp_remote_retrieve_body($response); $filepath = '/blah/blah/blah.mp3'; file_put_contents($filepath, $results); $return_val = '<button type="button">Get File</button>'; return $return_val; } add_shortcode('my_plugin', 'my_plugin_func');

How do I make this work when the button is clicked? Will it work through AJAX but making sure the API key is not exposed?

2

In order to keep your key secret you will have to send a request via AJAX that say "gimme the mp3" to the server, let the server communicate with the service provider and return the result in the response to the AJAX request. This way at no point in time you expose any secret on the general web.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.