-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsetup_withings.py
More file actions
67 lines (54 loc) · 1.87 KB
/
Copy pathsetup_withings.py
File metadata and controls
67 lines (54 loc) · 1.87 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
#!/usr/bin/env python3
"""
One-time setup: Authorize with Withings and store OAuth tokens.
1. Run this script
2. Open the printed URL in your browser
3. Authorize the app
4. Copy the 'code' parameter from the redirect URL
5. Paste it when prompted
"""
import json
from pathlib import Path
import requests
import yaml
CONFIG_PATH = Path(__file__).parent / "config.yaml"
TOKENS_PATH = Path(__file__).parent / "withings_tokens.json"
REDIRECT_URI = "http://localhost:8585/callback"
def main():
cfg = yaml.safe_load(open(CONFIG_PATH))["withings"]
client_id = cfg["client_id"]
client_secret = cfg["client_secret"]
auth_url = (
f"https://account.withings.com/oauth2_user/authorize2"
f"?response_type=code"
f"&client_id={client_id}"
f"&redirect_uri={REDIRECT_URI}"
f"&scope=user.metrics"
f"&state=weight-sync"
)
print(f"\nOpen this URL in your browser:\n\n{auth_url}\n")
print("After authorizing, you'll be redirected to a URL like:")
print(" http://localhost:8585/callback?code=SOME_CODE&state=weight-sync")
print("(The page won't load — that's fine.)\n")
code = input("Paste the 'code' value here: ").strip()
resp = requests.post("https://wbsapi.withings.net/v2/oauth2", data={
"action": "requesttoken",
"grant_type": "authorization_code",
"client_id": client_id,
"client_secret": client_secret,
"code": code,
"redirect_uri": REDIRECT_URI,
})
body = resp.json().get("body", {})
if not body.get("access_token"):
print(f"Error: {resp.json()}")
return
tokens = {
"access_token": body["access_token"],
"refresh_token": body["refresh_token"],
"userid": body["userid"],
}
TOKENS_PATH.write_text(json.dumps(tokens, indent=2))
print(f"\nTokens saved to {TOKENS_PATH}")
if __name__ == "__main__":
main()