Skip to main content
 首页 » 编程设计

php之我可以设置 PHP Twilio 应用程序服务器并授予推送功能吗

2025年04月02日27duanxz

我目前使用 Python Twilio 应用程序服务器并使用以下代码行向我的 token 授予推送功能:

@app.route('/accessToken') 
def token(): 
  account_sid = os.environ.get("ACCOUNT_SID", ACCOUNT_SID) 
  api_key = os.environ.get("API_KEY", API_KEY) 
  api_key_secret = os.environ.get("API_KEY_SECRET", API_KEY_SECRET) 
  push_credential_sid = os.environ.get("PUSH_CREDENTIAL_SID", PUSH_CREDENTIAL_SID) 
  app_sid = os.environ.get("APP_SID", APP_SID) 
 
  grant = VoiceGrant( 
    push_credential_sid=push_credential_sid, 
    outgoing_application_sid=app_sid 
  ) 
 
  token = AccessToken(account_sid, api_key, api_key_secret, IDENTITY) 
  token.add_grant(grant) 
 
  return str(token) 

我有办法用 PHP 做到这一点吗?我已经使用 composer 加载了 Twilio 依赖项,并且可以很好地获得 token 。我只是不知道如何向 token 添加推送功能。这些行当前生成 token (但不具有推送功能):

<?php 
include('./vendor/autoload.php'); 
include('./config.php'); 
include('./randos.php'); 
 
use Twilio\Jwt\ClientToken; 
use Twilio\Jwt\Grants; 
 
// choose a random username for the connecting user 
$identity = $_GET['identity']; 
 
$capability = new ClientToken($TWILIO_ACCOUNT_SID, $TWILIO_AUTH_TOKEN); 
$capability->allowClientOutgoing($TWILIO_TWIML_APP_SID); 
$capability->allowClientIncoming($identity); 
$token = $capability->generateToken(); 
 
echo $token; 
?> 

请您参考如下方法:

感谢 Zack with Twilio 的提示,我终于可以正常工作了!

include('./vendor/autoload.php'); 
include('./config.php'); 
include('./randos.php'); 
 
use Twilio\Jwt\AccessToken; 
use Twilio\Jwt\Grants; 
use Twilio\Jwt\Grants\VoiceGrant; 
use Twilio\Rest\Client; 
 
// choose a random username for the connecting user 
$identity = randomUsername(); 
 
 
$token = new AccessToken($TWILIO_ACCOUNT_SID, $API_KEY, $API_KEY_SECRET, 3600, $identity); 
 
$grant = new VoiceGrant(); 
$grant->setPushCredentialSid($PUSH_CREDENTIAL_SID); 
$grant->setOutgoingApplicationSid($TWILIO_TWIML_APP_SID); 
$token->addGrant($grant); 
 
echo $token;