腾讯云 服务器 api 购买 php-sdk
腾讯文档写的简直太差了
示例都不好好写
以下是我根据源码整理的写法示例
<?php
/**
* 创建云服务器
*
* 2019-05-31 范国金
*/
namespace app\pocket\cli;
use TencentCloud\Common\Credential;
use TencentCloud\Cvm\V20170312\CvmClient;
use TencentCloud\Cvm\V20170312\Models\DescribeInstancesRequest;
use TencentCloud\Cvm\V20170312\Models\InternetAccessible;
use TencentCloud\Cvm\V20170312\Models\Placement;
use TencentCloud\Cvm\V20170312\Models\RunInstancesRequest;
use think\console\Command;
use think\console\Input;
use think\console\input\Argument;
use think\console\Output;
class Cvm extends Command
{
protected $cvmClient;
protected function configure()
{
$this
->setName('cvm')
->addArgument('bandwidth', Argument::OPTIONAL, 'band width')
->addArgument('internetType', Argument::OPTIONAL, 'tnternet charge type')
->addArgument('area', Argument::OPTIONAL, 'the area of the cvm')
->setDescription('to purchase a new cvm of qcloud');
}
protected function execute(Input $input, Output $output)
{
$band = $input->getArgument('bandwidth');
$area = $input->getArgument('area');
$internet = (int) $input->getArgument('internetType');
$config = config('qcloud.user_purchase');
// 购买
$res = $this->purchase((int) ($band ?? $config['bandwith']), $config['internettype'][$internet], $area ?? $config['area'], $config['secretid'], $config['secretkey'], $config);
$output->writeln($res);
// 查询
$intance = json_decode($res, true)['InstanceIdSet'];
for ($i = 0; $i < 10; $i++) {
$res = $this->describe($intance);
$data = json_decode($res, true);
if ($data['InstanceSet'][0]['InstanceState'] != 'PENDING') {
break;
}
sleep(3);
}
$output->writeln($res);
$ip = array_column($data['InstanceSet'], 'PublicIpAddresses');
$output->writeln('ip: ' . json_encode($ip));
}
protected function purchase(string $bandwidth, string $internetType, string $area, string $secretid, string $secretkey, array $config)
{
$cred = new Credential($secretid, $secretkey);
$client = new CvmClient($cred, $area);
$zone = $config['zone'];
$imageid = $config['imageid'];
$this->cvmClient = $client;
// 可用区
$placement = new Placement();
$placement->setZone($zone);
// 公网访问
$internet = new InternetAccessible;
$internet->setInternetMaxBandwidthOut($bandwidth);
$internet->setInternetChargeType($internetType);
$internet->setPublicIpAssigned(true);
// 设置主机
$req = new RunInstancesRequest();
$req->setImageId($imageid);
$req->setPlacement($placement);
$req->setInternetAccessible($internet);
// 请求接口
$res = $client->RunInstances($req)->toJsonString();
return $res;
}
protected function describe($instanceid)
{
// 查询列表
$describe = new DescribeInstancesRequest;
$describe->setInstanceIds($instanceid);
$res = $this->cvmClient->DescribeInstances($describe)->toJsonString();
return $res;
}
}
最后更新于 2019-05-31 07:24:31 并被添加「腾讯云 服务器 api 购买 php-sdk」标签,已有 759 位童鞋阅读过。
此处评论已关闭