TypeError: stripe.redirectToCheckout is not a function in nuxt.js - vue.js

I am trying to integrate stripe payment gateway. I have a nuxt.js for front-end and adonis.js for backend.
From front-end I am calling an api to backend to create checkoutSession and return the sessionID. I am able to create checkoutSession and return the sessionID and in api response I am calling the
stripe.redirectToCheckout but it is not redirecting rather gives error as stripe.redirectToCheckout is not a function. How can I redirect users to checkout Page?
I have install the stripe-js file also.
import { loadStripe } from '#stripe/stripe-js'
const stripe = loadStripe(process.env.STRIPE_PK)
<button class="btn btn-primary btn-block text-center rounded" #click="checkout()">Buy</button>
import { loadStripe } from '#stripe/stripe-js'
const stripe = loadStripe(process.env.STRIPE_PK)
export default {
methods: {
checkout() {
let params = {
payment_method_types: ['card'],
line_items: [
{
name: 'Buy Now',
images: ['image.jpg'],
amount: 100 + '00',
currency: 'usd',
quantity: 1,
},
],
mode: 'payment',
success_url: `${process.env.URL}/success`,
cancel_url: window.location.href,
}
axios
.post(`${process.env.API_BASE_URL}/stripe/session`, params, {
'Content-type': 'application/json',
Accept: 'application/json',
})
.then((response) => {
this.stripeSession = response.data.data
stripe.redirectToCheckout({sessionId: this.stripeSession})
})
.catch((e) => {
console.log(e)
})
}
},
}
</script>

According to tyhe doc, loadStripe is an async function, try adding await in stripe assignement:
const stripe = await loadStripe(process.env.STRIPE_PK)
Edit:
To get rid of Module parse failed: Cannot use keyword 'await' outside an async function error you just need to add async before your function declaration :
async function myAsyncFunction() {
const test = await myPromise();
}
As I do not have the full definition of your function I cannot show it to you in your code :-(
But a weird solution (mixing 'await' and 'then') would be :
import { loadStripe } from '#stripe/stripe-js';
axios
.post(`${process.env.API_BASE_URL}/stripe/session`, params, {
'Content-type': 'application/json',
Accept: 'application/json',
})
.then(async response => {
this.stripeSession = response.data.data;
const stripe = await loadStripe(process.env.STRIPE_PK);
stripe.redirectToCheckout({ sessionId: this.stripeSession });
})
.catch(e => {
console.log(e);
});

This should work:
import { loadStripe } from '#stripe/stripe-js';
export default {
methods: {
async checkout() {
let params = {
payment_method_types: ['card'],
line_items: [
{
name: 'Buy Now',
images: ['image.jpg'],
amount: 100 + '00',
currency: 'usd',
quantity: 1,
},
],
mode: 'payment',
success_url: `${process.env.URL}/success`,
cancel_url: window.location.href,
};
try {
const { data } = await axios.post(`${process.env.API_BASE_URL}/stripe/session`, params, {
'Content-type': 'application/json',
Accept: 'application/json',
});
this.stripeSession = data.data;
const stripe = await loadStripe(process.env.STRIPE_PK);
stripe.redirectToCheckout({ sessionId: this.stripeSession });
} catch (error) {
console.error(error);
}
},
},
};

Related

how tc upload image in graphql variables with axios and formdata

Upload file with axios , graphql and formdata##
I want to upload image in the nodejs server by graphql and formdata with axios and this is my way but not working , I think this problem is in append to form data but I can not find why or in axios fetch data
Code
let data = {
query: `
mutation Mutation($image: Upload!) {
multimedia(image: $image) {
status
message
token
}
}`,
variables: {
image: null,
},
};
let map = {
0: ["variables.image"],
};
const FormD = new FormData();
FormD.append("operation", JSON.stringify(data));
FormD.append("map", JSON.stringify(map));
FormD.append(0, element.file, element.file.name);
console.log(FormD);
await axios({
url: "/",
method: "POST",
headers: {
token: token,
"Content-Type": "multipart/form-data",
},
data: FormD,
onUploadProgress:ProgressEvent=>{
element.loaded=ProgressEvent.loaded/ProgressEvent.total*100
}
})
.then((response) => {
if (response.data.errors) {
const { message } = response.data.errors[0];
toast.error(message);
} else {
setLoadedFiles(tempLoadedFiles);
}
})
.catch((error) => {
console.log(error);
});
but the response is
response
{
"message": "Request failed with status code 400",
"name": "AxiosError",
"config": {
"transitional": {
"silentJSONParsing": true,
"forcedJSONParsing": true,
"clarifyTimeoutError": false
},
"transformRequest": [
null
],
"transformResponse": [
null
],
"timeout": 0,
"xsrfCookieName": "XSRF-TOKEN",
"xsrfHeaderName": "X-XSRF-TOKEN",
"maxContentLength": -1,
"maxBodyLength": -1,
"env": {
"FormData": null
},
"headers": {
"Accept": "application/json",
"token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6IjYyZjY3NWZiODkwNjY0N2RlZWRmMTM5ZiIsImlhdCI6MTY2MDg5NTgzMSwiZXhwIjoxNjYzNDg3ODMxfQ._5gmsMHD_HRokvoopKOit1n8YhG_sP3oR_OLRSXqZTo"
},
"baseURL": "http://localhost:4000/graphql",
"url": "/",
"method": "post",
"data": {}
},
"code": "ERR_BAD_REQUEST",
"status": 400
}
thanks for your answer
I fixed this issue ,
dont use
let data = {
query: `
mutation Mutation($image: Upload!) {
multimedia(image: $image) {
status
message
token
}
}`,
variables: {
image: null,
},
};
and replace it in the axios
await axios({
url: "/",
method: "post",
headers: {
"token": token,
"Content-Type": "application/json",
},
data: {
query: `
mutation Mutation( $image : Upload!) {
multimedia(image: $image) {
status
message
}
}`,
variables: {
image: element.file,
},},
onUploadProgress: (ProgressEvent) => {
tempLoadedFiles[index].loaded =
(ProgressEvent.loaded / ProgressEvent.total) * 100;
},
})
and it's working...
this problem solve in the nodejs server
fixed it in server by:
import express from "express";
import mongoose from "mongoose";
import Router from "./routes/index.js";
import User from "./models/users.js";
import graphqlUploadExpress from 'graphql-upload/graphqlUploadExpress.js'
import { ApolloServer } from "apollo-server-express";
import MakeSchema from "../api/models/index.js";
import { config } from "../config/index.js";
const app = express();
const Application = () => {
const ServerConfig = async () => {
const server = new ApolloServer({
schema: MakeSchema,
playground: true,
introspection: "production",
formatError(err) {
if (!err.originalError) {
return err;
}
const data = err.originalError.data;
const code = err.originalError.code || 500;
const message = err.message || "error";
return { message, data, code };
},
context: async ({ req }) => {
let check;
let user;
let userInfo;
await User.VerifyToken(req).then((val) => {
check = val;
});
if (check) {
user = await User.findById(check.id);
userInfo = await User.CheckUserInfo({
fname: user.fname,
address: user.address,
});
}
if (user) {
return { role: user.role, check, userInfo };
}
return { check, role: user };
},
});
await server.start();
**app.use(graphqlUploadExpress())
app.use(express.static('public'))
app.use('/public',express.static('public'))
await server.applyMiddleware({ app });**
app.listen(config.port, () => {
console.log(`Server run on port ${config.port}`);
});
};
const DatabaseConfig = () => {
mongoose.Promise = global.Promise;
mongoose.connect(config.database.url, config.database.options);
};
const Routes=()=>{
app.use(Router)
}
ServerConfig();
DatabaseConfig();
Routes();
};
export default Application;

react native laravel echo: can not find variable pusher

i have imported laravel-echo and #pusher/pusher-websocket-react-native in react native but error occur:can not find variable pusher
please tell me solution will be thankfully
import Echo from "laravel-echo";
import {
Pusher,
PusherMember,
PusherChannel,
PusherEvent,
} from '#pusher/pusher-websocket-react-native';
let echo = new Echo({
broadcaster: "pusher",
key: "123",
wsHost: "my-domain",
wsPort: 6001,
forceTLS: false,
cluster: "mt1",
disableStats: true,
authorizer: (channel, options) => {
console.log(options);
return {
authorize: async (socketId, callback) => {
console.log('socketId, callback',channel,socketId, callback)
const response = await fetch(`http://my-domain/api/broadcasting/auth`, {
method: 'POST',
headers: {
Authorization: `Bearer ${token}`,
ContentType: 'application/json'
},
data: {
socket_id: socketId,
channel_name: channel.name,
},
})
.then((response) => {
console.log('fd',response);
callback(false, response.data);
})
.catch((error) => {
console.log('test',error)
callback(true, error);
});
},
};
},
});
=============================================================================================================================================
You must define Pusher to window
window.Pusher = Pusher;
Just write this line below the import

Error! Get request in Vuejs with axios (401 Unauthorized)

when I call the method "getStates" I unfortunately get a 401 (Unauthorized)" . But if call with GET and the same headers in Postman, it works! How i set my GET request headers??
getStates method:
getStates() {
this.axios
.get(
this.baseURL + "states",
{
params: {
id: this.city,
},
headers: {
"Authorization": "Bearer " + this.token
},
})
.then((response) => {
this.states = response.data.data;
console.warn(response.data.data);
})
.catch((err) => {});
this.apiLoaded = true;
}
try this
./App.vue :
<template>
<div id="app">
<button #click="getStatesInfo">Click</button>
<p>{{ states }}</p>
</div>
</template>
<script>
import { getStates } from "./services";
export default {
name: "App",
data() {
return {
states: "",
};
},
methods: {
getStatesInfo() {
getStates()
.then((res) => {
this.states = res;
console.log(res);
})
.catch((error) => {
console.error(error);
});
},
},
};
</script>
./services/index.js :
const baseUrl = "http://localhost:4000/";
const axios = require("axios");
const instance = axios.create({
baseURL: baseUrl,
timeout: 60000,
headers: {
"Authorization": "Bearer " + "your-token",
},
});
export async function getStates() {
const response = await instance.get("/states", {
params: {
id: "param1",
},
});
return response.data;
}

How to fetch data in Vue 3?

I don't know how to fetch data with Vue 3? I created one action and with this action I am calling endpoint (https://api.openbrewerydb.org/breweries/5494). I didn't get response data.
Endpoint:
import { createStore } from 'vuex'
export default createStore({
state: {
},
mutations: {
},
actions: {
async getData() {
await fetch('https://api.openbrewerydb.org/breweries/5494', {
method: 'get',
headers: { 'Content-type': 'application/json' },
}).then((response) => {
if (!response.ok) {
throw Error(response.statusText);
}
console.log('response: ', response)
}).catch((error) => {
console.log('Looks like there was a problem: \n', error);
});
}
},
modules: {
}
})
Vue component:
<template>
<div #click="loadData">Load Data</div>
</template>
<script>
import { useStore } from 'vuex'
export default {
name: 'HelloWorld',
props: {
msg: String
},
setup () {
const store = useStore()
const loadData = () => {
store.dispatch('getData')
}
return { loadData }
}
}
</script>
As a response I didn't get anything but I should get:
{"id":5494,"name":"MadTree Brewing","brewery_type":"regional","street":"3301 Madison Rd","address_2":null,"address_3":null,"city":"Cincinnati","state":"Ohio","county_province":null,"postal_code":"45209-1132","country":"United States","longitude":"-84.4239715","latitude":"39.1563725","phone":"5138368733","website_url":"http://www.madtreebrewing.com","updated_at":"2018-08-24T15:44:22.281Z","created_at":"2018-07-24T01:34:01.620Z"}
You need to make the data to json
.then(res=>res.json())
this will do the trick for you.
const getData = () => {
fetch('https://api.openbrewerydb.org/breweries/5494', {
headers: { 'Content-type': 'application/json' },
}).then(res=>res.json()).then((response) => {
console.log({ response })
}).catch((error) => {
console.log('Looks like there was a problem: \n', error);
});
}
getData();
If the response fails, it will surely get you to catch.
This answer Should be the accepted answer.
If readers landed here while working through the introductory examples on the Vue.js website, Adarsh's code can be adapted thusly (for Vue.js 3):
<div id="beer">
{{ message }}
</div>
const Breweries = {
data() {
return {
message: ""
}},
mounted() {
fetch('https://api.openbrewerydb.org/breweries/', {
headers: { 'Content-type': 'application/json' },
}).then(res=>res.json()).then((response) => {
this.message = response;
}).catch( (error) => {
this.message = error;
});
}
}
Vue.createApp(Breweries).mount('#beer')
First you must install a package like axios
Then create an object from axios and call the API
import axios from "axios";
export default {
setup() {
function getUsers() {
axios.get("https://jsonplaceholder.typicode.com/users")
.then(function (response) {
// handle success
console.log(response.data);
})
.catch(function (error) {
// handle error
console.log(error);
});
getUsers();
}
return { getUsers };
},
};

How to upload image in react-native using axios?

I am trying to upload Image with Axios but getting: Request failed with status code 500.I don't have backend problem because I can upload image with postman and everything is fine.
This is my addDocument() in FileUpload.js.
addDocument(){
let { title, description, imgUri } = this.state;
console.log(this.state.imgUri);
const body = new FormData();
body.append('image', {
uri: imgUri,
type: 'image',
name : `${new Date().getTime()}.jpg`,
});
addDocument(title, description, body).then((response) => {
if (response.isSuccess == true) {
this.setState({ loading: false });
this.props.navigation.navigate('FileList',{isUpdate:'true'});
}
});
};
This is my addDocument() in document.service.js.
export const addDocument = async (title, description, imageFile) => {
const trekkerId = await AsyncStorage.getItem("trekker_id");
const model = {
profileDocumentId: '',
title: title,
description: description
}
console.log(model);
console.log(imageFile);
if (trekkerId) {
return axios({
method: 'post',
url: baseUrl + "/api/Document/Document",
data: {
file: imageFile,
model: model
},
headers: {
'profileId': trekkerId,
'Authorization': 'Bearer ' + await AsyncStorage.getItem("id_token"),
'Content-Type': 'multipart/form-data'
},
}).then((response) => {
// console.log(response);
return {
isSuccess: true
};
}).catch((error) => {
console.log(error);
return {
isSuccess: false,
}
});