如何用PHP/JS调用Google API将CRM手机号同步至Google联系人?
解决方案:使用Google People API批量导入联系人
推荐使用Google People API完成需求——这是官方主推的REST风格接口,相比CardDAV更直观、功能更全面,适合批量操作联系人。以下是PHP和JavaScript的分步实现指南:
PHP 实现步骤
1. 前期配置
- 登录Google Cloud控制台,创建新项目并启用「People API」
- 创建OAuth 2.0客户端ID(选择「Web应用」类型),设置授权回调地址(本地测试可填
http://localhost/callback.php) - 下载客户端配置文件
credentials.json,放入项目根目录
2. 安装依赖
通过Composer安装Google官方客户端库:
composer require google/apiclient:^2.0
3. 获取授权令牌
创建auth.php文件处理授权流程:
<?php require __DIR__ . '/vendor/autoload.php'; $client = new Google\Client(); $client->setAuthConfig('credentials.json'); $client->addScope(Google\Service\PeopleService::CONTACTS); $client->setRedirectUri('http://localhost/callback.php'); $client->setAccessType('offline'); // 持久化令牌,支持后续无交互批量操作 if (!isset($_GET['code'])) { $authUrl = $client->createAuthUrl(); header('Location: ' . filter_var($authUrl, FILTER_SANITIZE_URL)); } else { $token = $client->fetchAccessTokenWithAuthCode($_GET['code']); file_put_contents('token.json', json_encode($token)); echo '授权完成,可执行联系人导入'; }
访问该文件完成授权,生成的令牌会保存到token.json。
4. 批量导入CRM手机号
创建import_contacts.php,替换示例中的CRM数据为实际业务数据:
<?php require __DIR__ . '/vendor/autoload.php'; // 初始化客户端 $client = new Google\Client(); $client->setAuthConfig('credentials.json'); $client->addScope(Google\Service\PeopleService::CONTACTS); $token = json_decode(file_get_contents('token.json'), true); $client->setAccessToken($token); // 自动刷新过期令牌 if ($client->isAccessTokenExpired()) { $client->fetchAccessTokenWithRefreshToken($client->getRefreshToken()); file_put_contents('token.json', json_encode($client->getAccessToken())); } $peopleService = new Google\Service\PeopleService($client); // 从CRM获取的联系人数据(示例格式) $crmContacts = [ ['name' => '客户A', 'phone' => '+8613800138000'], ['name' => '客户B', 'phone' => '+8613900139000'], // 更多联系人... ]; foreach ($crmContacts as $contact) { $person = new Google\Service\PeopleService\Person(); // 设置联系人姓名 $name = new Google\Service\PeopleService\Name(); $name->setGivenName($contact['name']); $person->setNames([$name]); // 设置手机号 $phone = new Google\Service\PeopleService\PhoneNumber(); $phone->setValue($contact['phone']); $phone->setType('mobile'); $person->setPhoneNumbers([$phone]); // 创建联系人 try { $peopleService->people->createContact($person); echo "已导入:{$contact['name']} - {$contact['phone']}<br>"; } catch (Exception $e) { echo "导入失败 {$contact['name']}:{$e->getMessage()}<br>"; } }
JavaScript(浏览器端)实现步骤
1. 前期配置
- 同PHP步骤,在Google Cloud控制台创建项目、启用People API
- 创建OAuth 2.0客户端ID(Web应用类型),添加允许的JavaScript来源(如
http://localhost:8080)
2. 编写页面代码
<!DOCTYPE html> <html> <head> <script src="https://apis.google.com/js/api.js"></script> </head> <body> <button onclick="initClient()">开始导入</button> <script> // 替换为你的API密钥和客户端ID const API_KEY = '你的API_KEY'; const CLIENT_ID = '你的CLIENT_ID'; function initClient() { gapi.client.init({ apiKey: API_KEY, clientId: CLIENT_ID, scope: 'https://www.googleapis.com/auth/contacts', discoveryDocs: ['https://people.googleapis.com/$discovery/rest?version=v1'], }).then(() => { const authInstance = gapi.auth2.getAuthInstance(); if (authInstance.isSignedIn.get()) { startImport(); } else { authInstance.signIn(); } }); } function startImport() { // 从CRM接口获取的联系人数据(示例格式) const crmContacts = [ { name: '客户A', phone: '+8613800138000' }, { name: '客户B', phone: '+8613900139000' } ]; crmContacts.forEach(contact => { const requestBody = { names: [{ givenName: contact.name }], phoneNumbers: [{ value: contact.phone, type: 'mobile' }] }; gapi.client.people.people.createContact({ resource: requestBody }).then(res => { console.log('导入成功:', contact.name); }).catch(err => { console.error('导入失败:', contact.name, err); }); }); } gapi.load('client:auth2'); </script> </body> </html>
关键提示
- 优先选择People API:CardDAV是基于WebDAV的旧协议,配置和调试复杂度更高,People API更贴合现代开发流程
- 注意API配额:批量操作时控制请求频率,避免触发Google的API调用限制
- 手机号格式:建议携带国家码(如+86),确保Google能正确识别号码类型
内容的提问来源于stack exchange,提问作者Storm
相关产品推荐
相关产品推荐

