How to add private members to external api - api

Good afternoon all,
I am attempting to create a function that will automatically create a membership through my external loyalty program (through Whisqr) for the current user on my Wix.com website. I am receiving an error message stating the public key is not found.
Here is my backend code:
import {fetch} from 'wix-fetch';
import {wixData} from 'wix-data';
export function postLoyalty() {
let options ={
"headers": {
"X-Public": "pk_live_ba43e74df464cbf521dd07ee20443ff754c3afc11adc16df2594facb2147cd76"
}
}
const url = 'https://whisqr.com/api/v1.2/user/customer/';
const key = '<pk_live_ba43e74df464cbf521dd07ee20443ff754c3afc11adc16df2594facb2147cd76>';
console.log("Url: ");
return fetch(url, {method: 'post'})
.then(response => {
return response.json();
})
.then((data) => {
console.log(data);
return data;
});
}
Here is my page code:
import {postLoyalty} from 'backend/Loyalty.jsw';
import {wixData} from 'wix-data';
import wixLocation from "wix-location";
import {myFunction} from 'public/core.js';
import wixUsers from 'wix-users';
$w.onReady(function () {
let publickey = 'pk_live_ba43e74df464cbf521dd07ee20443ff754c3afc11adc16df2594facb2147cd76';
myFunction(publickey)
.then( (response) => {
console.log(response); //your base64 encoded string
})});
export function page1_viewportEnter(event) {
//Add your code for this event here:
let email = wixUsers.currentUser.getEmail();
postLoyalty(email)
.then(LoyaltyInfo => {
console.log(LoyaltyInfo)
$w("#text1").text = LoyaltyInfo.Results.Value;
})
}
Any and all feedback is greatly appreciated!

You are making a call to the URL using the POST method but you are not utilizing any of the keys, headers which you have defined.
A proper POST call which utilizes the header and body in its request will look like the below:
export function myFunction(data) {
const url = "https://whisqr.com/api/v1.2/user/customer/";
const headers = {
"Authorization": "Bearer " + key, //if api key is required like this
"Content-Type": "application/json" //the content type
};
return fetch(url, {
"method": "POST",
"headers": headers,
"body": JSON.stringify(data) //if there is a body
});
}
You said that you need to create a member on the external platform so you must be needing to send a body with the customer's data. Read the API Documentation.

Related

How to get data correctly using the Spotify API with React

I have the following problem when I request data from the Spotify API, at first I get it, but when I reload the page or try to write this state using useState, an error 400 or 401 occurs. The code I use to get the data:
`
import axios from 'axios';
const BASE_URL = 'https://api.spotify.com/v1';
export const fetchFromAPI = async (url: string, token: string) => {
const { data } = await axios.get((`${BASE_URL}/${url}`), {
method: 'GET',
headers: {
Accept: "application/json",
"Content-Type": "application/json",
Authorization: `Bearer ${token}`
},
});
return data;
}
`
Next, I use the fetchFromAPI function:
`
const { token } = useContext(Context);
const [albums, setAlbums] = useState<string[]>([]);
useEffect(() => {
fetchFromAPI('browse/new-releases', token)
.then((data) => console.log(data));
}, [token])
`
I've tried logging out of my account and back in, I've also tried other links to get data but it's always the same problem. I also checked if the token is present before requesting the data and it is
Ok, I managed to find and solve this error myself.
The error was that I didn't have a user token yet, but useEffect was already starting to receive data.
useEffect(() => {
if (token) {
fetchNewReleases();
fetchFeaturedPlaylists();
fetchCategories();
fetchRecommendations();
} else {
console.log('error');
}}, [token])
For example, this piece of code will print an error twice, and only after that I receive a token and can receive data from the API.
To be honest, I didn't know how to run useEffect only when I have a token, so I solved it in a simpler way, but I don't know if it's completely correct, I have the following condition Object.values(state).length) !== 0 and if it is true, only then will I display the data from the API

How to store third-party API array data into elephantSQL database using React.js front-end and node.js back-end?

Coding newbie here. So I've been trying to build a dictionary app using wordsapi and was trying to find a way to store the dictionary api into my back end. Below is my code on the front end using React.
const _addToQuollection = async (e) => {
e.preventDefault();
const apiUrl = 'http://127.0.0.1:3333/quollection/add';
const submitResponse = await fetch(apiUrl, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ word: word, definition: definition }),
})
.then((response) => response)
.catch((e) => {
console.log(e);
});
console.log("word added to quollection: ", submitResponse)
if (submitResponse.status === 200) {
console.log("submit response is success")
}
}
In my console, the req body information for word and definition array pops up as so... console.log picture showing req body for string word and array definition
But the post request is only inserting into word and not definition... QUERY: INSERT INTO quollection (word) VALUES ('quote'
My backend route using Node.js looks like this...
router.post('/add', async(req, res) => {
console.log('backend reqBody: ', req.body);
const { word, definition } = req.body;
const response = await quollectionModel.addToQuollection(word, definition);
if (response.rowCount >= 1) {
console.log('def added success!')
res.sendStatus(200)
} else {
res.sendStatus(500)
}
});
And the backend model looks like this...
static async addToQuollection(word, definition) {
try {
const response = await db.result(`INSERT INTO quollection (word, definition) VALUES ($1, $2);`, [word, definition]);
return response;
} catch (error) {
console.log('error', error.message)
return error.message
}
}
This was how I created my schema...
CREATE TABLE quollection (
id serial PRIMARY KEY,
word text,
definition text[1000000]
);
And this is the result in postico...
postico screenshot with successful word column and null definition column
Ahhh I hope this was a decent enough explanation. Any help would be much appreciated T_T Thank you!

Multi-part form data in react-admin

I'm trying to use react-admin to send data to my custom API. I want to send files, I can see that there is , I'd like to send that data as multi-part form data. I have come across the base64 encoding help page, as a newcomer to react, it is hard for me to figure out what I need to do to turn it in to multi-part form data.
If someone could walk me through the code that makes it work, that'd be great! I'm here to learn.
Thanks so much in advance.
I had the same problem, this is my solution:
import { fetchUtils } from "react-admin";
import restServerProvider from 'ra-data-json-server';
const servicesHost = 'http://my-services-host';
const httpClient = (url, options = {}) => {
if (!options.headers) {
options.headers = new Headers({ Accept: 'application/json' });
}
const token = localStorage.getItem('token');
options.headers.set('Authorization', `Bearer ${token}`);
return fetchUtils.fetchJson(url, options);
};
const dataProvider = restServerProvider(servicesHost, httpClient);
const myDataProfider = {
...dataProvider,
create: (resource, params) => {
if (resource !== 'resource-with-file' || !params.data.theFile) {
// fallback to the default implementation
return dataProvider.create(resource, params);
}
let formData = new FormData();
formData.append('paramOne', params.data.paramOne);
formData.append('paramTwo', params.data.paramTwo);
formData.append('theFile', params.data.theFile.rawFile);
return httpClient(`${servicesHost}/${resource}`, {
method: 'POST',
body: formData,
}).then(({ json }) => ({
data: { ...params.data, id: json.id },
}));
}
};
export default myDataProfider;

get item from asyncstorage in constructor and pass it to other method - react native

I have a file called Server.js in which I have written parent method to make get and post request. I am trying to extract few items from async-storage in the constructor and passing it to a method where I am assigning it to another variable. Now I have to use this variable inside my get and post method but unable to access the new variables(which are declared inside the constructor itself).
These new initialized variables are accessible by post method, but not inside the get method. When I tried some other workaround, it says that all my 3 variables ( participantId, mobeToken, urlAsync are undefined. Any input on my above issue.
variables :
1. participantId: will be sent as a header attribute (for authentication).
2. mobeToken: token for authentication, sent in Get request just like participantId.
3. urlAsync: its the url in which all the calls will be made. Once this is accessible inside Get and post method, I will remove this.baseUrl from both, Get & Post method request.
import React, { Component } from "react";
import { Alert,AsyncStorage} from 'react-native';
import axios from "axios";
const DEV_ENV_URL = "http://www.aaa.com/api";
const STAGE_ENV_URL = "http://www.bbb.com/api";
const PROD_ENV_URL = "http://www.ccc.com/api";
export default class Server extends Component {
baseUrl = DEV_ENV_URL;
constructor(props) {
super(props);
mobeToken1 = "";
participantId1 = "";
urlAsync = "";
AsyncStorage.getItem("profile", (err, res) => {
if (res !== null) {
let profile = JSON.parse(res);
participantId = profile.participantId;
} else {
profile = "";
}
AsyncStorage.getItem("mobeToken", (err, mobeToken) => {
AsyncStorage.getItem("URL", (err, Url) => {
this.assignValues(participantId, mobeToken, Url);
});
});
});
}
assignValues(participantId, mobeToken, Url) {
participantId1 = participantId;
mobeToken1 = mobeToken;
urlAsync = Url;
console.log("mobeToken1 "+ mobeToken1 + "," + participantId1 +"," + urlAsync);
}
getRequest(url) {
// debugger;
console.log(mobeToken1); // need variables in this method but can't
return fetch(this.baseUrl + url , {
method: 'GET',
headers: {
}
})
.then(response => response.json())
.then(responseJson => {
console.log(responseJson);
return responseJson;
})
.catch(error => {
console.log(error);
Alert.alert("", "Network connection issue. Please contact support");
});
}
postRequest(url, jsonData) {
return fetch(this.baseUrl + url, {
method: "POST",
headers: {
Accept: "application/json",
"Content-Type": "application/json",
// 'Content-Type': 'application/text',
"parse-array": "|entryJSONList|",
"mobeToken": mobeToken1,
"participantId": participantId1,
},
body: JSON.stringify(jsonData)
})
.then(response => response.json())
.then(responseJson => {
console.log(responseJson);
return responseJson;
})
.catch(error => {
console.log(error);
Alert.alert("", "Network connection issue. Please contact support");
});
}
}
Is there any alternative solution for this?
Thanks for viewing or providing solutions to this....

GraphCool TypeError: Converting circular structure to JSON

I copy-pasted example from official documentation in hope that I will see some different error (invalid URL or invalid auth key or something similar) However I get some webpack/sandbox error:
const fetch = require('isomorphic-fetch')
const Base64 = require('Base64')
const FormData =require('form-data')
const apiKey = '__MAILGUN_API_KEY__'
const url = '__MAILGUN_URL__'
export default event => {
const form = new FormData()
form.append('from', 'Nilan <nilan#graph.cool>')
form.append('to', 'Nikolas <nikolas#graph.cool>')
form.append('subject', 'Test')
form.append('text', 'Hi')
return fetch(url, {
headers: {
'Authorization': `Basic ${Base64.btoa(apiKey)}`
},
method: 'POST',
body: form
})
}
Even simple API requests fail:
require('isomorphic-fetch')
module.exports = function (event) {
const url = 'https://jsonplaceholder.typicode.com/posts'
return fetch(url)
}
The code above also returns:
TypeError: Converting circular structure to JSON
at Object.stringify (native)
at /data/sandbox/lib/sandbox.js:532:48
at /data/io/8e0059b3-daeb-4989-972f-e0d88e27d15e/webtask.js:46:33
at process._tickDomainCallback (node.js:481:9)
How do I successfully call API from custom graphcool subscription/resolver?
This is the simplest working example:
require('isomorphic-fetch')
module.exports = function (event) {
const url = 'https://jsonplaceholder.typicode.com/posts'
return fetch(url)
.then(res => res.json())
.then(data => {
console.log(data)
return {
data: {
sum: 3
}
}
})
}