Error: Failed to load Stripe.js at HTMLScriptElement.<anonymous> - stripe-payments

I am using #stripe/stripe-js module in my javascript to run Stripe in my frontend alongside node and express in backend. I tried using the stripe cdn src='https://js.stripe.com/v3/' in my pug template and that didn't work form me, so I used the npm module.
Now every time I send request to my endpoints from frontend, I get an error:
Refused to load the script 'https://js.stripe.com/v3' because it violates the following Content Security Policy directive: "script-src 'self'". Note that 'script-src-elem' was not explicitly set, so 'script-src' is used as a fallback
Failed to load Stripe.js
at HTMLScriptElement. (bundle.js:6999:16)
but when I console the data from fetch method, I get the success result as
{message: 'success', session: {…}}
message: "success"
session:
after_expiration: null
allow_promotion_codes: null
amount_subtotal: 70000
amount_total: 70000
automatic_tax: {enabled: false, status: null}
billing_address_collection: null
cancel_url: "http://127.0.0.1:3000/accessTours/poon-hill-hot-spring-trekking"
client_reference_id: "5c88fa8cf4afda39709c2921"
consent: null
consent_collection: null
currency: "usd"
customer: null
customer_creation: "always"
customer_details: {email: 'abc#gmail.com', phone: null, tax_exempt: 'none', tax_ids: null}
customer_email: "abc#gmail.com"
expires_at: 1643568461
id: "cs_test_a1spczl6c2aTyF1K3DZ1nNmPWugoxgPqeREy4f85pHphxHx8IFUXi88UiU"
livemode: false
locale: null
metadata: {}
mode: "payment"
object: "checkout.session"
payment_intent: "pi_3KNLxZF1gqmNMMdG1Ow9eJFc"
payment_link: null
payment_method_options: {}
payment_method_types: ['card']
payment_status: "unpaid"
phone_number_collection: {enabled: false}
recovered_from: null
setup_intent: null
shipping: null
shipping_address_collection: null
shipping_options: []
shipping_rate: null
status: "open"
submit_type: null
subscription: null
success_url: "http://127.0.0.1:3000/"
total_details: {amount_discount: 0, amount_shipping: 0, amount_tax: 0}
url: "https://checkout.stripe.com/pay/cs_test_a1spczl6c2aTyF1K3DZ1nNmPWugoxgPqeREy4f85pHphxHx8IFUXi88UiU#fidkdWxOYHwnPyd1blpxYHZxWjA0TktEMElDNGJ0aEtISGFCb3JQYGM9T0F9UHFMPXAzamkxMDB3PXJKX31IUVcyQHRkTHA9cFE8ckx1SDRnY3xkU3M8PXZuSHBIcldUSmFrVzdjZGdJd3E8NTVnSEhfYnBvUScpJ2N3amhWYHdzYHcnP3F3cGApJ2lkfGpwcVF8dWAnPyd2bGtiaWBabHFgaCcpJ2BrZGdpYFVpZGZgbWppYWB3dic%2FcXdwYHgl"
[[Prototype]]: Object
[[Prototype]]: Object
Also when I check the stripe dash board there I can see incomplete payments.
Below is my code, can anyone help me with this?
import { loadStripe } from '#stripe/stripe-js';
export const session = async (tourID) => {
console.log('session');
// 1. GET CLIENT CHECKOUT SESSION FROM OUR API ENDPOINT
const url = `http://localhost:3000/api/vr1/accessBooking/client-checkout-session/${tourID}`;
// const url = `http://127.0.0.1:3000/api/vr1/accessBooking/client-checkout-session/${tourID}`;
try {
const response = await fetch(url, {
method: 'GET',
mode: 'same-origin',
});
const data = await response.json();
console.log(data);
// 2. CHARGE THE CARD WITHIN FORM
const stripe = await loadStripe(
'pk_test_51KNA5LF1gqmNMMdGjwUef8JD**MY_API_KEY**'
);
stripe.redirectToCheckout({
sessionId: data.session.id,
});
} catch (err) {
console.log(err);
}
};
But somehow I can not reach to the checkout page.

Stripe has a document about required CSP policies if you have CSP enabled in your app. Generally you would need
connect-src, https://api.stripe.com
frame-src, https://js.stripe.com, https://hooks.stripe.com
script-src, https://js.stripe.com

Related

Create LinkedIn UGC Post with Document Asset

The LinkedIn API documentation for UGC Posts seems to imply you can share a post with a document by setting shareMediaCategory: "NATIVE_DOCUMENT", but there is no additional information about how to make this work. The documentation seems limited to images/videos.
This is what I have tried so far.
const registerUpload = () => {
// Doesn't seem to be documented, but the API responses on the LinkedIn site
// returns 'urn:li:digitalmediaRecipe:feedshare-document', so it seemed like a decent guess
const type = 'document'; // 'image' or 'video' works fine
return axios({
method: 'post',
url: 'https://api.linkedin.com/v2/assets?action=registerUpload',
data: {
registerUploadRequest: {
owner,
recipes: [
`urn:li:digitalmediaRecipe:feedshare-${type}`,
],
serviceRelationships: [
{
identifier: 'urn:li:userGeneratedContent',
relationshipType: 'OWNER',
},
],
...(synchronous ? {
supportedUploadMechanism: [
'SYNCHRONOUS_UPLOAD',
],
} : {}),
},
},
headers: {
Authorization: `Bearer ${tokenInfo.token}`,
'X-Restli-Protocol-Version': '2.0.0',
},
});
}
which returns the following
{
serviceErrorCode: 100,
message: 'Field Value validation failed in REQUEST_BODY: Data Processing Exception while processing fields [/registerUploadRequest/recipes/relationshipType]',
status: 403
}
This doesn't make sense to me since registerUploadRequest/recipes/relationshipType doesn't match the documented schema. Is there another way to register document assets for UGC posts?

Unknown name "time_to_live" at 'message':

I am trying to send push notification via firebase:
await admin.messaging().sendAll({
token: 'some token',
data: {val1: '1', val2: '2'},
time_to_live: 300,
});
I am getting next error:
{"message":"Send push notification failed, Invalid JSON payload
received. Unknown name "time_to_live" at 'message': Cannot find
field.","level":"error"}
In firebase for time_to_live the key is ttl, also I use this request body for sending push notifications in android apps:
const body = {
notification: {
title: 'xxxx',
body: "xxxxxxxx"
},
data: {
notification_message: "xxxxxx"
},
token: 'xxxxxx',
android: {
ttl: 3600,
notification: { icon: 'xxxxx', color: '#b2b2b2' }
}
}
await admin.messaging().send(body)
Use ttl key in case of time_to_live.

Missing credentials while calling YouTube insert API

I want to use API key instead of OAuth token to call insert API from YouTube v3 lib. Code snippet is like below:
await google
.youtube("v3")
.videos.insert({
key: "my-youtube-api-key",
part: "id,snippet,status",
notifySubscribers: false,
requestBody: {
snippet: {
title: "Test video title",
description: "Test video description",
},
status: {
privacyStatus: "public",
},
},
media: {
body: fs.createReadStream(filePath),
},
})
.catch((err) => {
console.log("Upload to YouTube failed", err);
return null;
});
However, I am hitting error code 401, message is:
code: 401,
errors: [
{
message: 'Login Required.',
domain: 'global',
reason: 'required',
location: 'Authorization',
debugInfo: 'Authentication error: missing credentials.',
locationType: 'header'
}
]
How can I fix this issue? Isn't API key not supported? Thanks!
As per the docs, it's insufficient to use an API key on Videos.insert endpoint; you'll have to be properly authorized to call this endpoint:
Authorization
This request requires authorization with at least one of the following scopes (read more about authentication and authorization).
Scope
https://www.googleapis.com/auth/youtube.upload
https://www.googleapis.com/auth/youtube
https://www.googleapis.com/auth/youtubepartner
https://www.googleapis.com/auth/youtube.force-ssl

Unable to retrieve access token from authorisation code for Azure app

I am doing SSO to Azure AD for my Azure app using passport-azure-ad library. Following is the options object :
const options = {
identityMetadata: process.env.AZUREAD_IDENTITY_METADATA,
clientID: process.env.AZUREAD_AUTH_CLIENT_ID,
responseType: 'code id_token',
responseMode: 'form_post',
redirectUrl: process.env.AZUREAD_REDIRECT_URL,
allowHttpForRedirectUrl: true,
clientSecret: process.env.AZUREAD_AUTH_CLIENT_SECRET,
validateIssuer: false,
issuer: null,
passReqToCallback: true,
useCookieInsteadOfSession: true,
cookieEncryptionKeys: [
{ key: '********************************', iv: '************' },
{ key: '********************************', iv: '************' },
],
scope: ['profile', 'offline_access', 'https://graph.microsoft.com/mail.read'],
loggingLevel: 'info',
nonceLifetime: null,
nonceMaxAmount: 5,
clockSkew: null,
};
After getting authorisation code (req.body.code) from the AD callback, I am using that to retrieve access token for my app using adal-node library. Relevant code snippet -
const authenticationContext = new AuthenticationContext(
`https://login.microsoftonline.com/<tenant>.onmicrosoft.com`,
);
authenticationContext.acquireTokenWithAuthorizationCode(
req.body.code,
process.env.AZUREAD_REDIRECT_URL,
process.env.AZUREAD_AUTH_CLIENT_ID,
process.env.AZUREAD_AUTH_CLIENT_ID,
process.env.AZUREAD_AUTH_CLIENT_SECRET,
function(err, response) {
let message = '';
if (err) {
message = 'error: ' + err.message + '\n';
}
message += 'response: ' + JSON.stringify(response);
if (err) {
console.log(message);
return;
}
...
But this method is resulting in following error:
"error": "invalid_grant",
"error_description": "AADSTS54005: OAuth2 Authorization code was already redeemed, please retry with a new valid code or use an existing refresh token.\r\nTrace ID: 539cdaf3-460d-43fa-b4bb-6f23a8058800\r\nCorrelation ID: 507aafd9-5a4a-4417-b1f8-9fe4a5bc4cd3\r\nTimestamp: 2020-02-28 13:10:27Z",
"error_codes": [
54005
],
Also tried retrieving access token based on documentation (https://learn.microsoft.com/en-us/azure/active-directory/azuread-dev/v1-protocols-oauth-code#use-the-authorization-code-to-request-an-access-token) using Postman, but that also results in same error.
Kindly help me to figure out the mistake here.
Azure AD will no longer accept authorization codes to issue tokens that have already been used.
You need to get a new Authorization code every time. Also, you can change your code to request a refresh token that will be passed to /used by additional resources as the refresh tokens can still be reused.
Reference:
https://social.msdn.microsoft.com/Forums/en-US/4192e141-309a-4dd6-a5c9-f1a8ce32f4ca/aadsts54005-oauth2-authorization-code-was-already-redeemed

Firebase Auth REST API: OAuth sign-in with Twitter gives error 32 "could not authenticate you"

I'm writing a function in Node.js to log a user into Firebase using Twitter credentials, via the REST API (requests are made using the request library). I'm able to use the Twitter credentials to post a tweet, but attempting to sign in to Firebase with /accounts:signInWithIdp is returning the following error:
{ error:
{ code: 400,
message: 'INVALID_IDP_RESPONSE : Failed to fetch resource from https://api.twitter.com/1.1/account/verify_credentials.json?include_email=true, http status: 401, http response: {"errors":[{"code":32,"message":"Could not authenticate you."}]}',
errors: [ [Object] ] } }
This is my code:
loginWithOAuth = (idToken, postBody, onCompletion, onError) => {
var form = {
postBody: querystring.stringify(postBody),
requestUri: 'request uri',
returnIdpCredential: 'false',
returnSecureToken: 'true',
}
request.post({
url: 'https://identitytoolkit.googleapis.com/v1/accounts:signInWithIdp?key=' + firebase_api_key,
body: form,
json: true
}, (error, r, body) => {
// ...
});
}
where postBody is of the form
{
access_token: 'token',
oauth_token_secret: 'token secret',
providerId: 'twitter.com'
}
My Twitter app has permission to access user emails. I've also whitelisted the requestUri in both Firebase and Twitter. Regenerating my app & user keys doesn't make a difference.
What am I missing?
postBody is not a stringified object, it is URL encoded:
var form = {
postBody: 'access_token=[TWITTER_ACCESS_TOKEN]&oauth_token_secret=[TWITTER_TOKEN_SECRET]&providerId=twitter.com',
requestUri: 'request uri',
returnIdpCredential: 'false',
returnSecureToken: 'true',
}

Resources