Symfony Api Platform not showing the api page correctly - javascript

I am working on an existing project that was created by someone in Vue.js and Symfony. Right now I am trying to integrate "the login" module but it is not working. Specifically, I cannot login. In the Login.vue file there is an API calling for login /api/login.
Here is current code:
async Login() {
const data = { username: this.email, password: this.password };
this.loading = true;
const response = await fetch(
"/api/login",
{
method: "POST",
headers: {
"Content-Type": "application/json"
},
body: JSON.stringify(data)
}
);
console.log('333', response)
let newtoken = response.token
this.$store.dispatch("loginSuccess", response.token);
await this.getMyProfile(newtoken);
if (this.$route.query.r) {
await this.$router.push({ path: this.$route.query.r });
//window.location.href = this.$route.query.r;
} else {
await this.$router.push({ path: "/center" });
// window.location.href = "/center";
}
},
But I think the API is not working. Should I set any base_url in any file? Here is my .env file. Where I am wrong?
DATABASE_URL="mysql://root:#127.0.0.1/dating_sugar_sta?serverVersion=mariadb-10.4.25&charset=utf8"

Related

React / Node - PayPal can't capture a new subscription

I wan't to capture a new paypal subscription from frontend in my backend and give response with the needed data for mongodb.
If I add a body with capture_type: 'OUTSTANDING_BALANCE' (I found that in the manual) I'm getting this error.
So I'm not sure either it's just a wrong body or i totally mess up something else in the backend but so far I can't capture the subscription even so I get a subscription Id from
createSubscription Controller
PayPalScriptProvider
<PayPalScriptProvider options={initialOptions}>
<PayPalSubscriptionButton/>
</PayPalScriptProvider>
PayPal Button
{isPending ? <LoadingMedium /> : null}
<PayPalButtons
createSubscription={(data, actions) => {
return axios
.post(
'/api/subscription',
)
.then((response) => {
return response.data.id;
});
}}
onApprove={(data, actions) => {
axios
.post(`/api/subscription/${data.subscriptionID}/capture`)
.then(() => {
axios
.patch(
`/api/activesubscription`,
{
id: activeSub[0]?._id,
subscriptionID: data.subscriptionID,
}
)
});
});
}}
/>
Route for createSubscription
router.route('/subscription').post(async (req, res) => {
const searchPlan = await SubscriptionAmount.find();
console.log(searchPlan[0]?.subscriptionAmount);
const subscription = await paypalFee.createSubscription(
searchPlan[0]?.subscriptionAmount
);
res.json(subscription);
});
Router for onApprove
router.post('/subscription/:subscriptionID/capture', async (req, res) => {
const { subscriptionID } = req.params;
console.log('subscriptionID', subscriptionID);
const captureData = await paypalFee.captureSubscription(subscriptionID);
console.log('captureData', captureData);
res.json(captureData);
});
createSubscription Controller
async function createSubscription(planId) {
const accessToken = await generateAccessToken();
const url = `${base}/v1/billing/subscriptions`;
const response = await fetch(url, {
method: 'post',
headers: {
'Content-Type': 'application/json',
Authorization: `Bearer ${accessToken}`,
},
body: JSON.stringify({
intent: 'subscription',
plan_id: planId,
}),
});
const data = await response.json();
console.log('data', data);
return data;
}
captureSubscription Controller
async function captureSubscription(subscriptionId) {
const accessToken = await generateAccessToken();
const url = `${base}/v1/billing/subscriptions/${subscriptionId}/capture`;
const response = await fetch(url, {
method: 'post',
body: JSON.stringify({
// capture_type: 'OUTSTANDING_BALANCE',
}),
headers: {
'Content-Type': 'application/json',
Authorization: `Bearer ${accessToken}`,
},
});
const data = await response.json();
console.log('data', data);
return data;
}
I'm getting this logs for my data in captureSubscription if I do not pass a body in my captureSubscription Controller:
captureData {
name: 'INVALID_REQUEST',
message: 'Request is not well-formed, syntactically incorrect, or violates schema.',
details: [
{
location: 'body',
issue: 'MISSING_REQUEST_BODY',
description: 'Request body is missing.'
}
]
}
With body I'm getting this error
captureData {
name: 'UNPROCESSABLE_ENTITY',
message: 'The requested action could not be performed, semantically incorrect, or failed business validation.',
details: [
{
issue: 'ZERO_OUTSTANDING_BALANCE',
description: 'Current outstanding balance should be greater than zero.'
}
],
}
ZERO_OUTSTANDING_BALANCE
There is no outstanding balance to capture. An outstanding balance occurs when payments are missed due to failures.
For ordinary (non-outstanding) subscription payments, no captures can be triggered. Subscriptions will capture automatically on the schedule you specify in the plan, that is the point of subscriptions.

Unable to invoke "btoa" and "item.slice" method in my script for retrieving the playlist

Whenever I am trying to invoke the "btoa" method, I am not able to use this within my script. I created a variable to store the client id: client_secret in base64. The id and secrets are being retrieved from the ".env" file.
I have also tried to use the Buffer method, but unable to use this as well. I am getting the error "invalid from" in Buffer.
can someone help me?
Please look at the full code,
const client_id = process.env.SPOTIFY_CLIENT_ID;
const client_secret = process.env.SPOTIFY_CLIENT_SECRET;
const refresh_token = process.env.SPOTIFY_REFRESH_TOKEN;
const basic = btoa(`${client_id}:${client_secret}`);
const NOW_PLAYING_ENDPOINT = `https://api.spotify.com/v1/me/player/currently-playing`;
const TOP_TRACKS_ENDPOINT = `https://api.spotify.com/v1/me/top/tracks`;
const TOKEN_ENDPOINT = `https://accounts.spotify.com/api/token`;
const getAccessToken = async () => {
const response = await fetch(TOKEN_ENDPOINT, {
method: 'POST',
headers: {
Authorization: `Basic ${basic}`,
'Content-Type': 'application/x-www-form-urlencoded'
},
body: new URLSearchParams({
grant_type: 'refresh_token',
refresh_token
})
});
return response.json();
};
export const getNowPlaying = async () => {
const { access_token } = await getAccessToken();
return fetch(NOW_PLAYING_ENDPOINT, {
headers: {
Authorization: `Bearer ${access_token}`
}
});
};
export const getTopTracks = async () => {
const { access_token } = await getAccessToken();
return fetch(TOP_TRACKS_ENDPOINT, {
headers: {
Authorization: `Bearer ${access_token}`
}
});
};
Using the above script I am trying to embed the customized Spotify play on my site. This wrapper is intended to display the top track as well.
Also, whenever I am trying to run the wrapper used to display the top tracks, it displays the following error,
Full code for displaying the top tracks:
import { type NextRequest } from 'next/server';
import { getTopTracks } from 'lib/spotify';
export const config = {
runtime: 'experimental-edge'
};
export default async function handler(req: NextRequest) {
const response = await getTopTracks();
const { items } = await response.json();
const tracks = items.slice(0, 10).map((track) => ({
artist: track.artists.map((_artist) => _artist.name).join(', '),
songUrl: track.external_urls.spotify,
title: track.name
}));
return new Response(JSON.stringify({ tracks }), {
status: 200,
headers: {
'content-type': 'application/json',
'cache-control': 'public, s-maxage=86400, stale-while-revalidate=43200'
}
});
}
The problem is that you misspelled the Bytes to ASCII function, it is btoa, not btao.
If you are looking to do it the other way around, spell it atob.

error: "unsupported_grant_type" using reddit API, javascript

During the Oauth process for reddit API, I have gotten stuck at the access token request, getting an error saying 'unsupported_grant_type'. The API documentation says to use grant type 'authorization_code' which is what I have set now. I've tried using a string, URLSearchParams, and formData to correct it thinking that it was the format that was breaking it but nothing has worked.
Here is the function in question:
async function fetchAccessToken(){
console.log("fetching access token...");
const cred = btoa(`${client_id}:${client_secret}`);
var form = new FormData()
form.append('code', authCode)
form.append('grant_type', grantType)
form.append('redirect_uri', redirect_uri)
const response = await fetch('https://ssl.reddit.com/api/v1/access_token', {
method: 'POST',
headers: {
'Content-Type':"application/x-www-form-urlencoded",
'Authorization':`Basic ${cred}`
},
body: form
})
const data = await response.json();
console.log(response.status);//says 200
console.log(data);//says {error: 'unsupported_grant_type'}
}
I've been stuck here for over a week, any help would be appreciated.
I was stuck on a similar issue - ended up using Axios.
Make sure to add a unique 'User-Agent'.
const axios = require("axios").default;
const url = require("url");
async function fetchAccessToken(){
console.log("fetching access token...");
const client_id = "";
const client_secret = "";
const username = "":
const password = "";
const authData = {
grant_type: "password",
username: username,
password: password,
};
const params = new url.URLSearchParams(authData);
const response = await axios({
url: 'https://www.reddit.com/api/v1/access_token',
method: 'POST',
headers: {
'User-Agent': "myApp:V0.1 by Dschaar", //some unique user agent
},
auth: {
username: username,
password: password,
}
params: params
})
console.log(response.data);
}

Authentication credentials are not provided - Axios

here is my action of redux:
export const addToWishlist = (id) => async (dispatch, getState) => {
try {
const {
userLogin: { userInfo },
} = getState()
const config = {
headers: {
'Authorization': `JWT ${userInfo.token}`
}
}
const { data } = await axios.post(`/api/wishlist/add_to_wishlist/${id}/`, config
)
dispatch({
type: WISHLIST_ADD_ITEM,
payload: data
})
localStorage.setItem('wishlistItems', JSON.stringify(getState().wishlist.wishlistItemsFromStorage))
} catch (error) {
dispatch({
type: WISHLIST_ADD_ITEM_FAIL,
payload: error.response && error.response.data.detail
? error.response.data.detail
: error.message,
})
}
}
so i tried to send a post request to this api end point /api/wishlist/add_to_wishlist/${id}/ it says in response(from redux extension)
type:"WISHLIST_ADD_ITEM_FAIL"
payload:"Authentication credentials were not provided."
Authentication credentials we…provided.
but when I tried the same end point using postman it worked i.e. it add the item to wishlist.
What I tried
I tried to copy the token from console and paste it on postman it worked but again not on frontend
i even tried to hard copy the same token from postman to action code and it still says the same error
I tried change the config code and added content-type = applicaton/json but all in vain.
so can you please help me. Thanks .if you are curious here is view:
#api_view(['POST'])
#csrf_exempt
#permission_classes([IsAuthenticated])
def add_to_wishlist(request, id):
product = get_object_or_404(Product, _id=id)
if product.users_wishlist.filter(id=request.user.id).exists():
product.users_wishlist.remove(request.user)
else:
product.users_wishlist.add(request.user)
return Response('your item is add to the wishlist ')
in frontend please try like this.
const config = {
method: 'post',
url: `/api/wishlist/add_to_wishlist/${id}/`,
headers: {
'Content-Type': 'application/json',
'Authorization': 'Bearer ' + token
},
data : {},
};
const { data } = await axios(config);
...

Authorization via battle.net

I try to create auth on my site via battle.net. It's my first experience in OAuth. There is documentation https://develop.battle.net/documentation/api-reference/oauth-api
Now I can get code and want to get access token by code. I provide credentials. Using Koa.js.
const { code } = ctx.query;
const redirect_uri = 'http://127.0.0.1:3000/auth';
const client_id = '0010d...25f44b31...5c34b12f4af7'
const secret = 'MY_VERY_SECRET_CODE';
const scope = 'wow.profile';
if( !code ) ctx.redirect(`https://us.battle.net/oauth/authorize?response_type=code&client_id=${client_id}&redirect_uri=${redirect_uri}&scope=${scope}`);
try {
const { data } = await axios.post('https://us.battle.net/oauth/token', {
grant_type: 'authorization_code',
code,
redirect_uri,
client_id
}, {
auth: {
username: client_id,
password: secret
}
})
console.log(data);
} catch (e) {
console.error(e)
}
ctx.body = {
message: 'OK',
}
Redirect works and I got code. But how I should build a query with the gotten code? But I got error
data:
{ error: 'invalid_request',
error_description: 'Missing grant type' } },
I should use form data type.
formData.append('grant_type', 'authorization_code');
formData.append('code', code);
formData.append('redirect_uri', redirect_uri);
formData.append('client_id', client_id);
const { data: authData } = await axios.post('https://eu.battle.net/oauth/token',
formData,
{
auth: {
username: client_id,
password: secret,
},
headers: {
'Content-Type': `multipart/form-data; boundary=${formData._boundary}`,
}
},
)

Categories

Resources