微信公众平台——获取access_token、expires_in

微信公众平台——获取access_token、expires_in

在微信公众平台接口开发中,Access Token占据着重要地位,它相当于进入各种接口的邀请,拿到这个钥匙才拥有调用其他各种特殊接口的权限。

function GetMethod(HTTP: TIdHTTP; Url: String; Max: Integer): String;
var
RespData: TStringStream;
begin
RespData := TStringStream.Create('', TEncoding.UTF8);
try
try
HTTP.Get(Url, RespData);
HTTP.Request.Referer := Url;
Result := RespData.DataString;
except
Dec(Max);
if Max = 0 then
begin
Result := '';
Exit;
end;
Result := GetMethod(Url, Max);
end;
finally
FreeAndNil(RespData);
end;
end;

uses System.JSON;const
TokenUrl = 'https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=%s&secret=%s';procedure GetToken(AppID, AppSecret: String);

var
Url: string;
J: TJSONObject;
begin
Url := Format(TokenUrl, [AppID, AppSecret]);//AppID,AppSecret在你的公众平台上可以查到
J := TJSONObject.ParseJSONValue(GetMethod(Url, 1)) as TJSONObject;
try
if J.Count > 0 then
begin
Access_Token := J.GetValue('access_token').Value;//这就是后面做什么都要用到的access_token,每天获取的次数是每天2000次,所以不能每次用都重新获取
Expires_IN := J.GetValue('expires_in').Value.ToInteger;//access_token的过期时间,7200秒,所以要在过期前重新获取
end;
finally
J.Free;
end;
end;

猜你喜欢

转载自www.cnblogs.com/hnxxcxg/p/8987567.html