WIX use Corvid API with 3rd party website - velo

Is there a way to use the WIX Corvid API for external App, to retrieve the product Data.
I'm not able to find the SDK which we can use.
Our Client Wants to manage it product from a different platform.
we want a way to create/update/get product and order from the WIX store.

Make sure you do not get CORS error:
Change the below origin strings to your own origin.
This should resolve your CORS issue.
import {ok, badRequest, response} from 'wix-http-functions';
function validate(origin) {
if (origin == "http://localhost:4200" || origin == "http://localhost:4201") {
return true;
} else {
return false;
}
}
export function options_yourFunctionName(request) {
console.log(request);
let headers = {
"Access-Control-Allow-Methods": "POST, GET, OPTIONS",
"Access-Control-Max-Age": "86400"
}
if (validate(request.headers.origin)) {
headers["Access-Control-Allow-Origin"] = request.headers.origin;
}
return response({ "status": 204, "headers": headers });
}
export function post_yourFunctionName(request) {
console.log("post_duxLogin");
const _response = {
"headers": {
"Content-Type": "application/json",
}
};
if (validate(request.headers.origin)) {
_response.headers["Access-Control-Allow-Origin"] =
request.headers.origin;
_response.headers["Access-Control-Allow-Headers"] = "Content-Type";
}
// Perform other things here....
}

You need to use HTTP Functions to expose your sites API. Then you can send POST requests via the external app to your site's endpoint and based on the request parameters or body you can query your product data (provided its in a database collection) and return items to the external service.
As far as create/update/get goes, you can only do that as much as the Wix Stores Backend API allows you to: https://www.wix.com/corvid/reference/wix-stores-backend.html

Related

Why can't I access wix's My Collection from my backend code?

Because I add them from the dashboard and fetch them into my flutter app with api
this is my api code:
export async function get_adminData(request) {
let options = {
"headers": {
"Content-Type": "application/json",
"Access-Control-Allow-Origin": "*"
}
};
try {
const results = await wixData.query("Admin")
.eq("url", "specificValue")
.eq("image", "specificValue")
.eq("text", "specificValue")
.eq("article", "specificValue")
.find();
if (results.items.length > 0) {
options.body = results.items;
return ok(options);
} else {
return notFound({});
}
} catch (error) {
options.body = {
"error": error
};
return serverError(options);
}
}
But I can only access collects that are under Wix App Collection.
I am new to wix and flutter so please help.
First and most obvious issue here is usually permissions issue
Try to check everything with this article
https://support.wix.com/en/article/velo-exposing-a-site-api-with-http-functions
Permissions HTTP functions, no matter how they are invoked, always run
with the permissions of an anonymous site visitor.

How to handle X-Hasura-Role with graphql codegen

Good morning,
I have an Angular WebApp that uses GraphQL codegen with (apollo-angular plugin and all the typescript plugins). Everything works fine but I want to handle Hasura Roles and Hasura User ID. From Hasura Console everything is configured correctly and working.
Only thing I am missing is how to handle this on the front end. I need to add X-Hasura-Role and X-Hasura-User-Id headers to every request sent to Hasura.
Is there a way to do this with graphql-codegen?
What is the right way to do this?
I know I can add the headers section on the codegen.yml, but obviously the role and userid are dynamic so I cannot hardcode anything there.
Should I use maybe a customFetch component? This component, thought, should only intercept every request sent to Hasura and add the headers needed. I have no idea how to do this so I hope you can help me (I also hope there is a better solution)
Best regards
When you create your Apollo client instance in the Angular application you can set it up to pass along the Authorization header which should contain the user's id and their roles.
There are examples of this in the Angular Apollo docs. Eg:
import { NgModule } from '#angular/core';
import { HttpClientModule } from '#angular/common/http';
import { Apollo, APOLLO_OPTIONS } from 'apollo-angular';
import { HttpLink } from 'apollo-angular/http';
import { InMemoryCache,ApolloLink } from '#apollo/client/core';
import { setContext } from '#apollo/client/link/context';
const uri = '/graphql';
export function createApollo(httpLink: HttpLink) {
const basic = setContext((operation, context) => ({
headers: {
Accept: 'charset=utf-8'
}
}));
const auth = setContext((operation, context) => {
const token = localStorage.getItem('token');
if (token === null) {
return {};
} else {
return {
headers: {
Authorization: `JWT ${token}`
}
};
}
});
const link = ApolloLink.from([basic, auth, httpLink.create({ uri })]);
const cache = new InMemoryCache();
return {
link,
cache
}
}
#NgModule({
exports: [
HttpClientModule,
],
providers: [{
provide: APOLLO_OPTIONS,
useFactory: createApollo,
deps: [HttpLink]
}]
})
export class GraphQLModule {}
It is up to you to ensure that the JWT token that will be passed along with your request is available in the front end. Ultimately you're going to have to implement some kind of authentication approach to allow the user to sign in and pass the token to your front end application.
More information is available in the Hasura Docs for Authentication
There are also a number of tutorials and guides for integrating with different third party auth providers

Sending appropriate error responses on web actions

I have some web-enabled actions that are exposed through API Connect in IBM Cloud Serverless Functions.
Some of my actions use request-promises to call external REST services and I need to be able to catch an error and respond with an appropriate status-code to the caller.
Since the actions are web-enabled, the documentation indicates that I can use an annotated JSON to set the headers, status-code and body of the response. But it seems that, seems the API expects to always get a Content-Type=application/json, the response processor is failing to understand my annotations in the case of an error.
I tried the following without success:
let rp = require('request-promise');
function main(params){
//setup options
return rp(options).then(
res => {
return res;
}
).catch(
err => {
return { error: { statusCode:err.statusCode } }
}
);
}
Another variation:
let rp = require('request-promise');
function main(params){
//setup options
return rp(options).then(
res => {
return res;
}
).catch(
err => {
return { statusCode:err.statusCode }
}
);
}
The problem is that the status-code I always get is 200... I also tried to change the runtime to node8.0 without success.
Thanks!
I found the answer myself :)
In order to get the status-code and headers, one must set the field Response Content Type to `Use "Content-Type" header from action", while setting up the mapping between the API call and the action....

How do I make a CORS request with fetch on my localhost?

I'm building a React/Redux app that integrates with GitHub's API. This app will require users to sign-in using GitHub's OAuth. I'm trying to use the npm package isomorphic-fetch to do the request but cannot seem to get it to work.
Here is the Request:
require('isomorphic-fetch');
var types = require(__dirname + '/../constants/action_types');
module.exports.handleAuthClick = function() {
return function(dispatch, getState) {
var state = getState();
return fetch('http://localhost:3000/auth')
.then(function(res) {
if (res.status <= 200 && res.status > 300) {
// set cookie
// return username and token
return {
type: HANDLE_AUTH_CLICK,
data: res.json()
};
}
throw 'request failed';
})
.then(function(jsonRes) {
dispatch(receiveAssignments(jsonRes));
})
.catch(function(err) {
console.log('unable to fetch assignments');
});
};
};
Here is my Router
authRouter.get('/', function(req, res) {
res.redirect('https://github.com/login/oauth/authorize/?client_id=' + clientId);
});
And here is the Error I keep getting
Fetch API cannot load https://github.com/login/oauth/authorize/?client_id=?myclientID
No 'Access-Control-Allow-Origin' header is present on the requested resource.
Origin 'http://localhost:3000' is therefore not allowed access. If an opaque
response serves your needs, set the request's mode to 'no-cors' to fetch the
resource with CORS disabled.
Looks like this is a security option which prevents a web page from making AJAX requests to different domain. I faced the same problem, and below steps fixed it.
Firstly enable CORS in the WebService app using 'package Manager' console
PM>Install-Package Microsoft.AspNet.WebApi.Cors
Inside App_Start/WebApiConfig.cs file inside the method Register (HttpConfiguration config) add code
config.EnableCors();
Finally add the [EnableCors] attribute to the class
namespace <MyProject.Controllers>
{
[EnableCors(origins: "http://example.com", headers: "*", methods: "*")]
public class MyController : ApiController
{
//some code

Node Express as proxy for a server that requires basic authentication

So I'm using express and express-http-proxy as a proxy to an API web server that requires basic authentication. Then in my app, I'll be issuing Ajax calls to these APIs. After some effort I got this working but I'm sure there's a better way out there, hence this post.
Initially I set up the express proxy as follows:
var express = require('express'),
app = express(),
proxy = require('express-http-proxy');
app.use('/apis', proxy("https://myserver", {
forwardPath: function(req, res) {
return "/apis" + require('url').parse(req.url).path;
}
}));
When calling a URL directly in the browser (not via Ajax), eg. https://myserver/apis/myapi.ashx, I would see the authentication dialog asking me for my credentials, and I could authenticate and see the result.
However, when accessing the same URL via an Ajax call in my app, I was not getting a popup. Why this difference of behavior?
So I decided I needed to add my own basic authentication middleware using request and basic-auth as follows:
var express = require('express'),
app = express(),
proxy = require('express-http-proxy'),
request = require('request'),
basicAuth = require('basic-auth');
var myAuth = function (req, res, next) {
function unauthorized(res) {
res.set('WWW-Authenticate', 'Basic realm=Rimes');
return res.sendStatus(401);
};
var user = basicAuth(req);
if (!user || !user.name || !user.pass) {
return unauthorized(res);
};
var connectUrl = 'https://'+user.name+':'+user.pass+'#myserver/apis/connect.ashx';
request.get(connectUrl, function(error, response, body) {
if (!error && response.statusCode == 200) {
return next();
} else {
return unauthorized(res);
}
});
};
app.use('/apis', proxy("https://myserver", {
forwardPath: function(req, res) {
return "/apis" + require('url').parse(req.url).path;
}
}));
This worked fine, showing me the authentication popup during the Ajax call.
The obvious disadvantage here is:
Credential verification for every API request, although there may be a way to cache valid credentials. But in its defence, this is only on the development environment.
So is there a better way of doing this? Would a different middleware package do a better job?

Resources