本文将详细介绍如何通过 OAuth 2.0 授权对接 Salesforce,并获取 CRM 联系人信息。我们将从创建 Salesforce Connected App 开始,逐步讲解如何进行 OAuth 授权、获取 Access Token、调用 API 获取联系人数据,以及如何刷新 Token。让我们开始吧! 🚀
1. 在 Salesforce 创建 Connected App
1.1 登录 Salesforce 开发者账户
首先,访问 Salesforce Developer 并登录你的开发者账户。登录后,点击右上角的头像,选择 "Setup"(设置) 进入管理后台。
1.2 创建 Connected App
在 Setup 页面的搜索栏中输入 "App Manager"(应用程序管理器),然后点击进入应用管理页面。
点击 "New Connected App"(新建链接的应用程序),在弹出的窗口中选择 "创建链接的应用程序"。填写应用的基本信息,建议开启 "PKCE" 授权以增强安全性。
注意:创建完成后,务必保存好 Consumer Key 和 Consumer Secret,后续服务器调用接口时会用到。
2. 使用 OAuth 2.0 进行授权
2.1 OAuth 认证 URL
Salesforce 采用 OAuth 2.0 授权码模式。你的应用需要引导用户访问 Salesforce 的授权页面,URL 格式如下:
https://login.salesforce.com/services/oauth2/authorize?
response_type=code
&client_id=你的ConsumerKey
&redirect_uri=你的回调URL
&scope=api refresh_token
参数说明:
- response_type=code:请求授权码。
- client_id=你的 Consumer Key:应用的 Consumer Key。
- redirect_uri=你的回调 URL:必须与 Salesforce 配置的回调 URL 一致。
- scope=api refresh_token:获取 API 权限,并允许刷新令牌。
用户登录 Salesforce 并同意授权后,会跳转回你的 redirect_uri
,并带上 code。
2.2 交换授权码获取 Access Token
用户授权后,你的服务器需要发送 POST 请求以换取 Access Token:
POST https://login.salesforce.com/services/oauth2/token
Content-Type: application/x-www-form-urlencoded
grant_type=authorization_code
&client_id=你的ConsumerKey
&client_secret=你的ConsumerSecret
&redirect_uri=你的回调URL
&code=授权码
成功后,Salesforce 会返回以下 JSON 数据:
{
"access_token": "你的访问令牌",
"refresh_token": "你的刷新令牌",
"instance_url": "https://your-instance.salesforce.com",
"token_type": "Bearer"
}
3. 使用 API 获取 CRM 联系人
拿到 access_token
后,你可以调用 Salesforce API 获取联系人数据。以下是一个获取联系人列表的示例请求:
GET https://your-instance.salesforce.com/services/data/v59.0/query/?q=SELECT+Id,Name,Email+FROM+Contact
Authorization: Bearer 你的access_token
Salesforce 会返回如下 JSON 数据:
{
"totalSize": 2,
"done": true,
"records": [
{
"Id": "0031N00001xyz123",
"Name": "张三",
"Email": "zhangsan@example.com"
},
{
"Id": "0031N00001xyz456",
"Name": "李四",
"Email": "lisi@example.com"
}
]
}
4. 刷新 Access Token
Access Token 过期后,可以使用 refresh_token
刷新:
POST https://login.salesforce.com/services/oauth2/token
Content-Type: application/x-www-form-urlencoded
grant_type=refresh_token
&client_id=你的ConsumerKey
&client_secret=你的ConsumerSecret
&refresh_token=你的RefreshToken
成功后,Salesforce 会返回新的 access_token
,你可以继续调用 API。
5. 更新和新增联系人
新增联系人
url: /services/data/v58.0/composite/sobjects
method: POST
参数:
{
"records": [
{
"attributes": {
"type": "Contact"
},
"FirstName": "ben-jamin-toy",
"LastName": "-",
"Email": "",
"Phone": "",
"MobilePhone": "",
"Description": "",
"Fax": ""
}
]
}
更新联系人
url: /services/data/v58.0/composite/sobjects
method: PATCH
参数:
{
"records": [
{
"attributes": {
"type": "Contact"
},
"Id": "003xxxxx",
"FirstName": "ben-jamin-toy",
"LastName": "-",
"Email": "",
"Phone": "",
"MobilePhone": "",
"Description": "",
"Fax": ""
}
]
}
总结 🎉
通过本文,你已经学会了如何创建 Salesforce Connected App、使用 OAuth 2.0 进行授权、获取 Access Token、调用 API 获取联系人数据,以及如何刷新 Token 和更新联系人信息。希望这篇指南能帮助你顺利对接 Salesforce!如果有任何问题,欢迎在评论区留言讨论。😊
Happy Coding! 🚀