I'm relatively new to coding. I'm trying to learn by attempting to create a simple checkout page using Stripe. For this, I'm using one of their samples which uses HTML & JS for the client side and Python (Flask) for the server.
I'm struggling with the async side of the JS code. Especially fetching environmental varialbes from the server.
I have an .env file that contains my Stripe account's API keys. In the JS file, I need to fetch the Publishable Key from here, in order to initialize the Stripe instance and use Stripe Elements.
This seems very simple in my mind, but it is the first time I'm learning Javascript and I seem to can't wrap my mind on asynchronous code.
My server has the following route:
@app.route('/publishable-key', methods=['GET'])
def get_stripe_public_key():
publicKey = os.getenv('STRIPE_PUBLISHABLE_KEY')
return jsonify(publicKey)
So I'm trying to use fetch to make a GET request to this endpoint and store the Publishable Key in a variable that I can use later on to initialize Stripe:
var stripePublicKey;
fetch('/publishable-key')
.then(function(response) {
return response.json();
})
.then(function(responseJson) {
stripePublicKey = responseJson;
})
.catch(function(error) {
console.error("Error retrieving Stripe public key: " + error);
});
However, when trying to initialize Stripe later on in the code with: const stripe = Stripe(stripePublicKey)
I always get an error as stripePublicKey
is not defined.
I understand that this happens because fetch is async, and therefore, when I attempt to initialize Stripe later, stripePulicKey
hasn't been defined yet. So I tried to do something like this instead:
let stripePublicKey;
async function getStripePublicKey() {
try {
const response = await fetch('/publishable-key');
const responseJson = await response.json();
stripePublicKey = responseJson
} catch (error) {
console.error("Error retrieving Stripe public key: " + error);
}
}
getStripePublicKey();
but it still doesn't work. In this case getStripePublicKey()
only returns a Promise, but not the value of it. Is there any way to store the value of the promise in a variable, in this case?
Or alternatively, what should I be doing to fetch this key?
thank you