Delphi XE7 用indy开发微信公众平台(1) 获取access_token、expires_in

原文链接:http://www.cnblogs.com/devinlee/p/4282498.html

微信公众平台官方的资料都是PHP的,这几天闲来无事,用Delphi实现了部分功能,希望能抛砖引玉,大家共同完善

开发平台:Delphi XE7

主要涉及JSON、XML的解析,SHA1加密,indy的IdHTTP、IdSSLIOHandlerSocketOpenSSL、IdHTTPServer控件

完全使用Delphi自带控件

获取access_token、expires_in

扫下方二维码关注,测试效果

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;
原文地址:https://www.cnblogs.com/devinlee/p/4282498.html