Hey Nicolas,
Below is a gist of my generic code to perform fetch on Wix. This has been tested against Stripe and Sendgrid. Feel free to use it.
Nicely formatted & sharable version: Generic Wix backend 3rd party API call · GitHub
backend/api/base.jsw
import {fetch} from 'wix-fetch';
import {encodeRequestBody} from 'public/utils/http.js';
// NEVER, EVER, EVER, DISCLOSE THIS SECRET KEY BELOW!!!
const YOUR_API_SECRET_KEY = 'FIXME';
/**
* A private method to perform an HTTP Fetch request towards an API
* NOTE: This method is not exposed via `export`
*
* @param {string} url - API endpoint
* @param {string} method - 'get' or 'post'
* @param {Object} data - the data in form of one-level-deep object dictionary
* @returns {PromiseLike<T> | Promise<T>}
* @private
*/
async function request(url, method, data) {
const options = {
method: method,
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
'Authorization': `Bearer ${YOUR_API_SECRET_KEY}`
},
body: encodeRequestBody(data)
};
const response = await fetch(url, options);
if (response.ok) {
return await response.json();
}
return await response.text();
}
/**
* Perform a GET method on the API with the given data
*
* @example
* import {get} from 'backend/api/base.jsw';
* get('https://api.example.com/v1/something', {source: 'some_token'})
* .then(results => handle(results, ...))
* .catch(error => handleError(error, ...));
*
* @param {string} url - API endpoint
* @param {Object} data - the data in form of one-level-deep object dictionary
* @returns {PromiseLike<T>|Promise<T>}
*/
export async function get(url, data) {
return await request(url, 'get', data);
}
/**
* Perform a POST method on the API
*
* @example
* import {post} from 'backend/api/base.jsw';
* post('https://api.example.com/v1/something', {source: 'some_token'})
* .then(results => handle(results, ...))
* .catch(error => handleError(error, ...));
*
* @param {string} url - API endpoint
* @param {Object} data - the data in form of one-level-deep object dictionary
* @returns {PromiseLike<T>|Promise<T>}
*/
export async function post(url, data) {
return await request(url, 'post', data);
}
public/utils/http.js
/**
* Encode the key:value object into URI based string
* i.e. from { key1: 'value1', key2: 'value2' }
* to 'key1=value1&key2=value2'
*
* @param {Object} bodyData - the data in form of one-level-deep object dictionary
* @returns {string} - the encoded string
*/
export function encodeRequestBody(bodyData) {
let encoded = '';
for (let [key, value] of Object.entries(bodyData)) {
encoded = `${encoded}${key}=${encodeURIComponent(value)}&`;
}
return encoded;
}