Redirect to checkout in ReactJS - javascript

I am trying to implement the Stripe function "redirect to checkout" in ReactJS.
I have been looking around and there is no package that seems to help to do it.
const stripe =
Stripe('key');
stripe.redirectToCheckout({
items: [
// Replace with the ID of your SKU
{sku: 'sku_123', quantity: 1}
],
successUrl: 'https://your-website.com/success',
cancelUrl: 'https://your-website.com/canceled',
}).then(({error}) => {
// If `redirectToCheckout` fails due to a browser or
network
// error, display the localized error message to your
customer
// using `error.message`.
});
This is where I got this source code: https://stripe.com/docs/stripe-js/reference#stripe-redirect-to-checkout
StripeJS only seems to support the standard checkout that does not receive the product SKU as the parameter

After I read the new stripe-js docs https://stripe.com/docs/stripe-js/react
I found this might be useful for you
Instead using stripe, install #stripe/stripe-js
then the job can be done by
import { loadStripe } from "#stripe/stripe-js";
...
const stripePromise = loadStripe(
"pk_.........."
);
const stripe = await stripePromise;
stripe.redirectToCheckout({
...
})

I found out how ti make it work.
Basically as per the documentation, there is the need to import the Stripe script in public/index.html
stripe.redirectToCheckout(...)
can be simply put into the onClick of a button.
The thing that is really not clear in the docs, and that can mislead newbies like me, lies in setting the public key:
const stripe = Stripe('key');
doesn't work, because the script is not found at compile time.
This can be solved by using:
const stripe = window.Stripe('key');
This worked for me.

Related

'RestConnection Commit failed with error' when trying to write to firestore

I am getting the following error when trying to write to Firestore. This is done in JavaScript(React).Can anyone tell what is this and how can I fix this?
#firebase/firestore: Firestore (8.3.1): RestConnection Commit failed with error: {"code":"failed-precondition","name":"FirebaseError"} url: https://firestore.googleapis.com/v1/projects/{project name}/databases/(default)/documents:commit request: {"writes":[{"update":{"name":"projects/{project name}/databases/(default)/documents/teams/T22yKl1ERQSlfuZNitrvs2vRjSJ2/team-analytics/T22yKl1ERQSlfuZNitrvs2vRjSJ2-Dec-22-2021","fields":{"homePageViews":{"integerValue":"3"},"timeModified":{"timestampValue":"2021-12-22T09:32:00.000000000Z"}}},"updateMask":{"fieldPaths":["homePageViews","timeModified"]},"currentDocument":{"updateTime":"2021-12-22T09:23:08.916511000Z"}}]}
My code that is trying to access Firestore is shown below:
return db.runTransaction(async (transaction) => {
const analyticsDoc = await transaction.get(analyticsReference);
if (analyticsDoc.exists) {
const analytics: any = analyticsDoc.data();
return transaction.update(analyticsReference, { homePageViews: analytics.homePageViews + 1, timeModified: getCurrentDateTime() });
}
const newAnalytics: AnalyticsObject = {
totalViews: 0,
homePageViews: 1,
timeModified: getCurrentDateTime(),
};
return transaction.set(analyticsReference, newAnalytics);
});
I am also getting the following error in my console:
POST https://firestore.googleapis.com/v1/projects/optimx-sports/databases/(default)/documents:commit 400
Edit: After more digging in, I am thinking it might be because I am sending 2 transactions to the same document simultaneously. Is it possible that this error is because of this?
Below are a few Points you can check with:
In Cloud Firestore, you can only update a single document about once
per second, which might be too low for some high-traffic
applications. Have a look at Firestore documentation.
You can refer to the Documentation.
Also You can try with Postman API to access data.
Another way is combining two commits as well.
The issue was that I was sending two transaction commits to one firestore document within a second. The second commit was raising the above error. Fixed it by combining the two commits

Firebase 9 get single document from nested collections - React

This is my first time asking a question on here, usually I can find what I'm looking for, but I am upgrading from Firebase 8 to Firebase 9 in an ionic/react FC app, and have got some of it figured out, but I cannot figure out how to get a single document from nested collections. In Firebase 8 it would look like:
db.collection('department').doc(deptId).collection('employees').doc(empId).get()...
I have tried a couple ways with collectionGroup, and don't get anything returned at all, but I'm not even sure that is the correct way to go. Any help would be greatly appreciated!! Thanks!
If you already know syntax (and how Firebase works) of Firebase JS SDK (V8 and before), I'll highly recommend checking out the documentation as they have syntax of both side by side. Just click on the modular tab in documentation. Fetching a single document will be as shown below:
import { doc, getDoc } from "firebase/firestore";
const docRef = doc(db, "department", deptId, "employees", empId);
const docSnap = await getDoc(docRef);
if (docSnap.exists()) {
console.log("Document data:", docSnap.data());
} else {
console.log("No such document!");
}
Also checkout: Firestore: What's the pattern for adding new data in Web v9?

How to implement cookie authentication with Sveltekit & Supabase?

I'm fairly new to both SvelteKit & Supabase and have done a bit of experimentation on my own, but I would like to know what is the best way to implement user authentication with both of these technologies.
I currently have the following in my __layout.svelte file so that every page on my web application will have access to the session but I'm not sure how to implement persistent user authentication with a cookie.
If anyone can guide me and future users that would be awesome!
<script>
import supabase from "$lib/api";
import { page, session } from '$app/stores';
import { browser } from '$app/env';
if(browser){
$session = supabase.auth.session();
supabase.auth.onAuthStateChange((event, sesh) => {
$session = sesh;
});
}
</script>
It is definitely not clear how to do this. I tried to make it easy and put it into a user readable store:
export const user = readable<any>(null, (set) => {
set(supabase.auth.user());
const unsubscribe = supabase.auth.onAuthStateChange((_, session) => {
session ? set(session.user) : set(null);
});
return () => {
unsubscribe.data.unsubscribe();
}
});
Now you can just use $user anywhere to get the session, or see if there is a session.
J
The supabase project has released an example repo and a QuickStart Guide which helps by abstracting away some of the boilerplate. There's quite some modifications one needs to add so I won't re-paste all the information here as it wouldn't make sense without looking at the full solution. It's all based on a helper library https://supabase.com/docs/guides/auth/auth-helpers/sveltekit

Dynamic routing in Next.js gets TypeError: the ‘id’ argument must of type ‘string’. Received null

I’m running into an issue with generating dynamic pages in Next.js. I’m pulling data from Sanity, and I think I’ve got the code right, but every time I try load the page I get a type error - “the ‘id’ argument must be of type string. Received null”. The file path is ‘/post/[slug].js’, so that’s the variable name I’ve used throughout - I’m not sure where id is coming from, or if it’s something extra I need to pass, or if I’m not passing my slug right!
I’ve asked in the Sanity forums, and it doesn’t seem to be an API issue - I’m able to pull data in other parts of the app with no problem. In the console, it seems like the page compiles successfully, but this error comes up when attempting to load it. I’ve tried it with an empty div in the page component, to make sure it’s nothing in the presentation logic, with no luck.
I’ve put the full error message in a gist, and it looks like something with jest or next-server. For the life of me I can’t figure it out!
import client from '../../client’
const Post = ({ post }) => {
...
}
export default Post
export const getStaticPaths = async () => {
const posts = await client.fetch(`*[_type == "blog"]{ slug }`)
const paths = posts.map(post => ({
params: {
slug: post.slug.current
}
}))
return {
paths,
fallback: false }
}
export const getStaticProps = async ({ params }) => {
const post = await client.fetch(`*[_type == "blog" && slug.current == $slug]{ title, date, link, excerpt, body, slug }[0]`, {slug: params.slug})
return {
props: { post }
}
}
UPDATE: this seems to be an issue with either play.js or the configuration it uses - trying in a desktop environment doesn’t result in the same error.
I think the issue is your file name. the name should only be [slug].js, it should be located in pages/post. It should work perfectly when you access the page via the URL http://localhost:xxx/post/pulled-sanity-slug

firebase auth - get current provider javascript

I'm trying to find out what provider my user is using, and I have no idea how! the language that I use is vanilla javascript.
There's a very similar question:
Firebase Auth - get provider ID
but this only works in swift 3...
As the linked answer and Hareesh said, you will need to loop over the providerData array since a user can be signed in with multiple providers. So:
user.providerData.forEach(function(providerData) {
console.log("Signed in with "+providerData.providerId);
});
For a working example see: https://jsbin.com/vuzafuq/edit?html,js,output (check the JavaScript console for the actual providers)
I have tried multiple providers.
If you want to get all providers user have logged in, you can use user.providerData.
But the order of providerData is not based on the desc order by user log in time which the Swift SDK claimed.
This doesn't apply to Javascript SDK.
If you want to get current provider, you can decode the idToken which contain current logged in provider sign_in_provider.
The format would be something like this
{
.....
"email": ....,
"email_verified": true,
"firebase": {
"identities": {
"google.com": [
....
],
"email": [
....
]
},
"sign_in_provider": "password"
}
}
You could tried to decode by https://jwt.io/ or using npm package jsonwebtoken to decode.
Test on the firebase 7.15.0 and hope this works for you.
Firebase provides the currently signed-in provider information inside the user object like below (I have used the AngularFire Framework Library for the below example).
For the web platform, please refer to the following code:
import { AngularFireAuth } from '#angular/fire/auth';
import 'firebase/auth';
export class AuthenticationService {
constructor(private auth: AngularFireAuth) { }
getCurrentUser(){
this.auth.onAuthStateChanged((user) => {
if (user) {
// User is signed in.
user.getIdTokenResult()
.then((idTokenResult) => {
let currentProvider = idTokenResult.signInProvider;
// The result will look like 'google.com', 'facebook.com', ...
});
} else {
// No user is signed in.
}
});
}
}
For more details, check out the official doc here.
2022 Answer (Firebase v8)
I was looking for a simple little JS snippit and couldn't find one. Maybe this will help you:
// Gets the user's sign-in method
let signInMethod =
firebase.auth().currentUser?.providerData[0]?.providerId;

Categories

Resources