skydiver / ewelink-api

eWeLink API for JavaScript
https://www.npmjs.com/package/ewelink-api
MIT License
268 stars 108 forks source link

Error 401: Wrong account or password -- again #220

Open nareso opened 1 year ago

nareso commented 1 year ago

I got an Error 401 same as #212 today. https://github.com/skydiver/ewelink-api/issues/212

This error does not occur with sonoff devices but occurs with 4ch products that have the PSF-B04 module when using setDevicePowerState methods.

Is there anyone with the same symptoms?

nareso commented 1 year ago

Correction, sonoff devices also become errors.

nareso commented 1 year ago

I found a temporary workaround.

APP_ID: Uw83EKZFxdif7XFXEsrpduz5YyjP7nTl APP_SECRET: mXLOjea0woSMvK9gw7Fjsy7YlFO4iSu6 works for me.

Thanks, LiorLindvor. https://github.com/skydiver/ewelink-api/issues/212#issuecomment-1485629138

antonioGabrielGomes commented 1 year ago

after registering your ewelink account and creating app, did your app_id and secret_id work normally?

karocavo commented 1 year ago

I've had little problem finding correct directory under my portainer node-red install, found here: //data/node_modules/ewelink-api/src/data$ -if anyone has same problem. Using vi editor I have changed the credentials as above (or create your own under dev.ewelink.cc) and the auth problem solved now!

mduchain commented 1 year ago

@antonioGabrielGomes , all, I've created my own APP_ID & APP_SECRET on dev.ewelink.cc, - standard role. However this doens't fully work. I can get devices and events just fine, but all other nodes just give me "wrong account or password".

With the above credentials from @nareso , I get full functionality. At this point, should I assume the issue is with the role?

antonioGabrielGomes commented 1 year ago

@karocavo

I did that but got the same error

antonioGabrielGomes commented 1 year ago

@mduchain

It could be the type of account we're creating, maybe individual developer access doesn't have permissions.

ghost commented 1 year ago

Regarding authorization issues, accounts created by individual developers can only be redirected to the authorization page for login. So it cannot directly request the login interface to obtain a Token, the specific information is here: https://coolkit-technologies.github.io/eWeLink-API/#/en/OAuth2.0

nareso commented 1 year ago

Hi carl , thanks for your reply.

I do not understand the Create application procedure, but how should I describe it in the redirect URL field?

By the way, in my account, I can login with https://dev.ewelink.cc/#/login, but with https://c2ccdn.coolkit.cc/oauth/index.html the login process does not proceed.

ghost commented 1 year ago

This is an example of eWeLink OAuth2.0 login:https://github.com/coolkit-carl/eWeLinkOAuthLoginDemo

nareso commented 1 year ago

Hi carl, thank you very much for your kind explanation.

But, I can't find config.js in ewelink-api directory. Isn't your example for ewelink-api-next?

Please tell me the create application procedure when using ewelink-api.

karocavo commented 1 year ago

Hi carl, thank you very much for your kind explanation.

But, I can't find config.js in ewelink-api directory. Isn't your example for ewelink-api-next?

Please tell me the create application procedure when using ewelink-api.

The file to overwrite keys from previous comments is in directory path i’ve mentioned specifically in case of a portainer install (NAS)- keys from ewelink.cc supposedly do not work, as written above

antonioGabrielGomes commented 1 year ago

Hi carl , thanks for your reply.

I do not understand the Create application procedure, but how should I describe it in the redirect URL field?

By the way, in my account, I can login with https://dev.ewelink.cc/#/login, but with https://c2ccdn.coolkit.cc/oauth/index.html the login process does not proceed.

the same here.

karocavo commented 1 year ago

Well, I've had problems with Error 401, now it's gone. I have not created API myself, but used keys from this post - APP_ID: Uw83EKZFxdif7XFXEsrpduz5YyjP7nTl APP_SECRET: mXLOjea0woSMvK9gw7Fjsy7YlFO4iSu6 /by nareso/ and changed these in settings.js file under command line in nodered container - attached pic for reference nr2

antonioGabrielGomes commented 1 year ago

Regarding authorization issues, accounts created by individual developers can only be redirected to the authorization page for login. So it cannot directly request the login interface to obtain a Token, the specific information is here: https://coolkit-technologies.github.io/eWeLink-API/#/en/OAuth2.0

Thanks for the info. Now, with the individual developer method, we can integrate with devices ? making a boost on the demo you sent?

ghost commented 1 year ago

Uw83EKZFxdif7XFXEsrpduz5YyjP7nTl It is an APPID that should not be used, please ignore it.

Through personal developer methods, it is possible to integrate with devices. I will add an example of obtaining device information and controlling devices later, but the specific content needs to be configured based on your device.

ghost commented 1 year ago

Updated, feat: Add device examples to control the current login account https://github.com/coolkit-carl/eWeLinkOAuthLoginDemo

thomas350 commented 1 year ago

@coolkit-carl can we say at least that it is really messy ?? Why Ewelink disables v1 interface while v2 interface does not work for production ?

On my side, my own app_id and app_secret doesn't work but this app_id works : Uw83EKZFxdif7XFXEsrpduz5YyjP7nTl Which is really weird.

Can you explain us how to easily use your ewelink-api-next to basically turn on/off a device please ?

Documentation here : https://coolkit-technologies.github.io/eWeLink-API/#/en/OAuth2.0 Or here : https://github.com/coolkit-carl/eWeLinkOAuthLoginDemo are clearly not understandable and seems to not be stable at all.

ghost commented 1 year ago
  1. Can you give an example of why you feel unstable? The v2 interface has been running and maintained for 3 years, and there have been no significant changes to the interface.
  2. We have stopped maintaining the v1 interface. Its security is not as high as the v2 interface, and its functionality is not as comprehensive as the v2 interface. Stopping is inevitable. 3 https://github.com/coolkit-carl/eWeLinkOAuthLoginDemo <https://github.com/coolkit-carl/eWeLinkOAuthLoginDemo > I updated the latest document for this project yesterday and wrote about the entire process.
  3. ewelink-api-next actually has basic examples. In the next few days, it will be open source and provide additional documentation for all functions (in fact, if you use TypeStript, you will get a more perfect prompt, and its source code also has annotations). Dep:产品部|解决方案工程师 Name:刘家乐 @. @. > Tel:+86(0)755 26404901 Mob:+86 18598029557

    发件人:thomas350 @.> 发送时间:2023年8月16日(星期三) 19:48 收件人:skydiver/ewelink-api @.> 抄 送:刘家乐 @.>; Mention @.> 主 题:Re: [skydiver/ewelink-api] Error 401: Wrong account or password -- again (Issue #220) @coolkit-carl <https://github.com/coolkit-carl > can we say at least that it is really messy ?? Why Ewelink is disabling v1 interface while v2 interface does not work for production ? On my side, my own app_id and app_secret doesn't work but this app_id works : Uw83EKZFxdif7XFXEsrpduz5YyjP7nTl Which is really weird. Can you explain us how to easily use your ewelink-api-next to basically turn on/off a device please ? Documentation here : https://coolkit-technologies.github.io/eWeLink-API/#/en/OAuth2.0 <https://coolkit-technologies.github.io/eWeLink-API/#/en/OAuth2.0 > Or here : https://github.com/coolkit-carl/eWeLinkOAuthLoginDemo <https://github.com/coolkit-carl/eWeLinkOAuthLoginDemo > are clearly not understandable and seems to not be stable at all. — Reply to this email directly, view it on GitHub <https://github.com/skydiver/ewelink-api/issues/220#issuecomment-1680456963 >, or unsubscribe <https://github.com/notifications/unsubscribe-auth/AMDDIXVSHSAIYH2XMKDTXDTXVSXRZANCNFSM6AAAAAA3K5OG2Q >. You are receiving this because you were mentioned.Message ID: @.***>

antonioGabrielGomes commented 1 year ago
  1. Can you give an example of why you feel unstable? The v2 interface has been running and maintained for 3 years, and there have been no significant changes to the interface. 2. We have stopped maintaining the v1 interface. Its security is not as high as the v2 interface, and its functionality is not as comprehensive as the v2 interface. Stopping is inevitable. 3 https://github.com/coolkit-carl/eWeLinkOAuthLoginDemo <https://github.com/coolkit-carl/eWeLinkOAuthLoginDemo > I updated the latest document for this project yesterday and wrote about the entire process. 4. ewelink-api-next actually has basic examples. In the next few days, it will be open source and provide additional documentation for all functions (in fact, if you use TypeStript, you will get a more perfect prompt, and its source code also has annotations). Dep:产品部|解决方案工程师 Name:刘家乐 @. @. > Tel:+86(0)755 26404901 Mob:+86 18598029557 ------------------------------------------------------------------ 发件人:thomas350 @.> 发送时间:2023年8月16日(星期三) 19:48 收件人:skydiver/ewelink-api @.> 抄 送:刘家乐 @.>; Mention @.> 主 题:Re: [skydiver/ewelink-api] Error 401: Wrong account or password -- again (Issue #220) @coolkit-carl <https://github.com/coolkit-carl > can we say at least that it is really messy ?? Why Ewelink is disabling v1 interface while v2 interface does not work for production ? On my side, my own app_id and app_secret doesn't work but this app_id works : Uw83EKZFxdif7XFXEsrpduz5YyjP7nTl Which is really weird. Can you explain us how to easily use your ewelink-api-next to basically turn on/off a device please ? Documentation here : https://coolkit-technologies.github.io/eWeLink-API/#/en/OAuth2.0 <https://coolkit-technologies.github.io/eWeLink-API/#/en/OAuth2.0 > Or here : https://github.com/coolkit-carl/eWeLinkOAuthLoginDemo <https://github.com/coolkit-carl/eWeLinkOAuthLoginDemo > are clearly not understandable and seems to not be stable at all. — Reply to this email directly, view it on GitHub <#220 (comment) >, or unsubscribe <https://github.com/notifications/unsubscribe-auth/AMDDIXVSHSAIYH2XMKDTXDTXVSXRZANCNFSM6AAAAAA3K5OG2Q >. You are receiving this because you were mentioned.Message ID: @.***>

Does the method in the demo not work for 4ch devices? and does the library work to enable and disable devices in real time?

ghost commented 1 year ago
  1. For 4ch devices, the control instructions are different and the method is the same. Change {"switch": "on"} to {"switches": [{"switch": "off", "outlet": 0}, {"switch": "off", "outlet": 1}, {"switch": "off", "outlet": 2}, {"switch": "off", "outlet": 3}]} to complete this section https://coolkit-technologies.github.io/eWeLink-API/#/en/UIIDProtocol It is stated in the document.

  2. It supports real-time control of devices, whether through interfaces or websockets.

nareso commented 1 year ago

Hi carl

I noticed that the object structure has changed between V1 and V2. For example, an ”off” information of a single switch from node-red-contrib-ewelink are V1 --- msg.payload.params.switch: "off" V2 --- msg.payload.params.switch.switch: "off" Like, it's one layer deep.

Could these changes be the reason that node-red-contrib-ewelink doesn't work properly with V2 interfaces?

ghost commented 1 year ago

No, the action for controlling the device have not changed. We have only changed the interface domain name, path, and parameter transfer method.

nareso commented 1 year ago

The change from V1 object {"switch":"off"} to V2 object {"switch":{"switch":"off"}} is a very big change for me.

To which of the described changes does such a change apply?

ghost commented 1 year ago

There is no change, {"switch": {"switch": "off"}} is incorrect.

nareso commented 1 year ago

Here is my environment and results.

Nod-red version : v3.0.2 node-red-contrib-ewelink version : 2.0.0 node: ewelink-generic-device input : {"method":"getDevice"}

Using V1 API output path of "off" is msg.payload.params.switch: "off"

Using V2 API output path of "off" is msg.payload.params.switch.switch: "off"

please confirm.

thomas350 commented 1 year ago

@coolkit-carl

Can you explain us how to easily use your ewelink-api-next to basically turn on/off a 4ch device please ?

Documentation here : https://coolkit-technologies.github.io/eWeLink-API/#/en/OAuth2.0 Or here : https://github.com/coolkit-carl/eWeLinkOAuthLoginDemo are clearly not understandable and doesn't have example.

Thank you.

PhilETaylor commented 1 year ago

Ok I have this working for my hallway 2 channel light switch. I can turn them on and off right now.

in plain English:

  1. Learn what OAuth is... or follow the instructions at https://github.com/coolkit-carl/eWeLinkOAuthLoginDemo to run a local web server and login - after that you will be redirected back to your redirectUrl and a token.json will be saved with your authentication tokens. Keep this safe!

  2. run controlDeviceDemo.js - this listed all my devices... that was good, but the code to toggle the first device as a demo did not work for me... but having the list of devices showed that I was authenticated correctly.

  3. By trial and error I worked out then that I could pass the following code

await client.device.setThingStatus({
          type: 1,
          id: '10007bc171', // not my real id, but I used my real id here
          params:
            {
              "switches": [
                {"switch": "on", "outlet": 0},
                {"switch": "on", "outlet": 1}
              ]
            }
        })

AND MY LIGHTS TURNED ON....

  1. with some playing I was able to dump the actual HTTP request that was being made, which simply looks like (This is not code that you can copy and paste from this comment to make it work, this is a dump of the request for you to look at, and to compile your own HTTP Request that looks like this - any decent developer should be able to make a HTTP request in their programming language of choice)
Send request:  {
  url: '/v2/device/thing/status',
  method: 'post',
  baseURL: 'https://eu-apia.coolkit.cc',
  headers: AxiosHeaders {
    Accept: 'application/json, text/plain, */*',
    'Content-Type': 'application/json',
    Authorization: 'Bearer aa0dbbf06cd1NOTMYREALKEY8e84f9a09ffe536d62',
    'X-CK-Nonce': '4s3p08wn',
    Date: '1692398015055'
  },
  params: undefined,
  data: '{"type":1,"id":"10007bc171","params":{"switches":[{"switch":"off","outlet":0},{"switch":"off","outlet":1}]}}'
}

So now I have a proof of concept working in Javascript, I can switch back to PHP and write real HTTP requests, that consume the OAuth Endpoint, which gives me a token to store, and then I can then just use any HTTP client (mine will continue to be PHP) to make http requests

Once you have an access token from OAuth you can call any of the APIs - here is a scaled down request, made by standard curl command

curl --location 'https://eu-apia.coolkit.cc/v2/device/thing/status' \
--header 'X-CK-Nonce: 9e3NOTREALwR7' \
--header 'Authorization: Bearer 90e4e9c7de5NOTMYREALTOKENd36154e3bbc2' \
--header 'Content-Type: application/json' \
--data '{
    "type": 1,
    "id": "10007bc171",
    "params": {
        "switches": [
                {"switch": "on", "outlet": 1}
              ]
    }
}'

The above all works in real life in my house today. Im not @coolkit-carl, Im a PHP dev with API experience :)

If you are looking for a non-technical project where you can just input your username and password to a config file, and magically control your devices, then you can no longer do that. But if you are willing to learn basic development (like OAuth which is pretty much industry standard for authenticating and authorising external services nowadays) then that can be "easily" done.

The old ewelink-api project should be considered deprecated and no longer used.

PhilETaylor commented 1 year ago

I will also just note that the OAuth 2.0 process they are using is crazy and non-standard. If it were standard OAuth then tools like PostMan would be able to get access tokens automatically.

The Authorisation parameters are simply wrong for standard OAuth -https://coolkit-technologies.github.io/eWeLink-API/#/en/OAuth2.0?id=authorization-page-description (eg client_id is right clientId is non-standard etc.)

The PostMan Collection/Environment provided as an example (https://coolkit-technologies.github.io/eWeLink-API/#/en/APICenterV2?id=postman-example), doesnt even support auto Oauth2.0 to get a bearer token :( so at the moment the only way to get/refresh your token is with the demo app that was provided as an example https://github.com/coolkit-carl/eWeLinkOAuthLoginDemo - or to hand code your OAuth authorisation signature as per the documentation on how to hash the authorisation signatures.

nareso commented 1 year ago

Thank you for your detailed explanation.

Now, when the V1 interface is deprecated, I would like an alternative environment for ewelink-api, but if anyone knows a recommended environment, please let me know.

Development candidates that can control ewelink device with low code are

  1. node-red-contrib-ewelink-cube In my testing, it's still unstable.
  2. Homeassiatant Add-on eWeLink Smart Home Does this use the V2 interface?
  3. homebridge-ewelink Does this use the V2 interface?
  4. other candidates

Any comments would be appreciated.

antonioGabrielGomes commented 1 year ago

@coolkit-carl Can you show a valid example of token refresh?

ghost commented 1 year ago

@coolkit-carl您能展示一个令牌刷新的有效示例吗? https://github.com/coolkit-carl/eWeLinkOAuthLoginDemo/blob/main/controlDeviceDemo.js

AndreFvdMerwe commented 1 year ago

@coolkit-carl您能展示一个令牌刷新的有效示例吗? https://github.com/coolkit-carl/eWeLinkOAuthLoginDemo/blob/main/controlDeviceDemo.js

@coolkit-carl . I have registered and received my APPID and APPsecret, used both to update ewelink api in node-red on the rpi. I receive all info on my own devices on NodeRed using "devices" node. IT WORKS !!!

Problem: However, in NodeRed "devices" node I do not receive any info on devices shared with me from other ewelink users.

HOW can I set to also receive info on devices shared with me by others in "devices" node?

( Note: on Home Assistant I am receiving info from both my own sonoff devices, and from sonoff devices shared with me by other users. BUT, it does not work the same in NodeRed)

UPDATE: I tested NodeRed "event listener". There I do receive info from devices shared with me

ghost commented 1 year ago

@coolkit-carl您能展示一个令牌刷新的有效示例吗? https://github.com/coolkit-carl/eWeLinkOAuthLoginDemo/blob/main/controlDeviceDemo.js

@coolkit-carl . I have registered and received my APPID and APPsecret, used both to update ewelink api in node-red on the rpi. I receive all info on my own devices on NodeRed. IT WORKS !!!

Problem: However, in NodeRed I do not receive any info on devices shared with me from other ewelink users.

HOW can I set to also receive info on devices shared with me by others ?

( Note: on Home Assistant I am receiving info from both my own sonoff devices, and from sonoff devices shared with me by other users. BUT, it does not work the same in NodeRed)

Please provide me with a shared device ID, and I will check the device status for you. In theory, this situation can only occur on the device shared with you, and its brand is not included in the free authorization list of eWeLink.

mduchain commented 1 year ago

@coolkit-carl, I confirm the same behavior reported by @AndreFvdMerwe. I use two accounts, and only account 1 has the devices. Account 1 has shared all devices with account 2 via android app ewelink. On the android app, all devices are visibile when using account 2. Yet, the nodered node "devices" returns an empty array when using account 2. Using account 1, I get the full list of devices. device id: 1000a4f037

AndreFvdMerwe commented 1 year ago

my own device: 10017c1e94 shared with me device: 10017c198a

ghost commented 1 year ago

my own device: 10017c1e94 shared with me device: 10017c198a

10017c1e94 SONOFF UIID181, switch control command: {"switch": "on"} or {"switch": "off"}

10017c198a is also the same, theoretically no problem.

I think it is still necessary to check the code and return to ensure that all devices have been obtained (please refer to my code example: https://github.com/coolkit-carl/ewelink-api-next/blob/main/src/web/apis/device/getAllThings.ts ). I am sure that under normal parameter transmission, this device information will definitely be returned

ghost commented 1 year ago

@coolkit-carl, I confirm the same behavior reported by @AndreFvdMerwe. I use two accounts, and only account 1 has the devices. Account 1 has shared all devices with account 2 via android app ewelink. On the android app, all devices are visibile when using account 2. Yet, the nodered node "devices" returns an empty array when using account 2. Using account 1, I get the full list of devices. device id: 1000a4f037

1000a4f037

1000a4f037 SONOFF UIID1 a socket, The same as my previous answer, we do not restrict the return of information on this device (its brand is licensed to you for free)

ghost commented 1 year ago

@coolkit-carl, I confirm the same behavior reported by @AndreFvdMerwe. I use two accounts, and only account 1 has the devices. Account 1 has shared all devices with account 2 via android app ewelink. On the android app, all devices are visibile when using account 2. Yet, the nodered node "devices" returns an empty array when using account 2. Using account 1, I get the full list of devices. device id: 1000a4f037

1000a4f037

1000a4f037 SONOFF UIID1 a socket, The same as my previous answer, we do not restrict the return of information on this device (its brand is licensed to you for free)

michelefa1988 commented 1 year ago

Good afternon, ive been following this chat and I am very curious if there is a way to toggle ewelink smart switches directly via internal network using curl. I do not see why a simple toggle needs to be done via third party apis

Also has anyone figured out a way to do all of the above via curl since so that switch can be attached to node red since after to going over the thread, I still don't have a clear idea on how to do this with node red.

Thanks

soki2001 commented 1 year ago

I was using ewelink node red module for a couple of years to control my solar system. 3 weeks ago fails and I followed the instructions to change api stuff on constants file.

Now get devices node is working but SET state or GET state nodes are not working and show: error: 401 msg: "Wrong account or password"

There are any "how to" to solve it because I'm not a developer and I don't understand very well what is the issue

Thanks in advance

apadilla83 commented 1 year ago

Ok I have this working for my hallway 2 channel light switch. I can turn them on and off right now.

in plain English:

  1. Learn what OAuth is... or follow the instructions at https://github.com/coolkit-carl/eWeLinkOAuthLoginDemo to run a local web server and login - after that you will be redirected back to your redirectUrl and a token.json will be saved with your authentication tokens. Keep this safe!
  2. run controlDeviceDemo.js - this listed all my devices... that was good, but the code to toggle the first device as a demo did not work for me... but having the list of devices showed that I was authenticated correctly.
  3. By trial and error I worked out then that I could pass the following code
await client.device.setThingStatus({
          type: 1,
          id: '10007bc171', // not my real id, but I used my real id here
          params:
            {
              "switches": [
                {"switch": "on", "outlet": 0},
                {"switch": "on", "outlet": 1}
              ]
            }
        })

AND MY LIGHTS TURNED ON....

  1. with some playing I was able to dump the actual HTTP request that was being made, which simply looks like (This is not code that you can copy and paste from this comment to make it work, this is a dump of the request for you to look at, and to compile your own HTTP Request that looks like this - any decent developer should be able to make a HTTP request in their programming language of choice)
Send request:  {
  url: '/v2/device/thing/status',
  method: 'post',
  baseURL: 'https://eu-apia.coolkit.cc',
  headers: AxiosHeaders {
    Accept: 'application/json, text/plain, */*',
    'Content-Type': 'application/json',
    Authorization: 'Bearer aa0dbbf06cd1NOTMYREALKEY8e84f9a09ffe536d62',
    'X-CK-Nonce': '4s3p08wn',
    Date: '1692398015055'
  },
  params: undefined,
  data: '{"type":1,"id":"10007bc171","params":{"switches":[{"switch":"off","outlet":0},{"switch":"off","outlet":1}]}}'
}

So now I have a proof of concept working in Javascript, I can switch back to PHP and write real HTTP requests, that consume the OAuth Endpoint, which gives me a token to store, and then I can then just use any HTTP client (mine will continue to be PHP) to make http requests

Once you have an access token from OAuth you can call any of the APIs - here is a scaled down request, made by standard curl command

curl --location 'https://eu-apia.coolkit.cc/v2/device/thing/status' \
--header 'X-CK-Nonce: 9e3NOTREALwR7' \
--header 'Authorization: Bearer 90e4e9c7de5NOTMYREALTOKENd36154e3bbc2' \
--header 'Content-Type: application/json' \
--data '{
    "type": 1,
    "id": "10007bc171",
    "params": {
        "switches": [
                {"switch": "on", "outlet": 1}
              ]
    }
}'

The above all works in real life in my house today. Im not @coolkit-carl, Im a PHP dev with API experience :)

If you are looking for a non-technical project where you can just input your username and password to a config file, and magically control your devices, then you can no longer do that. But if you are willing to learn basic development (like OAuth which is pretty much industry standard for authenticating and authorising external services nowadays) then that can be "easily" done.

The old ewelink-api project should be considered deprecated and no longer used. This work for me , but in short time I have this error; {"status":200,"responseTime":257,"error":401,"msg":"cannot found access token info","data":{}}

There are a procces to renew token and I used it, but only work for me in a short time after get token, then when I try to refesh token I get this: { status: 200, responseTime: 300, error: 405, msg: "can't find the account with this rt!", data: {} } any ideas?

ghost commented 1 year ago

Explanation on rt invalidation: If you use the same APPID, account, request login, refresh token, reset password, or other interfaces or behaviors, it will return a new at, rt, and cause the previous login credentials to become invalid.

apadilla83 commented 1 year ago

Explanation on rt invalidation: If you use the same APPID, account, request login, refresh token, reset password, or other interfaces or behaviors, it will return a new at, rt, and cause the previous login credentials to become invalid.

Then , what can I do to refresh token when the token are expired or before expired? Because in short time i received this: {"status":200,"responseTime":257,"error":401,"msg":"cannot found access token info","data":{}} Thanks

ghost commented 1 year ago

Explanation on rt invalidation: If you use the same APPID, account, request login, refresh token, reset password, or other interfaces or behaviors, it will return a new at, rt, and cause the previous login credentials to become invalid.

Then , what can I do to refresh token when the token are expired or before expired? Because in short time i received this: {"status":200,"responseTime":257,"error":401,"msg":"cannot found access token info","data":{}} Thanks

  1. You can tell me your account and I will check your login records for you. 2. When you receive this message, you can request to refresh the token interface and use rt to obtain new at and rt. If rt also fails, it proves that you have indeed reset it elsewhere.
apadilla83 commented 1 year ago

Explanation on rt invalidation: If you use the same APPID, account, request login, refresh token, reset password, or other interfaces or behaviors, it will return a new at, rt, and cause the previous login credentials to become invalid.

Then , what can I do to refresh token when the token are expired or before expired? Because in short time i received this: {"status":200,"responseTime":257,"error":401,"msg":"cannot found access token info","data":{}} Thanks

Then , what can I do to refresh token when the token are expired or before expired? Because in short time i received this: {"status":200,"responseTime":257,"error":401,"msg":"cannot found access token info","data":{}} Thanks

  1. You can tell me your account and I will check your login records for you. 2. When you receive this message, you can request to refresh the token interface and use rt to obtain new at and rt. If rt also fails, it proves that you have indeed reset it elsewhere. < Ok this is the case, Mi application login with oauth demo, I login manually and obtain the token. then all work correcty on mi application, after some time I received this mensage when the application try to control some device: :

{"status":200,"responseTime":257,"error":401,"msg":"cannot found access token info","data":{}}

I call the function refreshToken like that: console.log('Token expired, refreshing token') const refreshStatus = await client.user.refreshToken({ rt: LoggedInfo.data?.refreshToken, })

And I get always the same error

{ status: 200, responseTime: 380, error: 405, msg: "can't find the account with this rt!", data: {} }

then when you say that I have to reset it , is that I have to login again? Because this happend after short time..

Thanks!

apadilla83 commented 1 year ago

Ok this is the case, Mi application login with oauth demo, I login manually and obtain the token. then all work correcty on mi application, after some time I received this mensage when the application try to control some device: :

{"status":200,"responseTime":257,"error":401,"msg":"cannot found access token info","data":{}}

I call the function refreshToken like that: console.log('Token expired, refreshing token') const refreshStatus = await client.user.refreshToken({ rt: LoggedInfo.data?.refreshToken, })

And I get always the same error

{ status: 200, responseTime: 380, error: 405, msg: "can't find the account with this rt!", data: {} }

then when you say that I have to reset it , is that I have to login again? Because this happend after short time..

Thanks!

ghost commented 1 year ago

It looks like it has been reset. You need to log in again. It is recommended to check the code to see if there are any other places that will refresh this token, as each refresh will reset at and rt.

apadilla83 commented 1 year ago

Hi this is the code...

import { client } from '../../config.js' import {refreshToken} from './refresh.token.js';

import * as fs from 'fs'

export async function SonoffChangeState (ctx) { if (!fs.existsSync('./token.json')) { throw new Error('token.json not found, please run login.js first') }

  // get token
  let LoggedInfo = JSON.parse(fs.readFileSync('./token.json', 'utf-8'))
  // console.info(LoggedInfo)
  client.at = LoggedInfo.data?.accessToken
  client.region = LoggedInfo?.region || 'eu'
  client.setUrl(LoggedInfo?.region || 'eu')
  // Check if the token has expired, and refresh the token if it has expired
  if (
    LoggedInfo.data?.atExpiredTime < Date.now() &&
    LoggedInfo.data?.rtExpiredTime > Date.now()
  ) {
    console.log('Token expired, refreshing token')
    const refreshStatus = await client.user.refreshToken({
      rt: LoggedInfo.data?.refreshToken,
    })
    console.log(refreshStatus)
    if (refreshStatus.error === 0) {
      // You can also use built-in storage
      // client.storage.set('token', {...})
      fs.writeFileSync(
        './token.json',
        JSON.stringify({
          status: 200,
          responseTime: 0,
          error: 0,
          msg: '',
          data: {
            accessToken: refreshStatus?.data?.at,
            atExpiredTime: Date.now() + 2592000000,
            refreshToken: refreshStatus?.data?.rt,
            rtExpiredTime: Date.now() + 5184000000,
          },
          region: client.region,
        })
      )
      LoggedInfo = JSON.parse(fs.readFileSync('./token.json', 'utf-8'))
    }
  }

  if (LoggedInfo.data?.rtExpiredTime < Date.now()) {
    console.log('Failed to refresh token, need to log in again to obtain token')
    return
  }

const body = ctx.request.body
const deviceId = body.deviceId;
const channel = body.channel;
const channels= body.channels;
const state = body.state;
if(deviceId !=undefined && state !=undefined  && channel!=undefined && channels==undefined ){
let nchannels=parseFloat(channel)
let nchannel=--nchannels
console.log(`se va a cambiar el estado del dispositivo ${deviceId}  a ${state} canal ${nchannel} `)

try {
    let status = await client.device.setThingStatus({
      type: 1,
      id: deviceId,
      params: {
        switches: [
           { switch: state, outlet: nchannel },

        ],
      },
      //params: {
      //  switch: state, // Specific control instructions: https://coolkit-technologies.github.io/eWeLink-API/#/en/UIIDProtocol

      //},

    })
    console.log(status)
    if(status.error==401 || status.error==4002){
      refreshToken();
    }
    //res.send({DeviceStateChangueTo: status});
    ctx.body =status;

}catch(error){
    console.log(error)
   // res.send({DeviceStateChangueError: error});
   //ctx.body({status: error});
   ctx.body =error;
   //ctx.body(error);

  }     
}else{
  console.log(`se va a cambiar el estado del dispositivo de doble canal ${deviceId}  a ${state} canal ${channel} `)
  let nchannel=parseFloat(channel)
  try {
      let status = await client.device.setThingStatus({
        type: 1,
        id: deviceId,
        params: {
          switches: [
             { switch: state, outlet: nchannel },

          ],
        },
      })
      console.log(status)
      //res.send({DeviceStateChangueTo: status});
      ctx.body =status;
  }catch(error){
      console.log(error)
     // res.send({DeviceStateChangueError: error});
     //ctx.body({status: error});
     ctx.body =error;
     //ctx.body(error);

    }      
}

}

apadilla83 commented 1 year ago

HI, I think that is not error on my application, I have another application that connect to websocket with the same APP_ID AND APP_SECRET with the old api ewelink-api. ¿may be? I need to created another app en https://dev.ewelink.cc/ , but there is not possible..