Is it important to hide Stripe secret key in Javascript? - javascript

I would like to know if it's important to hide my stripe key in my javascript.
In fact, in my Symfony website, I put this key in my javascript to allow users to pay their orders.
And this is how I made that:
</footer>
</body>
<script src="https://kit.fontawesome.com/47f28c9d14.js" crossorigin="anonymous"></script>
<script type="text/javascript">
var stripe = Stripe("pk_live_....");
var checkoutButton = document.getElementById("checkout-button");
checkoutButton.addEventListener("click", function () {
fetch("/orders/create-session/154154154", {method: "POST"})
.then(function (response) { return response.json(); })
.then(function (session) { if (session.error == 'order')
{ window.location.replace('/orders'); } else { return stripe.redirectToCheckout({sessionId: session.id}); } })
.then(function (result) { if (result.error) { alert(result.error.message); } })
.catch(function(error) { console.error("Error:", error); }); });
</script>
</html>
But if you open console and check the source code you can see my stripe key...
Thanks

Yes, you can use the Stripe 'publishable' key in your client side app.
More information: https://stripe.com/docs/keys?locale=en-GB

Related

Stripe checkout button does not do anything on mobile

I have integrated Stripe payment in my ASP.NET MVC app. The checkout button works on desktop and redirects user to Stripe checkout page, but the button doesn't do anything on mobile.
I tried Edge and Chrome on iOS and both are not working.
This is my JavaScript in razor page (Cart.cshtml)
<div>
#using (Html.BeginForm("", "Cart", FormMethod.Post))
{
<input type="submit" id="stripe-checkout-button" value="Stripe" />
}
</div>
<script type="text/javascript">
var stripe = Stripe('MyStripePublishKey');
var checkoutButton = document.getElementById('stripe-checkout-button');
checkoutButton.addEventListener('click', function () {
fetch('https://mywebsite.com/Cart/Checkout_Stripe', {
method: 'POST'
})
.then(function(response) {
return response.json();
})
.then(function (session) {
return stripe.redirectToCheckout({ sessionId: session.id });
})
.then(function(result) {
if (result.error) {
alert(result.error.message);
}
})
.catch(function (error) {
window.location.href = "/Cart/GatewayRedirectFailed";
console.error('Error:', error);
});
});
</script>
The button does submit the form and there is no error. Also I have to mention, the client-side validation happens, because I have a agreement checkbox which is tagged as "required", and there is a pop-over for that checkbox, pressing the button only triggers that validation.
After getting help from Stripe support, they found I can make it work by updating my JavaScript as below:
<script type="text/javascript">
var stripe = Stripe('MyStripePublishKey');
var checkoutButton = document.getElementById('stripe-checkout-button');
checkoutButton.addEventListener('click', function (event) { -- adding event parameter
event.preventDefault(); <<-- this is the key to make it work!
fetch('https://mywebsite.com/Cart/Checkout_Stripe', {
method: 'POST'
})
.then(function(response) {
return response.json();
})
.then(function (session) {
return stripe.redirectToCheckout({ sessionId: session.id });
})
.then(function(result) {
if (result.error) {
alert(result.error.message);
}
})
.catch(function (error) {
window.location.href = "/Cart/GatewayRedirectFailed";
console.error('Error:', error);
});
});
</script>
Because my form does not have any action, looks like in iPhone browser it's not working.

Can't verify password on client side

I am trying to use pdf.js on my webpage where I need to verify that the password entered by the user of PDF is correct before uploading it to the server.
But I am not able to make it work.
I used CDN hosted pdf.min.js
<script src="https://cdnjs.cloudflare.com/ajax/libs/pdf.js/2.6.347/pdf.min.js" integrity="sha512-Z8CqofpIcnJN80feS2uccz+pXWgZzeKxDsDNMD/dJ6997/LSRY+W4NmEt9acwR+Gt9OHN0kkI1CTianCwoqcjQ==" crossorigin="anonymous"></script>
and this is the password checking function:
function checkPass() {
pdfjsLib.getDocument({
url: 'pdf.pdf',
password: '01010101'
}).promise.then(function (pdf) {
input.classList.add("rightpass");
}).catch(function (error) {
input.classList.add("wrongpass");
console.log(error);
});
}
and in the console log, it logs Deprecated API usage: No "GlobalWorkerOptions.workerSrc" specified.
I tried to disable it by pdfjsLib.disableWorker = true; but it didn't work.
I just need to verify the password and nothing else no rendering.
Here is a working code sample:
<html>
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/pdf.js/2.6.347/pdf.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/pdf.js/2.6.347/pdf.worker.min.js"></script>
<script>
const pdfName = "empty-protected.pdf";
async function loaded()
{
const loadingTask = pdfjsLib.getDocument({ url: pdfName, password: "qwerty" });
loadingTask.promise.then(() => console.log(1, "OK"), (ex) => console.log(1, ex));
const loadingTask2 = pdfjsLib.getDocument({ url: pdfName, password: "" });
loadingTask2.promise.then(() => console.log(2, "OK"), (ex) => console.log(2, ex));
}
</script>
</head>
<body onload="javascript:loaded();">
</body>
</html>
Here is the password-protected pdf file (password is qwerty) that I used for the experiment:
https://mega.nz/file/lJg2GKgS#AdVJ0DZ1OfsGrlSqM67dfr_r2n8lBiiOm9q0o4wt7e4
Incliding pdf.worker.min.js changes the warning "Warning: Deprecated API usage: No "GlobalWorkerOptions.workerSrc" specified." to "Warning: Setting up fake worker."

No error but not writing into firestore. The code works in 7.9.1 but this is 7.14.1. Is this the error?

I am trying to write into Firestore using Javascript but it doesn't work although there is no error. I am using 7.14.1 version. This code ran properly on 7.9.1 so I don't know if this is the error.
<script src="https://www.gstatic.com/firebasejs/7.14.1/firebase-app.js"></script>
<script src="https://www.gstatic.com/firebasejs/7.14.1/firebase-firestore.js"></script>
<script src="https://www.gstatic.com/firebasejs/7.14.1/firebase-auth.js"></script>
<!-- TODO: Add SDKs for Firebase products that you want to use
https://firebase.google.com/docs/web/setup#available-libraries -->
<script src="https://www.gstatic.com/firebasejs/7.14.1/firebase-analytics.js"></script>
I try to console log before reading data, it works but the console log after reading data does not work.
function retriveid(){
fireauth.onAuthStateChanged(function(user) {
if (user) {
var user = fireauth.currentUser;
if (user != null) {
user.providerData.forEach(function () {
console.log("Firestore loaded");
const songname = document.getElementById('songname');
const singername = document.getElementById('singer');
const youtubelink = document.getElementById('ytlink');
const audiolink = document.getElementById('aulink')
console.log(categoryname.value, songname.value, singername.value, youtubelink.value, audiolink.value, user.uid);
firestore.collection("song").doc("Rock").set({
song_name: songname.value,
singer_name: singername.value,
youtube_link: youtubelink.value,
audio_link: audiolink.value
})
.then(function(){
console.log("Document successfully written!");
})
.catch(function(error){
console.error("Error writing document: ", error);
})
});
}
} else {
// No user is signed in.
console.log("not yet log in")
}
});
}
Hi Doug i have the same error, only you need modify the link in "...firebase-app.js" to "...firebase.js"
<script src="https://www.gstatic.com/firebasejs/7.14.1/firebase.js"></script>
the function ..listAll() works correctly. It will help you a lot, I had to consult several sources, i leave you an example:
storageRef = firebase.storage().ref('images/'+idReport);
storageRef.listAll().then(function(result) {
result.items.forEach(function(imageRef) {
// And finally display them
displayImage(imageRef);
});
}).catch(function(error) {
// Handle any errors
});
function displayImage(imageRef) {
imageRef.getDownloadURL().then(function(url) {
console.log("url", url);
}).catch(function(error) {
console.log("error", error);
});
}

Chain functions using bluebird promises in NodeJS

I'm sorry for asking yet another Promise question however, I can't quite grasp it and after reading tons of questions on here and explanations I'm still struggling.
So in my nodejs project, I'm trying to do three things.
1) Get user info from the Facebook API
graph.get(message.user, function getUserInfo(err, res) {
console.log(res)
}
2) Get a list of users from another API
request.get('https://api-url/api/users', {
'auth': {
'bearer': 'bearerAuth'
}
})
3) Check the name from the Facebook user matches a name in the JSON data I get back from my API then hand it to the user.
let aPieceOfData = "";
Bluebird.promisifyAll(graph.get(message.user))
.then(function(res) {
// this should give me the response from the Facebook API which is the user
// Then pass the response to the next .then(function(){})
})
.then(function(res) {
request.get('https://api-url/api/users', {
'auth': {
'bearer': 'bearerAuth'
}
const apiData = JSON.parse(response.body);
for (i in apiData) {
if (res.username == apiData[i].username) {
// if the username matches the user name then save some data to a variable outside this scope so I can access it
aPieceOfData = apiData[i].item;
}
}
})
})
.catch(function(err) {
console.log(err, "<<<<<<<");
})
Formatting might be a little off. But I'm struggling to understand how promises work and how I can pass the data between my chained functions than at the end save it outside my function so I can use it.
Can someone give a bit of explanation and/or some links to beginner friendlier explanations.
Based on the example from the doc
var fs = Promise.promisifyAll(require("fs"));
fs.readFileAsync("myfile.js", "utf8").then(function(contents) {
console.log(contents); }).catch(function(e) {
console.error(e.stack); });
I believe it should be like this:
var g = Bluebird.promisifyAll(graph);
g.getAsync(message.user)
.then(function (res) {
// this should give me the response from the Facebook API which is the user
// Then pass the response to the next .then(function(){})
return res;
})
.then(function (res) {
return request.get('https://api-url/api/users', {
'auth': {
'bearer': 'bearerAuth'
}
});
})
.then(function (response) {
const apiData = JSON.parse(response.body);
for (i in apiData) {
if (res.username == apiData[i].username) {
// if the username matches the user name then save some data to a variable outside this scope so I can access it
aPieceOfData = apiData[i].item;
}
}
})
.catch(function (err) {
console.log(err, "<<<<<<<");
});

How to Get Access Token Using LinkedIn API JavaScript SDK

I am trying to get LinkedIn Access Token after login. Login is working fine with JavaScript SDK and I'm able to receive "oauth_token" and member_id. I need access_token to verify the email address (if it is not forged on the way).
Below is my script:
<script>
function LoginWithLinkedIn() {
IN.User.authorize(afterAuthorization);
}
function afterAuthorization(response){
debugger
if(IN.User.isAuthorized()==true){
getProfileData();
}
}
function onSuccess(data) {
console.log(data);
}
function onError(error) {
console.log(error);
}
function getProfileData(r) {
IN.API.Profile("me")
.fields("id,firstName,lastName,email-address,picture-urls::(original),public-profile-url,location:(name)")
.result(onSuccess)
.error(onError);
}
</script>
I need help getting the access_token after successful authorization. Any help is highly appreciated!
Thanks!
Hope following code will work
function LinkedInLogin() {
IN.User.authorize(getProfileData);
}
function onSuccess(data) {
jQuery('#hdnAccessToken').val(IN.ENV.auth.oauth_token);
try {
jQuery('#hdnSocialLoginType').val('in');
jQuery('#HiddenFieldUserId').val(data.values[0].id);
jQuery('#HiddenFieldEmail').val(data.values[0].emailAddress);
jQuery('#HiddenFieldFirstName').val(data.values[0].firstName);
jQuery('#HiddenFieldLastName').val(data.values[0].lastName);
jQuery('#HiddenFieldType').val('linkedin');
jQuery('#BtnLoginSocial').click();
}
catch (err) {
alert(jQuery('#HiddenErrorMessage').val());
}
//console.log(data);
}
function onError(error) {
console.log(error);
}
function getProfileData() {
if (IN.User.isAuthorized() == true) {
IN.API.Profile("me").fields("id,firstName,lastName,email-address").result(onSuccess).error(onError);
}
}

Categories