Can someone help me with webhooks

Split it and then join the array back with a space or a dash. Or replace ‘\n’ with a space or dash. I haven’t found a way to pass multi-line strings to GraphQL.

Pass in the mutation with triple quotes.

I’ll give that a shot, thanks.

Now the headache of escaping them properly :face_with_symbols_over_mouth:

I haven’t tried it but I don’t think you need to put a \n in the mutation itself. It’ll just read the [ENTER] and pass it along.

I’ll find out one way or the other lol

Speaking of finding out one way or the other, I still haven’t figured out how to get a fresh access token. So I just copied a token from console log and pasted it into a variable lol. :laughing:

But at least my new integration works perfectly…

I did, and still do, a lot of hard coding when starting a project. Once I get the flow right, I then code the variables.

Here’s the flow I use for obtaining an access token:

Figure out where you’ll store the access token and expiration date.

Retrieve access token and expiration date.

If they’re null or empty, query for new access token, save access token and expiration datetime (calculate this by adding the seconds in the ‘expires_in’ field of the JSON response to current datetime. I subtract 5 minutes so I don’t have to worry about a token expiring in the middle of a transaction).

If they’re not null or empty, check the expiration datetime against current datetime and if the expiration datetime is later than now, return the stored access token. Else, query for a new access token.

I did that but my access token returns as undefined. I just need to research learn the steps of a GET request and there’s something to do with a callback function that I’m not doing correctly.

1 Like

This is from the original integration, maybe it can help.

function Authorize(callback) {
    accessToken = undefined;
    var form = { grant_type: 'client_credentials', client_secret: serverKey, client_id: 'gloria' };
    var formData = querystring.stringify(form);
    var contentLength = formData.length;

    request({
        headers: {
            'Content-Length': contentLength,
            'Content-Type': 'application/x-www-form-urlencoded'
        },
        uri: 'http://' + messageServer + ':' + messageServerPort + '/Token',
        body: formData,
        method: 'POST'
    }, function (err, res, body) {
        if (err) {
            console.log('Error while trying to authorize >', err.message);
        }
        else if (res.statusCode === 400) {
            console.log(body);
            if (callback) callback();
        }
        else {
            var result = JSON.parse(body);
            accessToken = result.access_token;
            accessTokenExpires = new Date(result['.expires']);
            if (callback) callback();
        }
    });
}
2 Likes

The form method is POST not GET.

1 Like

I’ve looked at the original integration, but I still don’t get it. I’ll just have to look into http requests.

I copied and pasted the contents of

    function Authorize(callback)

from the official Integrators’ API guide and pasted it before the if (!accessToken) line but the variable for accessToken is still undefined.
Can someone show me where to put the body of the Authorize function?

This is what my code roughly looks like

    app.use(bodyParser.json());
    app.listen(PORT, () => console.log(`Server running on port ${PORT}`));
    app.post("/", (req, res) => {
        processOrder(req.body);
        res.status(200).end();
      })

    function processOrder(order) {
        /*
        order process stuff
        a whole bunch of gql calls in here
        */
        }

    function gql (query, callback) {
        //body of Authorize(callback) function pasted here
        //......
        //......
        if (!accessToken) {
            console.log('Valid access Token is needed to execute GQL calls.')
            return;
        }
        var data = JSON.stringify({ query: query });
        request({
            headers: {
                'Content-Type': 'application/json',
               'Accept': 'application/json',
                'Authorization': 'Bearer ' + accessToken
            },
           uri: 'http://' + messageServer + ':' + messageServerPort + '/api/graphql',
            body: data,
            method: 'POST'
        }, function (err, res, body) {
            if (res.statusCode === 401) {
                console.log('Should Authorize...');
                Authorize(() => gql(query, callback));
            }
            else {
                var data = JSON.parse(body).data;
                if (callback) callback(data);
            }
        });
           }```

I’m not too familiar with javascript, but accesstoken wouldn’t be a boolean, it’s a string - shouldn’t the check be something like this:

if (accesstoken != null && accesstoken != '')

from what I see, you’re checking accesstoken before the query so it should be null before it’s assigned

have you looked at the code postman gives for this query?

Just posting what my final code roughly looks like, if any of yall are interested.

const axios = require('axios');

app.use(bodyParser.json());
app.listen(PORT, () => console.log(`Server running on port ${PORT}`));
app.post("/", async (req, res) => {
    await Authorize();
    processOrder(req.body);
    res.status(200).end();
  });

const Authorize = async () => {
    try {
        const authForm = {
            grant_type:     'client_credentials',
            client_secret:   serverKey,
            client_id:      'parseur' 
        };
        const config = {
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded'
            }
        };
        if (accessTokenExpires < new Date() || !accessTokenExpires || !accessToken) {
            const resp = await axios.post('http://localhost:9000/token', querystring.stringify(authForm), config);
            accessToken = resp.data.access_token
            accessTokenExpires = new Date(resp.data['.expires']);
            console.log('Token created');
        }
    } catch (err) {
        console.log(err);
    }
};

const processOrder = order => {
    //order processing stuff here
}
1 Like