@@ -202,6 +202,7 @@ async def fetch_token(
202
202
f"Missing access_token in Instagram OAuth response, app={ self .app_name } "
203
203
)
204
204
raise OAuth2Error ("Missing access_token in Instagram OAuth response" )
205
+
205
206
# return the token response with long-lived access token
206
207
return token
207
208
except Exception as e :
@@ -210,15 +211,28 @@ async def fetch_token(
210
211
211
212
async def refresh_token (
212
213
self ,
214
+ access_token : str ,
213
215
refresh_token : str ,
214
216
) -> dict [str , Any ]:
215
217
try :
216
- token = cast (
217
- dict [str , Any ],
218
- await self .oauth2_client .refresh_token (
219
- self .refresh_token_url , refresh_token = refresh_token
220
- ),
221
- )
218
+ if self .app_name == "INSTAGRAM" :
219
+ response = await self .oauth2_client .get (
220
+ self .refresh_token_url ,
221
+ params = {
222
+ "grant_type" : "ig_refresh_token" ,
223
+ "access_token" : access_token ,
224
+ },
225
+ timeout = 30.0 ,
226
+ )
227
+ response .raise_for_status ()
228
+ token = cast (dict [str , Any ], response .json ())
229
+ else :
230
+ token = cast (
231
+ dict [str , Any ],
232
+ await self .oauth2_client .refresh_token (
233
+ self .refresh_token_url , refresh_token = refresh_token
234
+ ),
235
+ )
222
236
return token
223
237
except Exception as e :
224
238
logger .error (f"Failed to refresh access token, app_name={ self .app_name } , error={ e } " )
@@ -253,7 +267,11 @@ async def parse_fetch_token_response(self, token: dict) -> OAuth2SchemeCredentia
253
267
if "expires_at" in data :
254
268
expires_at = int (data ["expires_at" ])
255
269
elif "expires_in" in data :
256
- expires_at = int (time .time ()) + int (data ["expires_in" ])
270
+ if self .app_name == "INSTAGRAM" :
271
+ # Reduce expiration time by 1 day (86400 seconds) for safety margin
272
+ expires_at = int (time .time ()) + max (0 , int (data ["expires_in" ]) - 86400 )
273
+ else :
274
+ expires_at = int (time .time ()) + int (data ["expires_in" ])
257
275
258
276
# TODO: if scope is present, check if it matches the scope in the App Configuration
259
277
0 commit comments