Skip to main content

APEX を使用してコールを実行する

学習の目的

この単元を完了すると、次のことができるようになります。

  • Pardot API にアクセスするためのさまざまな方法を説明する。
  • 開発者コンソールと APEX を使用して、Pardot API に対するコールを実行する。

Pardot API コールのしくみを学習できたところで、実際に試してみましょう。この単元では、APEX を使用して Pardot API コールを実行し、カスタムリダイレクトオブジェクトをクエリして、カスタムリダイレクトとその項目のリストを取得します。 

すでに説明したように、Pardot API にアクセスする方法は多数あります。APEX コードを使用する方法はその 1 つに過ぎません。また、独自のアプリケーションを作成することも、Postman のような外部アプリケーションを使用することもできます。この単元で紹介する方法は、システムレベルのインテグレーションには使用できませんが、API のテストには最適です。 

始める前に、Pardot 管理者としてログインし、Pardot ビジネスユニット ID を取得します (その権限がある場合)。

認証を設定する

Salesforce で作業しているため、このアクティビティには認証のショートカットを使用できます。Visualforce ページを作成してセッションを作成し、そのセッション ID を使用して Pardot API を認証します。

  1. 開発者コンソールを開きます。
  2. SessionPage という名前の Visualforce ページを作成します。
  3. 次のコードをコピーして貼り付けます。
    <apex:page contentType="application/json">
    {"sessionId":"{!$Api.Session_ID}"}
    </apex:page>
  4. ファイルを保存します。

このページでは、APEX クラスで認証を管理するためにコールする sessionID が JSON で返されます。

API の結果を保存するクラスを作成する

次に、カスタムリダイレクトクエリの結果を保存するクラスを作成します。このクラスでは、JSON 応答文字列をオブジェクト項目に変換する処理も実行されます。

  1. 開発者コンソールを開きます。
  2. SamplePardotRequest_SessionID という APEX クラスを作成します。
  3. このコードをコピーして貼り付け、作業を保存します。
public class CustomRedirects {
   public List<Values> values;
   public class Values {
       public Integer id;
       public String salesforceId;
       public Integer folderId;
       public String name;
       public String destinationUrl;
       public Integer campaignId;
       public Integer trackerDomainId;
       public String vanityUrlPath;
       public String vanityUrl;
       public String trackedUrl;
       public String gaSource;
       public String gaMedium;
       public String gaTerm;
       public String gaContent;
       public String gaCampaign;
       public Boolean bitlyIsPersonalized;
       public String bitlyShortUrl;
       public String createdAt;
       public String updatedAt;
       public Integer createdById;
       public Boolean isDeleted;
    }
     public CustomRedirects jsonToObject(String json) {
        System.debug('Parsing String:' + json);
        return (CustomRedirects) System.JSON.deserialize(json, CustomRedirects.class);
     }
}

APEX コードには、次の 3 つの主要なコンポーネントが含まれています。

  1. すべての応答項目を含む値クラス。
  2. 各クエリレコードを含む値のリスト。
  3. JSON を解析してカスタムリダイレクト値を設定する jsonToObject というメソッドコール。

カスタムリダイレクトをクエリするクラスを作成する

次のクラスでは、クエリが実行され、CustomRedirects オブジェクトが返されます。 

  1. 開発者コンソールを開きます。
  2. CustomRedirectsQuery という APEX クラスを作成します。
  3. このコードをコピーして貼り付け、<BUID を挿入する> をビジネスユニット ID に置き換えて、作業を保存します。
public class CustomRedirectsQuery {
   /*End point Url to web service callout*/
   private final static String PARDOT_URL = 'https://pi.demo.pardot.com/api/v5/objects/custom-redirects';
   //Note: If you’re using a Pardot production account, use the domain "pi.pardot.com" instead of "pi.demo.pardot.com"
   private final static String BUID = '<insert your BUID>';
   public CustomRedirects customRedirects;
  //Create a class to parse the sessionID from the APEX page.
  public class SessionId {
    public string sessionId;
  }
   //Get the session ID from the APEX Page
   @AuraEnabled
   public static string getUserSessionId() {
      SessionId sessionJson = new SessionId();
      if(!Test.isRunningTest()){
         sessionJson = (SessionId)JSON.deserialize(Page.SessionPage.getContent().toString(), SessionId.class);
      }
      return sessionJson.sessionId;
   }
   public CustomRedirects customRedirectsQuery(){
      //Set up the authorization header for the API request
      String sessionId = getUserSessionId();
      String authorizationHeader = 'Bearer '+ sessionId;
      //Set up the fields to request
      String reqFields = '?fields=id,name,campaignId,destinationUrl,folderId,trackerDomainId,vanityUrlPath,gaSource,gaMedium,gaTerm,gaContent,gaCampaign,salesforceId,vanityUrl,trackedUrl,bitlyIsPersonalized,bitlyShortUrl,isDeleted,createdAt,updatedAt,createdById,createdById';
      String response = null;
      //Set up the HTTP Classes
      Http http = new Http();
      HttpRequest req = new HttpRequest();
      HttpResponse res = new HttpResponse();
      //Create the HTTPS Request Parameters
      req.setEndpoint(PARDOT_URL + reqFields);
      req.setMethod('GET');
      req.setHeader('Pardot-Business-Unit-Id', BUID);
      req.setHeader('Authorization', authorizationHeader);
      //Print out the request to logs
      System.debug('Request:' + req);
      //Submit the request
      try {
         res = http.send(req);
         response = res.getBody();
         System.debug('Response: ' + response);
         this.customRedirects = new CustomRedirects();
         this.customRedirects = this.customRedirects.jsonToObject(response);
         System.debug('CustomRedirectArray: ' + this.customRedirects.values);
         return this.customRedirects;
      }catch(System.CalloutException e){
         System.debug('Callout Error' + e);
         System.debug(res.getBody());
         return null;
      }
   }
}

コードでは、次の操作が行われます。

  • カスタムリダイレクトエンドポイント URL が定義されます。
  • 先ほど作成した Visualforce ページから、セッション ID を保持するクラスとセッション ID を取得するメソッドが作成されます。
  • 次のクエリが実行されます。
    • 認証ヘッダーを作成する。
    • 要求された項目を追加する。別の項目が返されるようにする場合は、この部分を編集してください。
    • HTTP クラスを初期化する。
    • HTTPS 要求を作成する。
    • 要求を送信する。
    • 結果を解析して、customRedirects オブジェクトを作成する。

コードを実行する

  1. [Debug (デバッグ)] > [Open Execute Anonymous Window (匿名実行ウィンドウを開く)] の順に開きます。
  2. 次のコードをコピーして貼り付けます。
    CustomRedirectsQuery test = new CustomRedirectsQuery();
    test.customRedirects = test.customRedirectsQuery();
    System.debug('Final Object Output:' + test.customRedirects);
  3. [Open Log (ログを開く)] をオンにします。
  4. [実行] をクリックします。

数秒後にログが開き、Salesforce 内で Pardot API コールの応答を確認できます。

これで、APEX を使用したコールを試したので、次はコードを使用して独自の要求を設計してみましょう。 

リソース

無料で学習を続けましょう!
続けるにはアカウントにサインアップしてください。
サインアップすると次のような機能が利用できるようになります。
  • 各自のキャリア目標に合わせてパーソナライズされたおすすめが表示される
  • ハンズオン Challenge やテストでスキルを練習できる
  • 進捗状況を追跡して上司と共有できる
  • メンターやキャリアチャンスと繋がることができる