💥

【Salesforce】API経由でLeadをコンバートさせたい

2022/09/08に公開

SalesforceのリードをAPI経由でコンバートする際に少し手間だったので、
備忘録的に実装手順を残しておきます。

コード(結論)

「設定」 > 「カスタムコード」 > 「Apexクラス」からApexクラスの実装を行い、このApexクラスをAPIから呼ぶことで、コンバートの処理を実装できました。
参照: LeadConvertクラス

// リードの検索
Lead ToBeConvertedLead = [select Id from Lead where Id = :leadId];

// LeadConvertオブジェクトを作成
Database.LeadConvert lc = new Database.LeadConvert();
lc.setLeadId(ToBeConvertedLead.id);

// コンバート処理
LeadStatus convertStatus = [SELECT Id, MasterLabel FROM LeadStatus WHERE IsConverted=true LIMIT 1];
lc.setConvertedStatus(convertStatus.MasterLabel);

コードの解説

  1. リードの検索
// リードの検索
Lead ToBeConvertedLead = [select Id from Lead where Id = :leadId];

[ ... ]の記法は、SOQLのステートメントに記載してあります。
Apexクラス内ではこの記法を使っておけば、SQL-likeな検索をかけられますね。


  1. LeadConvertオブジェクトを作成
// LeadConvertオブジェクトを作成
Database.LeadConvert lc = new Database.LeadConvert();
lc.setLeadId(ToBeConvertedLead.id);

LeadConvertオブジェクトを作成し、コンバート対象リードのIdをオブジェクトに渡しています。
この時点ではまだコンバート処理は行われていません。

ちなみに、setLeadIdは必須項目です。
参照: setLeadId


  1. コンバート処理
// コンバート処理
LeadStatus convertStatus = [SELECT Id, MasterLabel FROM LeadStatus WHERE IsConverted=true LIMIT 1];
lc.setConvertedStatus(convertStatus.MasterLabel);

ここでは、convertStatusIdMasterLabelを格納し、MasterLabelだけsetConvertedStatusに渡しています。

Idの用途は不明)

そして、setConvertedStatusした時点で、コンバート処理が走ります。

MasterLabelとApiNameについて

参照したApex 開発者ガイドの通りsetConvertedStatusのところでMasterLabelを使うと、私の場合はエラーが出てしまいました。

調べてみると、StackExchangeに同様の問題に対する質問が取り上げられていました。

投稿者: They are using MasterLabel for setting the status while conversion. In one of our customer org they had the api name different from the Masterlabel and while i was passing the MasterLabel it always threw a invalid status error. Once i had the api name and Master label as same the error disappeared. So is it best to use api name instead or MasterLabel?

和訳: 「公式ドキュメント通りMasterLabel使うとエラー出るが、ApiNameにすると動く。どうして?」

回答者: That's correct, you should use the API Name. Using the masterLabel will throw an exception at runtime. The only exception would be if the masterLabel and apiName are the same (typically when the status is a single word), but this isn't something you can rely on.

和訳: 「API Nameを使おう。」

 

これだけだと違いがよくわからなかったので、
API経由でLeadオブジェクトのMasterLabelApiNameを取得し、レスポンスを比較してみることにしました。すると、

// MasterLabel
client.query("SELECT Id, MasterLabel FROM LeadStatus WHERE IsConverted=true LIMIT 1").first
=> {... ,  "MasterLabel"=>"Hogehoge"} // 頭文字大文字

// LeadStatus
client.query("SELECT Id, ApiName FROM LeadStatus WHERE IsConverted=true LIMIT 1").first
=> {... , "ApiName"=>"hogehoge"} // 頭文字小文字

(レスポンスの値は仮のものです。)

  • MasterLabel→ リードのStatusの「値」を取得する
  • ApiName→ リードのStatusの「API参照名」を取得する

という点で異なることがわかりました。

 

また、LeadStatusのドキュメントにも、以下の通り書いてありました。

MasterLabel
説明
このリード状況値の表示ラベル。この表示値は、翻訳されない内部ラベルです。

ApiName
説明
選択リストの値を一意に識別します。これにより ID や主表示ラベルを使用せずに選択リストの値を取得できます。

おわりに

今回使用したLeadConvertのメソッドを見ると、色々なことができそうですね。

訂正箇所などございましたら、ご指摘いただけますと幸いです。

参考にしたもの

Discussion