LoginSignup
13
7

More than 3 years have passed since last update.

フローでSalesforceのレコード情報をSlackに投稿する

Posted at

レコード詳細ページでボタンを押したら、レコード情報をSlackに投稿する機能を考えてみます。
Apexで作っちゃえば簡単なのですが、投稿内容を変更するのにいちいちApexを修正するとなると、お客様が修正するのは大変ですね。
フローを使えばノンコーディングで投稿内容を修正可能にできるなーと思ってやってみました。

作るもの

まとめると今回作ってみるのは以下のような機能です。

  • 商談レコードページにアクションを置く
  • アクションをクリックすると商談レコードをSlackに投稿する
  • Flow Builderで投稿内容を自由に編集できる

sendtoslack.gif

Slackに投稿するApexクラスを作る

最初にSlackに投稿するApexクラスを作ります。

SendToSlackAction.cls
public class SendToSlackAction {
    public class SlackException extends Exception {}

    public class SendMessageRequest {
        @InvocableVariable(required=true label='Webhook URL')
        public String webhookUrl;
        @InvocableVariable(required=true label='メッセージJSON')
        public String message;
    }
    public class SendMessageResponse {
        @InvocableVariable
        public Boolean success;
        @InvocableVariable
        public String message;
        @InvocableVariable
        public String detail;
    }

    @InvocableMethod(label='Slackに投稿')
    public static SendMessageResponse[] sendMessage(SendMessageRequest[] requests) {
        SendMessageResponse[] results = new List<SendMessageResponse>();
        for (SendMessageRequest request : requests) {
            try {
                sendMessage(request.webhookUrl, request.message);
                SendMessageResponse res = new SendMessageResponse();
                res.success = true;
                results.add(res);
            } catch (Exception e) {
                System.debug(e);
                SendMessageResponse res = new SendMessageResponse();
                res.success = false;
                res.message = e.getMessage();
                res.detail = e.getTypeName() + ': ' + e.getMessage() + '\n' + e.getStackTraceString();
                results.add(res);
            }
        }
        return results;
    }

    private static void sendMessage(String webhookUrl, String msg) {
        Http http = new Http();
        HttpRequest req = new HttpRequest();
        req.setEndpoint(webhookUrl);
        req.setMethod('POST');
        req.setHeader('Content-Type', 'application/json');
        req.setBody(msg);
        HttpResponse res = http.send(req);
        Integer statusCode = res.getStatusCode();
        if (statusCode != 200) {
            throw new SlackException(res.getBody());
        }
    }
}

Webhook URLをリモートサイトに追加はしておいてください。

image.png

Flowを作る

Flow Builderを開きます。

今回は商談レコードページにアクションとして配置するので、レコードIDを受けるために、 recordId という変数を追加します。マネージャ > 新規リソース から追加します。

image.png

要素 > レコードを取得をデザイナーにドロップし、以下のように設定します。
商談レコードを絞り込みで Id = {!recordId} にするのがポイントです。これで今見ている商談が取得できます。

image.png

同じダイアログの下の方に行って、 レコード変数新規リソース を選択します。

image.png

以下のように設定します。

image.png

変数に保存する商談項目を選択 に投稿したい項目を適当に選びます。

image.png

Apexアクション をドロップして、以下のように設定します。
SlackのWebhook URLは適当に取得してきてください。

image.png

入力値の MessageJson は新規数式リソースを以下のように作成します。

image.png

数式の中身はこんな感じです。テキストテンプレートリソースでもよかったんですが、数式のほうがJSENCODE関数が使えてよいかと思います。
SlackのメッセージフォーマットについてはAn overview of message composition | Slackを見てください。

'{' &
'  "icon_url": "https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/27267/1ccfdf75-9564-1469-55df-d8c0ba1a01b2.png",' &
'  "username": "Salesforce",' &
'  "text": "' & JSENCODE({!CurrentOpportunity.Name}) & 'を共有しました!!"' &
'}'

ここまでで一応動きますが、結果の画面表示用に出力値も変数に保存します。

image.png

決定 ブロックをドロップして、以下のように設定します。

image.png

成功画面を作ります。画面ブロックをドロップし、以下のように設定します。
細かいところは適当に設定してください。

image.png

失敗画面も同様に作ります。

image.png

以下のようにつなぎます。

image.png

フローを保存します。

image.png

アクションを作る

以下のようなアクションを作ります。

image.png

ページレイアウトに配置します。

image.png

完成です。

完成

ボタンを押すとSlackに投稿されます。

sendtoslack.gif

Slackにはこんな感じに投稿されています。

image.png

数式をがんばると

'{' &
'  "icon_url": "https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/27267/1ccfdf75-9564-1469-55df-d8c0ba1a01b2.png",' &
'  "username": "Salesforce",' &
'  "blocks": ['&
'    {' &
'      "type": "section",' &
'      "fields": [' &
'        {' &
'          "type": "mrkdwn",' &
'          "text": "<https://atskimura-dev-ed.lightning.force.com/' & {!CurrentOpportunity.Id} & '|' & JSENCODE({!CurrentOpportunity.Name}) & '>を共有しました!!"' &
'        }' &
'      ]' &
'    },' &
'    {' &
'      "type": "section",' &
'      "fields": [' &
'        {' &
'          "type": "mrkdwn",' &
'          "text": "*取引先名:*\n' & JSENCODE({!CurrentOpportunity.Account.Name}) & '"' &
'        },' &
'        {' &
'          "type": "mrkdwn",' &
'          "text": "*金額:*\n' & TEXT({!CurrentOpportunity.Amount}) & '"' &
'        },' &
'        {' &
'          "type": "mrkdwn",' &
'          "text": "*担当者:*\n' & JSENCODE({!CurrentOpportunity.Owner.LastName} & {!CurrentOpportunity.Owner.FirstName}) & '"' &
'        },' &
'        {' &
'          "type": "mrkdwn",' &
'          "text": "*フェーズ:*\n' & TEXT({!CurrentOpportunity.StageName}) & '"' &
'        }' &
'      ]' &
'    }' &
'  ]' &
'}'

もっとリッチにできます。

image.png

でも、JSONを数式で書くの辛いなあ。

13
7
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
13
7