0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Salesforce から LINE WORKS に通知を送る

Posted at

Salesforce と LINE WORKS を Apex で連携して通知を送る

概要

Salesforce 内で商談(Opportunity)のステータスが変更された際に、LINE WORKS の Bot を使って指定のユーザーにメッセージを送信する方法を紹介します。Apex を使って HTTP コールアウトを行い、LINE WORKS の Bot API を呼び出す構成です。

背景

Salesforce では標準の通知機能もありますが、他ツール(例:LINE WORKS)との連携にはカスタム開発が必要です。通知を LINE WORKS に送ることで、営業チームや関係者にリアルタイムで情報共有できます。

連携概要

  • トリガー: 商談(Opportunity)のステージが変更されたとき
  • 通知先: LINE WORKS のユーザー(ログイン ID 指定)
  • 使用技術: Apex クラス、HTTP コールアウト、LINE WORKS Bot API
  • 認証方式: Refresh Token によるアクセストークン取得(Authorization Code Flow)

実装ステップ

1. LINE WORKS Developer Console 側の準備

  • Bot を作成し、Bot ID を取得
  • ユーザーのメールアドレス(ログイン ID)を確認
  • OAuth 認証を設定し、Client ID・Client Secret・Refresh Token を取得

2. Apex 認証クラスを作成(アクセストークンを取得)

public class LineWorksAuthSimple {
    public static String refreshAccessToken() {
        final String tokenEndpoint = 'https://auth.worksmobile.com/oauth2/v2.0/token';
        final String clientId = 'あなたのCLIENT_ID';
        final String clientSecret = 'あなたのCLIENT_SECRET';
        final String refreshToken = '保存済みのREFRESH_TOKEN';

        HttpRequest req = new HttpRequest();
        req.setEndpoint(tokenEndpoint);
        req.setMethod('POST');
        req.setHeader('Content-Type', 'application/x-www-form-urlencoded');

        String body = 'grant_type=refresh_token'
                    + '&client_id=' + EncodingUtil.urlEncode(clientId, 'UTF-8')
                    + '&client_secret=' + EncodingUtil.urlEncode(clientSecret, 'UTF-8')
                    + '&refresh_token=' + EncodingUtil.urlEncode(refreshToken, 'UTF-8');
        req.setBody(body);

        Http http = new Http();
        HttpResponse res = http.send(req);

        if (res.getStatusCode() == 200) {
            Map<String, Object> resBody = (Map<String, Object>) JSON.deserializeUntyped(res.getBody());
            return (String) resBody.get('access_token');
        } else {
            System.debug('Token refresh failed: ' + res.getBody());
            throw new AuraHandledException('Access Token refresh failed');
        }
    }
}

3. Apex クラスで通知送信処理を作成

public class LineWorksNotifier {
    public static void sendOpportunityUpdateNotification(Opportunity opp, String oldStageName) {
        String accessToken = LineWorksAuthSimple.refreshAccessToken();

        String message = '[商談更新通知]\n'
                       + '商談名: ' + opp.Name + '\n'
                       + 'ステージ: ' + oldStageName + ' → ' + opp.StageName + '\n'
                       + '金額: ' + opp.Amount;

        HttpRequest req = new HttpRequest();
        req.setEndpoint('https://www.worksapis.com/v1.0/bots/あなたのBOT_ID/users/通知先ユーザーID/messages');
        req.setMethod('POST');
        req.setHeader('Authorization', 'Bearer ' + accessToken);
        req.setHeader('Content-Type', 'application/json');

        Map<String, Object> payload = new Map<String, Object>{
            'content' => new Map<String, Object>{
                'type' => 'text',
                'text' => message
            }
        };
        req.setBody(JSON.serialize(payload));

        Http http = new Http();
        HttpResponse res = http.send(req);

        System.debug('Status: ' + res.getStatusCode());
        System.debug('Body: ' + res.getBody());
    }
}

4. Apex Trigger を設定

trigger OpportunityTrigger on Opportunity (after update) {
    for (Opportunity opp : Trigger.new) {
        Opportunity oldOpp = Trigger.oldMap.get(opp.Id);
        if (opp.StageName != oldOpp.StageName) {
            LineWorksNotifier.sendOpportunityUpdateNotification(opp, oldOpp.StageName);
        }
    }
}

Apex とは?

Apex は Salesforce プラットフォームで使用される Java に似たオブジェクト指向のプログラミング言語です。主に以下の目的で使用されます:

  • レコード更新に伴う処理の自動化(トリガー)
  • バッチ処理や非同期処理(@future や Queueable)
  • 外部 API との連携(HttpRequest)

Salesforce では、開発者コンソールや「開発者設定」から GUI 上で Apex クラスを作成・編集できます。

注意点

  • HTTP Callout を行うクラスでは @future(callout=true)Queueable を使う必要があります。
  • 外部サイトにアクセスするには「リモートサイト設定」が必要です。
  • テストコード(カバレッジ)を別途用意しないと本番環境にデプロイできません。

まとめ

本記事では、Salesforce 内の商談ステータス更新をトリガーに、LINE WORKS Bot へ通知を送信する一連の流れを紹介しました。業務効率化や通知の即時性を向上させる活用例として参考になれば幸いです。

0
0
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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?