sarmadmakhdoom/ringcentral-php

RingCentral 平台 PHP SDK

dev-master 2024-03-18 16:18 UTC

This package is auto-updated.

Last update: 2024-09-18 17:27:38 UTC


README

Build Status Coverage Status Chat Twitter

RingCentral 开发者 是一个可以通过超过 70 个 API 访问的云通信平台。平台的主要功能包括以下技术:语音短信/MMS传真Glip 团队消息数据和配置

API 参考文档API 探索器

需求

  • PHP 7.2+
  • CURL 扩展
  • MCrypt 扩展

安装

请选择以下安装选项之一

使用 Composer (推荐)

Composer 的默认安装位置是本地。我们建议您在应用程序目录结构的顶层安装它。

  1. 安装 Composer

    $ curl -sS https://getcomposer.org/installer | php

    关于在 Linux / Unix / OSXWindows 上安装的更多信息。

  2. 运行 Composer 命令以安装最新版本的 SDK

    $ php composer.phar require ringcentral/ringcentral-php
  3. 在您的 PHP 脚本中需要 Composer 的自动加载器(假设它位于安装 Composer 的同一目录中)

    require('vendor/autoload.php');

带有捆绑依赖项的 PHAR

不建议这样做!使用 Composer 作为与 PHP 包一起工作的现代方式。

  1. 下载 PHAR 文件

  2. 需要文件

    require('path-to-sdk/ringcentral.phar');

请注意,捆绑的依赖项可能会干扰您的其他依赖项。

基本用法

初始化

$rcsdk = new RingCentral\SDK\SDK('clientId', 'clientSecret', RingCentral\SDK\SDK::SERVER_SANDBOX);

您还可以使用应用程序的名称和版本提供自定义的 AppName 和 AppVersion 参数。这些参数是可选的,但它们将大大帮助您在 API 日志中识别应用程序并加快任何潜在的故障排除。允许用于 AppName 和 AppVersion 的字符包括:字母、数字、连字符、点和下划线。

$rcsdk = new RingCentral\SDK\SDK('clientId', 'clientSecret', RingCentral\SDK\SDK::SERVER_SANDBOX, 'MyApp', '1.0.0');

对于生产使用 RingCentral\SDK\SDK::SERVER_PRODUCTION 常量。或者手动输入服务器 URL。

身份验证

检查身份验证状态

$rcsdk->platform()->loggedIn();

使用 jwt 验证用户

$rcsdk->platform()->login([
    'jwt' => 'your_jwt_token'
]);

使用授权代码验证用户

$rcsdk->platform()->login([
    'code' => 'authorization code from RingCentral login redirect uri'
]);

身份验证生命周期

如果需要,平台类会执行令牌刷新程序。您可以在 CGI 模式下在请求之间保存身份验证。

// when application is going to be stopped
file_put_contents($file, json_encode($rcsdk->platform()->auth()->data(), JSON_PRETTY_PRINT));

// and then next time during application bootstrap before any authentication checks:
$rcsdk->platform()->auth()->setData(json_decode(file_get_contents($file), true));

重要!如果您共享身份验证,则必须手动维护 SDK 之间的同步。当两个并发请求执行刷新时,只有一个会成功。一个解决方案是使用信号量,在其中一个执行刷新时暂停其他挂起的请求。

执行 API 调用

$apiResponse = $rcsdk->platform()->get('/account/~/extension/~');
$apiResponse = $rcsdk->platform()->post('/account/~/extension/~', array(...));
$apiResponse = $rcsdk->platform()->put('/account/~/extension/~', array(...));
$apiResponse = $rcsdk->platform()->delete('/account/~/extension/~');

print_r($apiResponse->json()); // stdClass will be returned or exception if Content-Type is not JSON
print_r($apiResponse->request()); // PSR-7's RequestInterface compatible instance used to perform HTTP request
print_r($apiResponse->response()); // PSR-7's ResponseInterface compatible instance used as HTTP response

多部分响应

加载多个逗号分隔的 ID 将导致 HTTP 207 响应,内容类型为 Content-Type: multipart/mixed。此响应将被解析为多个子响应

$presences = $rcsdk->platform()
                 ->get('/account/~/extension/id1,id2/presence')
                 ->multipart();

print 'Presence loaded ' .
      $presences[0]->json()->presenceStatus . ', ' .
      $presences[1]->json()->presenceStatus . PHP_EOL;

发送短信 - 发起 POST 请求

$apiResponse = $rcsdk->platform()->post('/account/~/extension/~/sms', array(
    'from' => array('phoneNumber' => 'your-ringcentral-sms-number'),
    'to'   => array(
        array('phoneNumber' => 'mobile-number'),
    ),
    'text' => 'Test from PHP',
));

获取平台错误消息

try {

    $rcsdk->platform()->get('/account/~/whatever');

} catch (\RingCentral\SDK\Http\ApiException $e) {

    // Getting error messages using PHP native interface
    print 'Expected HTTP Error: ' . $e->getMessage() . PHP_EOL;

    // In order to get Request and Response used to perform transaction:
    $apiResponse = $e->apiResponse();
    print_r($apiResponse->request());
    print_r($apiResponse->response());

    // Another way to get message, but keep in mind, that there could be no response if request has failed completely
    print '  Message: ' . $e->apiResponse->response()->error() . PHP_EOL;

}

如何调试 HTTP

您可以设置任何 HTTPS 嗅探器(例如,代理服务器,如 Charles)并将 SDK 流量通过自定义 Guzzle 客户端实例路由到它。

use GuzzleHttp\Client as GuzzleClient;

$guzzle = new GuzzleClient([
    'proxy' => 'localhost:8888',
    'verify' => false
]);

$rcsdk = new SDK("clientId", "clientSecret", SDK::SERVER_PRODUCTION, 'Demo', '1.0.0', $guzzle);

订阅

Webhook 订阅

$apiResponse = $rcsdk->platform()->post('/subscription', array(
    'eventFilters' => array(
        '/restapi/v1.0/account/~/extension/~/message-store',
        '/restapi/v1.0/account/~/extension/~/presence'
    ),
    'deliveryMode' => array(
        'transportType' => 'WebHook',
        'address' => 'https://consumer-host.example.com/consumer/path'
    )
));

当创建webhook订阅时,它将通过headers中的validation-token向webhook地址发送请求。webhook地址应返回带有headers中的validation-token的成功请求来完成webhook注册。

WebSocket订阅

use RingCentral\SDK\WebSocket\WebSocket;
use RingCentral\SDK\WebSocket\Subscription;
use RingCentral\SDK\WebSocket\Events\NotificationEvent;

// connect websocket
$websocket = $rcsdk->initWebSocket();
$websocket->addListener(WebSocket::EVENT_READY, function (SuccessEvent $e) {
    print 'Websocket Ready' . PHP_EOL;
    print 'Connection Details' . print_r($e->apiResponse()->body(), true) . PHP_EOL;
});
$websocket->addListener(WebSocket::EVENT_ERROR, function (ErrorEvent $e) {
    print 'Websocket Error' . PHP_EOL;
});
$websocket->connect();

// create subscription
$subscription = $rcsdk->createSubscription();
$subscription->addEvents(array(
    '/restapi/v1.0/account/~/extension/~/presence',
    '/restapi/v1.0/account/~/extension/~/message-store/instant?type=SMS'
));
$subscription->addListener(Subscription::EVENT_NOTIFICATION, function (NotificationEvent $e) {
    print 'Notification ' . print_r($e->payload(), true) . PHP_EOL;
});
$subscription->register();

在创建订阅之前需要创建WebSocket连接。当WebSocket连接出错时,需要手动重新创建WebSocket和订阅。

PubNub订阅

这是已废弃的,请使用WebSocket订阅。

use RingCentral\SDK\Subscription\Events\NotificationEvent;
use RingCentral\SDK\Subscription\PubnubSubscription;

$subscription = $rcsdk->createSubscription('Pubnub);
$subscription->addEvents(array('/restapi/v1.0/account/~/extension/~/presence'))
$subscription->addListener(PubnubSubscription::EVENT_NOTIFICATION, function (NotificationEvent $e) {
    print_r($e->payload());
});
$subscription->setKeepPolling(true);
$apiResponse = $subscription->register();

请注意,由于PubNub库的限制,它是同步的,因此订阅可能会过期,必须手动重新创建。

多部分请求

SDK提供了一个助手来简化发送传真。

$request = $rcsdk->createMultipartBuilder()
                 ->setBody(array(
                     'to'         => array(
                         array('phoneNumber' => '16501112233'),
                     ),
                     'faxResolution' => 'High',
                 ))
                 ->add('Plain Text', 'file.txt')
                 ->add(fopen('path/to/file', 'r'))
                 ->request('/account/~/extension/~/fax'); // also has optional $method argument

$response = $rcsdk->platform()->sendRequest($request);

如何演示?

克隆仓库并创建一个文件demo/_credentials.php,将'demo/_credentialsSample.php'文件的内容复制如下

return array(
    'username'     => '18881112233', // your RingCentral account phone number
    'extension'    => null, // or number
    'password'     => 'yourPassword',
    'clientId'     => 'yourClientId',
    'clientSecret' => 'yourClientSecret',
    'server'       => 'https://platform.devtest.ringcentral.com', // for production - https://platform.ringcentral.com
    'smsNumber'    => '18882223344', // any of SMS-enabled numbers on your RingCentral account
    'mobileNumber' => '16501112233', // your own mobile number to which script will send sms
    'dateFrom'     => 'yyyy-mm-dd',
    'dateTo'       => 'yyyy-mm-dd'
);

然后执行

$ php index.php

应该输出

Auth exception: Refresh token has expired
Authorized
Refreshing
Refreshed
Users loaded 10
Presence loaded Something New - Available, Something New - Available
Expected HTTP Error: Not Found (from backend)
SMS Phone Number: 12223334455
Sent SMS https://platform.ringcentral.com/restapi/v1.0/account/111/extension/222/message-store/333
Subscribing

之后,该脚本将等待任何存在通知。从您的账户发起呼叫或从您的账户进行外呼。当您发起呼叫时,脚本将打印通知并退出。

请查看demo文件夹以查看所有演示。