Stripe payment method React - javascript

I am making a small ecommerce and I am using Stripe as a payment method. I got stuck on the request as I get this error:
"You did not provide an API key. You need to provide your API key in the Authorization header, using Bearer auth (e.g. 'Authorization: Bearer YOUR_SECRET_KEY'). See https://stripe.com/docs/api#authentication for details, or we can help at https://support.stripe.com/."
My code:
back:
const router = require("express").Router();
const stripe = require("stripe")(process.env.STRIPE_KEY);
router.post("/payment", (req, res) => {
stripe.charges.create(
{
source: req.body.tokenId,
amount: req.body.amount,
currency: "usd",
},
(stripeErr, stripeRes) => {
if (stripeErr) {
res.status(500).json(stripeErr);
} else {
res.status(200).json(stripeRes);
}
}
);
});
module.exports = router;
Front:
const publicToken = "pk_test..."
const secretKey = "sk_test_..."
const cart = useSelector(state => state.cart)
const navigate = useNavigate();
const [stripeToken, setStripeToken] = useState(null)
const onToken = (token) => {
setStripeToken(token)
}
useEffect(() => {
const makeRequest = async () => {
try{
const res = await userRequest.post("/checkout/payment",{
tokenId: stripeToken.id,
amount: 500,
}, {headers: { 'Authorization': 'Bearer ' + publicToken }})
navigate("/success", {data:res.data})
} catch{}
}
stripeToken && makeRequest();
}, [stripeToken, cart.total, navigate])
I tried to pass the authorization in a thousand ways and I keep getting the same error.
Any suggestions?
Thank you very much.

Related

Fetching Friends from api and Display on the frontend

i'M working on a Chat Application project
but im getting this error of fetching friends from the backend(node)
I'm getting the friends data on the console but i'm unable to display it.
this is my Context and States
export const Messenger = () => {
// Context State
const { friends, setFriends, authInfo } = useAuth();
const [loggedUser, setLoggedUser] = useState();
const { updateNotification } = useNotification();
const fetchMessengerUsers = async () => {
try {
const token = getToken();
const config = {
headers: {
authorization: "Bearer " + token,
},
};
const { data } = await client("/get-friends", config);
console.log(data);
setFriends(data);
} catch (error) {
updateNotification("error", "Failed To load the Chat");
}
};
useEffect(() => {
setLoggedUser(localStorage.getItem("auth-token"));
fetchMessengerUsers();
}, []);
then in return i'm mapping all friends to display them
<div className="friends">
{friends && friends.length > 0
? friends.map((fd) => (
<div className="hover-friend">
<Friends friend={fd} />
</div>
))
: "No Friend"}
</div>
It displays No Friend on the browser
this link shows how it appears on the browser
just change your fetchMessengerUsers function.
you need to set setFriends(data.friends)
const fetchMessengerUsers = async () => {
try {
const token = getToken();
const config = {
headers: {
authorization: "Bearer " + token,
},
};
const { data } = await client("/get-friends", config);
console.log(data);
setFriends(data.friends); // you have to set friends array here, earlier you were setting the entire object.
} catch (error) {
updateNotification("error", "Failed To load the Chat");
}
};

GET http://localhost:5000/..... 401 (Unauthorized) React

i want to fetch datas from backend with axios Authorization header.
I get token code from local storage and set it to a state.
for first load every thing is ok and datas are showin correctly.but on each render I got 401 (Unauthorized) error.
here is my code. where is the problem?
const UserManage = () => {
const [tokenCode, setTokenCode] = useState("");
const api_url = "http://localhost:5000";
const accessToken = tokenCode;
const AuthAxios = axios.create({
baseURL: api_url,
headers: {
Authorization: `Bearer ${accessToken}`,
},
});
useEffect(() => {
const loginDetail = JSON.parse(localStorage.getItem("authState"));
setTokenCode(loginDetail.token); //access token code from local storage
}, []);
const [users, setusers] = useState([])
useEffect(() => {
const fetchUsers = async() => {
const {
data
} = await AuthAxios.get(`/user/all`);
setUsers(data);
setUsers(data);
};
try {
fetchUsers();
} catch (error) {
console.log(error);
}
}, []);
}

I can't get my httpOnly cookie from my post request using axios

I am having an issue where I am not able to grab my cookies from my node.js backend. Below is my current code and when I console.log(req.cookies) It returns [Object: null prototype] {}. I had a similar issue in the past and the way I fixed that was just by adding "withCredentials: true" but since I already have that on my axios post request I don't believe that to be the issue.
Front-end
const save = async () => {
if (loggedInCookie) {
await axios.post('http://localhost:5000/savelisting', {
withCredentials: true,
link: link,
car: car,
price: price,
picture: picture,
timeleft: timeleft,
site: site,
milage: milage,
location: location,
trans: trans
});
} else {
console.log("please login to save this listing")
};
};
Backend
app.post('/savelisting', async (req, res) => {
console.log(req.cookies);
try {
var jwtToken = await req.cookies.AccessToken;
console.log(jwtToken);
// Grooms cookie
jwtToken = jwtToken
.split('; ')
.find(row => row.startsWith('AccessToken='))
.split('=')[1];
const decoded = jwt.verify(jwtToken, process.env.TOKEN_KEY);
var userId = decoded.id
console.log(userId)
const link = req.body.link;
const car = req.body.car;
const price = req.body.price;
const picture = req.body.picture;
const timeleft = req.body.timeleft;
const site = req.body.site;
const milage = req.body.milage;
const location = req.body.location;
const trans = req.body.trans;
} catch(err) {
console.log(err)
};
res.status(200).send();
});
You are sending the withCredentials setting as part of the data to your API. It should be passed as an option to axios:
axios.post(
'http://localhost:5000/savelisting',
{
link: link,
car: car,
...
},
{
withCredentials: true
}
)

functions: Error: Request failed with status code 401, twitter api auth error

I am writing code to automatically tweet, and it used to work just fine. After implementing some code changes and a cron job it began giving me this error. My code uses the twitter api v2 and auth2.0. as well as firebase/firestore and node.js to create and host servers to run the functions.
! functions: Error: Request failed with status code 401
at createError (C:\Users\EASYHOME\OneDrive\Desktop\AI twitter bot\functions\node_modules\axios\lib\core\createError.js:16:15)
at settle (C:\Users\EASYHOME\OneDrive\Desktop\AI twitter bot\functions\node_modules\axios\lib\core\settle.js:17:12)
at IncomingMessage.handleStreamEnd (C:\Users\EASYHOME\OneDrive\Desktop\AI twitter bot\functions\node_modules\axios\lib\adapters\http.js:322:11)
at IncomingMessage.emit (events.js:228:7)
at endReadableNT (_stream_readable.js:1185:12)
at processTicksAndRejections (internal/process/task_queues.js:81:21)
I am pretty sure it has to do with the authentication, I tried regenerating the access tokens and every other token, but to no avail. I did notice that on the twitter developer platform it says my access token and secret was "Created with Read Only permissions"
Here is the code in question
const functions = require("firebase-functions");
const admin = require("firebase-admin");
admin.initializeApp();
const dbRef = admin.firestore().doc("tokens/demo");
const TwitterApi = require("twitter-api-v2").default;
const twitterClient = new TwitterApi({
clientId: "client id goes here",
clientSecret: "client secret goes here",
});
const {Configuration, OpenAIApi} = require("openai");
const configuration = new Configuration({
organization: "org goes here",
apiKey: "api key goes here",
});
const openai = new OpenAIApi(configuration);
const callbackURL = "http://127.0.0.1:5001/twbot-ad868/us-central1/callback";
// STEP 1 - Auth URL
exports.auth = functions.https.onRequest(async (request, response) => {
const {url, codeVerifier, state} = twitterClient.generateOAuth2AuthLink(
callbackURL,
{scope: ["tweet.read", "tweet.write", "users.read", "offline.access"]},
);
// store verifier
await dbRef.set({codeVerifier, state});
response.redirect(url);
});
exports.callback = functions.https.onRequest(async (request, response) => {
const {state, code} = request.query;
const dbSnapshot = await dbRef.get();
const {codeVerifier, state: storedState} = dbSnapshot.data();
if (state != storedState) {
return response.status(400).send("Stored tokens do not match!");
}
const {
client: LoggedClient,
accessToken,
refreshToken,
} = await twitterClient.loginWithOAuth2({
code,
codeVerifier,
redirectUri: callbackURL,
});
await dbRef.set({accessToken, refreshToken});
const {data} = await LoggedClient.v2.me();
response.send(data);
});
exports.tweet = functions.https.onRequest(async (request, respone) => {
const {refreshToken} = (await dbRef.get()).data();
const {
client: refreshedClient,
accessToken,
refreshToken: newRefreshToken,
} = await twitterClient.refreshOAuth2Token(refreshToken);
await dbRef.set({accessToken, refreshToken: newRefreshToken});
const i = Math.floor(Math.random() * prs.length);
const nextTweet = await openai.createCompletion("text-davinci-001", {
prompt: prs[i],
temperature: 1,
max_tokens: 64,
});
const {data} = await refreshedClient.v2.tweet(
nextTweet.data.choices[0].text,
);
console.log(data);
});
exports.tweetHourly = functions.pubsub
.schedule("0 * * * *")
.onRun(async (context) => {
const {refreshToken} = (await dbRef.get()).data();
const {
client: refreshedClient,
accessToken,
refreshToken: newRefreshToken,
} = await twitterClient.refreshOAuth2Token(refreshToken);
await dbRef.set({accessToken, refreshToken: newRefreshToken});
const i = Math.floor(Math.random() * prs.length);
const nextTweet = await openai.createCompletion("text-davinci-001", {
prompt: prs[i],
temperature: 1,
max_tokens: 64,
});
const {data} = await refreshedClient.v2.tweet(
nextTweet.data.choices[0].text,
);
console.log(data);
});

Axios POST with the server responded with a status of 500 (Internal Server Error)

I'm using ReactJS to build a blog app. I can use axios get, put, delete but NOT POST. Every time I post a new blog, it gives me server responded with a status of 500 (Internal Server Error).
I have been struggle with this issue for a week and couldn't figure out the reason. Thank you very much for your help! Let me know if you need additional information.
Here are my codes:
API
import axios from 'axios'
const baseUrl = `/api/blogs`
let token = null
const setToken = newToken => {
token = `bearer ${newToken}`
}
const getAll = () => {
const request = axios.get(baseUrl)
return request.then(response => response.data)
}
const create = async newBlog => {
const config = {headers: { Authorization: token }}
const response = await axios.post(baseUrl, newBlog, config)
return response.data
}
const update = async (id, newObject) => {
const request = axios.put(`${baseUrl}/${id}`, newObject)
const response = await request
return response.data
}
const remove= async (id) => {
const config = {headers: { Authorization: token }}
const request = axios.delete(`${baseUrl}/${id}`, config)
const response = await request
return response.data
}
const exportedObject = { getAll, create, update, setToken, remove }
export default exportedObject
Frontend App.js
import React, { useState, useEffect, useRef } from 'react'
import blogService from './services/blogs'
import loginService from './services/login'
import Blog from './components/Blog'
import LoginForm from './components/LoginForm'
import BlogForm from './components/BlogForm'
import Togglable from './components/Togglable'
import Notification from './components/Notification'
import axios from 'axios'
const App = () => {
const [blogs, setBlogs] = useState([])
const [username, setUsername] = useState('')
const [password, setPassword] = useState('')
const [user, setUser] = useState(null)
const [loginVisible, setLoginVisible] = useState(false)
const [notificationText, setNotificationText] = useState("")
const [notificationStyle, setNotificationStyle] = useState("notification")
const [Toggle, setToggle] = useState(false)
const BlogFormRef = useRef()
useEffect(() => {
const Data = async () => {
const initialBlogs = await blogService.getAll()
setBlogs( initialBlogs )
}
Data()
}, [])
useEffect(() => {
const loggedUserJSON = window.localStorage.getItem('loggedBlogUser')
if (loggedUserJSON) {
const user = JSON.parse(loggedUserJSON)
setUser(user)
blogService.setToken(user.token)
}
}, [])
const addBlog = async (blogObject) => {
BlogFormRef.current.toggleVisibility()
if (blogObject.title !== '' && blogObject.author !== '' && blogObject.url !== '') {
const newBlog = await blogService.create(blogObject)
setBlogs(blogs.concat(newBlog))
setNotificationStyle('notification')
setNotificationText(`A new blog ${blogObject.title} by ${blogObject.author} is added`)
setToggle(!Toggle)
setTimeout(() => {
setToggle(false)
}, 5000)
setBlogs('')
console.log(blogObject)
document.location.reload()
} else {
setNotificationStyle('Warning')
setNotificationText('You must fill all fields to create a blog')
setToggle(!Toggle)
setTimeout(() => {
setToggle(false)
}, 5000)
}
}
Backend
const blogsRouter = require('express').Router()
const Blog = require('../models/blog')
const User = require('../models/user')
const jwt = require('jsonwebtoken')
const middleware = require("../utils/middleware")
blogsRouter.get('/', async (request, response) => {
const blogs = await Blog.find({}).populate('user', { username: 1, name: 1 })
response.json(blogs)
})
blogsRouter.get('/:id', (request, response) => {
Blog.findById(request.params.id)
.then(blog => {
if (blog) {
response.json(blog)
} else {
response.status(404).end()
}
})
})
blogsRouter.post('/', middleware.userExtractor, async (request, response) => {
const body = request.body
const user = request.user
const decodedToken = jwt.verify(request.token, process.env.SECRET)
if (!decodedToken.id){
return response.status(401).json({error: 'token missing or invalid'})
}
if(body.title === undefined){
return response.status(400).send({
error: 'title is missing'
})
}
else if(body.author === undefined){
return response.status(400).send({
error: 'author is missing'
})
}
else if(body.url === undefined){
return response.status(400).send({
error: 'url is missing'
})
}
else{
const blog = new Blog({
title: body.title,
author: body.author,
url: body.url,
likes: body.likes,
user: user.id
})
const savedBlog = await blog.save()
//console.log(savedBlog)
//console.log(user)
user.blogs = user.blogs.concat(savedBlog.id)
await user.save()
const populatedBlog = await savedBlog.populate('user', { username: 1, name: 1 }).execPopulate()
response.status(200).json(populatedBlog.toJSON())
}
})
blogsRouter.delete('/:id', middleware.userExtractor, async (request, response) => {
const blog = await Blog.findByIdAndRemove(request.params.id)
const user = request.user
const decodedToken = jwt.verify(request.token, process.env.SECRET)
if(! request.token || !decodedToken.id){
return response.status(401).json({error:'token is missing or invalid'})
}
else if(blog.user.toString() === user.id.toString()){
await Blog.findByIdAndRemove(request.params.id)
response.status(204).end()
}
else{
return response.status(401).json({error:'cannot process deletion'})
}
})
blogsRouter.put('/:id', async (request, response) => {
const body = request.body
const blog = {
title: body.title,
author:body.author,
url: body.url,
likes: body.likes
}
await Blog.findByIdAndUpdate(request.params.id, blog, { new: true })
.then(updatedBlog => {
response.json(updatedBlog)
})
})
module.exports = blogsRouter
Mongoose
const mongoose = require('mongoose')
const blogSchema = new mongoose.Schema({
title: {type:String,
required: true},
author:{type:String,
required: true},
url: {type:String,
required: true},
likes: {type:Number,
default: 0},
user: {
type: mongoose.Schema.Types.ObjectId,
ref: 'User'}
})
blogSchema.set('toJSON', {
transform: (document, returnedObject) => {
returnedObject.id = returnedObject._id.toString()
delete returnedObject._id
delete returnedObject.__v
}
})
const Blog = mongoose.model('Blog', blogSchema)
module.exports = Blog
Additional information: terminate output, the info is actually POST just cannot render in the front
terminal output

Categories