1

Get Token Programmatically

(15/06/2020 03:40:08 отредактировано Jose Donoso)

Тема: Get Token Programmatically

How to get a token from Windows Services for integration to deploy with external services.

Currently I have to get it by accessing https://hosting.wialon.com/login.html

But my Windows services I must implement a function that programmatically get the token.

This is my login function to Wialon:

public Wi_Login LoginWialon ()
{
   var request = (HttpWebRequest) WebRequest
                             .Create ("https://hst-api.wialon.com/wialon/ajax.html?svc=token/login");

   // Here we need to replace the Token variable with a function that allows me to get one automatically
   // var Token = GetWialonToken (); // Get Expected Token

   var Token = "TOKEN";

   var postData = "& params = {\" token \ ": \" + Token + "\"} ";
   var data = Encoding.UTF8.GetBytes (postData);
   request.Method = "POST";
   request.ContentType = "application / x-www-form-urlencoded";
   request.ContentLength = data.Length;
   using (var stream = request.GetRequestStream ())
   {
       stream.Write (data, 0, data.Length);
   }
   var response = (HttpWebResponse) request.GetResponse ();
   var responseString = new StreamReader (response.GetResponseStream ()). ReadToEnd ();
   Wi_Login login = JsonConvert.DeserializeObject (responseString);

   return login;
}
Saludos,
Sauro Dev
2

Get Token Programmatically

Re: Get Token Programmatically

To get tokens programmatically you can acquire super-token (with -1 acl to the top user) via https://hosting.wialon.com/login.html and then create other tokens with token/update by your super-token.

3

Get Token Programmatically

Re: Get Token Programmatically

rual, thank you very much for responding. Your advice has been helpful to me.

After making a few changes implement my function GetWialonToken ();

I have passed all the parameters to the function as follows:

https://hst-api.wialon.com/wialon/ajax.html?svc=token/update&params={"callMode":"create", "userId":"ESPOLGPS", "h":"4b94588f72a6cbf3769af7987b0e46AF5B14419A1219741453BEEA77E288EA7A4AFD", "app":"test", "at":"0", "dur":"300", "fl":"2", "p":"{}"}

But I get an ERROR.

error 7: reason "OPERATION_NOT_ALLOWED: for 'create' operation you should be authorized"

Do you know the known reason for the error?

Saludos,
Sauro Dev
4

Get Token Programmatically

Re: Get Token Programmatically

Jose Donoso пишет:

error 7: reason "OPERATION_NOT_ALLOWED: for 'create' operation you should be authorized"

Currently all API requests require sid parameter with session id. Also, "userId" parameter accepts id, not name.

I wrote full example on js (nodejs) to illustrate which requests you need to do:

const https = require('https');

const TOKEN =
    'XXXX6c5XXXX8272XXXX894a47376c1e8F2XXXX2C4XXXXAF08B231D2D60XXXX2CC4F8XXXX';
const API_URL = 'https://hst-api.wialon.com/wialon/ajax.html';
const FOR_USER = 'another';

main().catch((error) => {
    console.error('[main error]', error);
});

async function main() {
    /*
        Login with our super-token to create session for other requests
    */
    let loginResult = await apiRequest({
        svc: 'token/login',
        params: {
            token: TOKEN,
            operateAs: '',
            fl: 0,
        },
    });

    let { eid: sid, au: userName } = loginResult;

    console.log(`Authorized as ${userName}`);

    /*
        Search user by name
    */
    let searchItemsResult = await apiRequest({
        sid,
        svc: 'core/search_items',
        params: {
            spec: {
                itemsType: 'user',
                propName: 'sys_name',
                propValueMask: FOR_USER,
                sortType: '',
                propType: '',
                or_logic: false,
            },
            force: 1,
            flags: 1,
            from: 0,
            to: 1,
        },
    });

    if (searchItemsResult.items.length !== 1) {
        throw new Error(`Found ${searchItemsResult.items.length} users`);
    }

    let { id: userId, nm: foundUserName } = searchItemsResult.items[0];

    /*
        Create token for found user
    */
    let createTokenResult = await apiRequest({
        sid,
        svc: 'token/update',
        params: {
            callMode: 'create',
            userId,
            app: 'Forum example',
            at: 0,
            dur: 300,
            fl: 2,
            p: '{}',
        },
    });

    console.log(
        `Token for user "${foundUserName}" (id${userId}) created: ${createTokenResult.h}`,
    );

    /*
        Logout to cleanup session
    */
    await apiRequest({
        sid,
        svc: 'core/logout',
        params: {},
    });
}

/*
    Function that does API-call
*/
function apiRequest({ svc, params, sid }) {
    return new Promise((resolve, reject) => {
        let req = https.request(
            `${API_URL}?svc=${encodeURIComponent(svc)}`,
            {
                method: 'POST',
                headers: {
                    'content-type': 'application/x-www-form-urlencoded',
                },
            },
            (res) => {
                let buffers = [];
                let totalLength = 0;

                res.on('error', reject);

                res.on('data', (data) => {
                    buffers.push(data);
                    totalLength += data.length;
                });
                res.on('end', () => {
                    let result;

                    try {
                        result = JSON.parse(
                            Buffer.concat(buffers, totalLength),
                        );
                    } catch (error) {
                        reject(error);
                        return;
                    }

                    if (!result) {
                        reject(new Error('no data'));
                        return;
                    }

                    if (result.error) {
                        reject(result);
                        return;
                    }

                    resolve(result);
                });
            },
        );

        req.on('error', reject);

        let bodyParams = [];

        if (sid) {
            bodyParams.push(['sid', encodeURIComponent(sid)]);
        }

        bodyParams.push(['params', encodeURIComponent(JSON.stringify(params))]);

        req.end(bodyParams.map((x) => x.join('=')).join('&'));
    });
}
5

Get Token Programmatically

Re: Get Token Programmatically

rual,
Again thank you very much for your time and support.

I have been able to correctly write the user search function by Name, it works perfectly and I get the data.

But, when creating the token for the found user. I get an error.

The parameters I send are:

param=
{
    callMode:create,
    userId: 1829120,
    app: 'ESPOL', ------>Is this just a descriptive value, or do I have to define it somewhere on the platform?
    at:0,
    dur: 300,
    fl: 2,
    p:{}
}

And I get the error:

{"error": 7, "reason": "CHECK_TOP_ACL_FAILED"}

Do you have any idea?

Thanks for your help.

Saludos,
Sauro Dev
6

Get Token Programmatically

Re: Get Token Programmatically

Jose Donoso пишет:

{"error": 7, "reason": "CHECK_TOP_ACL_FAILED"}

Looks like original token does not have -1 acl to be able to manage other tokens.

Try to get it with access_type=-1 — https://hosting.wialon.com/login.html?access_type=-1

7

Get Token Programmatically

Re: Get Token Programmatically

My Friend, if I had you in front, I give you a kiss!!!


Works!!!
Get Token Programmatically

I am new to this, I hope to continue learning from You Guru !!!
Thank you!!!. Anything I am at your disposal!

I work in Microsoft Visual Studio technologies, now I implement solutions in Gurtam and GateGps.


Cheers,
Jose Donoso

Saludos,
Sauro Dev
8

Get Token Programmatically

Re: Get Token Programmatically

Hi ,
I am trying to create new token with the API call


https://hst-api.wialon.com/wialon/ajax.html?svc=token/update&params={"callMode":"create","userId":"xxxxxxx","app":"MIS","at":0,"dur":300,"fl":-1,"p":{}}&sid=

I get response as
{
    "error": 4,
    "reason": "VALIDATE_PARAMS_ERROR: {app: text, at: uint, dur: uint, fl: int, p: text}"
}

Asked Gurtam official support they too confirmed my API calls looks correct , can I get some help here?

Sint
9

Get Token Programmatically

Re: Get Token Programmatically

HI ,
Found the issue (with help from Gurtam support)
"P" too should be a string "p":"{}"

Sint