首页 > 编程语言 >SMS-Activate API PHP SDK

SMS-Activate API PHP SDK

时间:2023-04-01 20:13:01浏览次数:87  
标签:__ Activate return requestParam country SMS API array id

SMS-Activate是著名的短信验证码接码平台,其官网为 https://sms-activate.org/

本文介绍SMS-Activate API PHP SDK。代码如下:

 

<?php


class RequestError extends Exception
{
    private $responseCode;

    public function __construct($errorCode)
    {
        $this->responseCode = $errorCode;
//        если надо получать файл и строку в которой получена ошибка
//        $message = "Error in {$this->getFile()}, line: {$this->getLine()}: {$this->errorCodes[$errorCode]}";
        $message = "{$this->errorCodes[$errorCode]}";
        parent::__construct($message);
    }

    protected $errorCodes = array(
        'ACCESS_ACTIVATION' => 'Сервис успешно активирован',
        'ACCESS_CANCEL'     => 'активация отменена',
        'ACCESS_READY'      => 'Ожидание нового смс',
        'ACCESS_RETRY_GET'  => 'Готовность номера подтверждена',
        'ACCOUNT_INACTIVE'  => 'Свободных номеров нет',
        'ALREADY_FINISH'    => 'Аренда уже завершена',
        'ALREADY_CANCEL'    => 'Аренда уже отменена',
        'BAD_ACTION'        => 'Некорректное действие (параметр action)',
        'BAD_SERVICE'       => 'Некорректное наименование сервиса (параметр service)',
        'BAD_KEY'           => 'Неверный API ключ доступа',
        'BAD_STATUS'        => 'Попытка установить несуществующий статус',
        'BANNED'            => 'Аккаунт заблокирован',
        'CANT_CANCEL'       => 'Невозможно отменить аренду (прошло более 20 мин.)',
        'ERROR_SQL'         => 'Один из параметров имеет недопустимое значение',
        'NO_NUMBERS'        => 'Нет свободных номеров для приёма смс от текущего сервиса',
        'NO_BALANCE'        => 'Закончился баланс',
        'NO_YULA_MAIL'      => 'Необходимо иметь на счету более 500 рублей для покупки сервисов холдинга Mail.ru и Mamba',
        'NO_CONNECTION'     => 'Нет соединения с серверами sms-activate',
        'NO_ID_RENT'        => 'Не указан id аренды',
        'NO_ACTIVATION'     => 'Указанного id активации не существует',
        'STATUS_CANCEL'     => 'Активация/аренда отменена',
        'STATUS_FINISH'     => 'Аренда оплачена и завершена',
        'STATUS_WAIT_CODE'  => 'Ожидание первой смс',
        'STATUS_WAIT_RETRY' => 'ожидание уточнения кода',
        'SQL_ERROR'         => 'Один из параметров имеет недопустимое значение',
        'INVALID_PHONE'     => 'Номер арендован не вами (неправильный id аренды)',
        'INCORECT_STATUS'   => 'Отсутствует или неправильно указан статус',
        'WRONG_SERVICE'     => 'Сервис не поддерживает переадресацию',
        'WRONG_SECURITY'    => 'Ошибка при попытке передать ID активации без переадресации, или же завершенной/не активной активации'
    );

    public function getResponseCode()
    {
        return $this->errorCodes[$this->responseCode];
    }
}

class ErrorCodes extends RequestError
{
    public function checkExist($errorCode)
    {
        return array_key_exists($errorCode, $this->errorCodes);
    }
}

class SMSActivate
{
    private $url = 'https://api.sms-activate.org/stubs/handler_api.php';

    private $apiKey;

    public function __construct($apiKey)
    {
        $this->apiKey = $apiKey;
    }

    public function getBalance()
    {
        return $this->request(array('api_key' => $this->apiKey, 'action' => __FUNCTION__), 'GET');
    }

    public function getBalanceAndCashBack()
    {
        return $this->request(array('api_key' => $this->apiKey, 'action' => __FUNCTION__), 'GET');
    }

    public function getTopCountriesByService($service = '', $freePrice = false)
    {
        $requestParam = array('api_key' => $this->apiKey, 'action' => __FUNCTION__, 'service' => $service, '$freePrice' => $freePrice);
        return $this->request($requestParam, 'POST', true);
    }

    public function getNumbersStatus($country = null, $operator = null)
    {
        $requestParam = array('api_key' => $this->apiKey, 'action' => __FUNCTION__);
        if ($country) {
            $requestParam['country'] = $country;
        }
        if ($operator && ($country == 0 || $country == 1 || $country == 2)) {
            $requestParam['service'] = $operator;
        }
        $response = array();
        $changeKeys = $this->request($requestParam, 'GET', true);
        foreach ($changeKeys as $services => $count) {
            $services = trim($services, "_01");
            $response[$services] = $count;
        }
        unset($changeKeys);
        return $response;
    }

    public function getNumber($service, $country = null, $forward = 0, $operator = null, $ref = null)
    {
        $requestParam = array('api_key' => $this->apiKey, 'action' => __FUNCTION__, 'service' => $service, 'forward' => $forward);
        if ($country) {
            $requestParam['country'] = $country;
        }
        if ($operator && ($country == 0 || $country == 1 || $country == 2)) {
            $requestParam['operator'] = $operator;
        }
        if ($ref) {
            $requestParam['ref'] = $ref;
        }
        return $this->request($requestParam, 'POST', null, 1);
    }

    public function getMultiServiceNumber($services, $forward = 0, $country = null, $operator = null, $ref = null)
    {
        $requestParam = array('api_key' => $this->apiKey, 'action' => __FUNCTION__, 'multiService' => $services, 'forward' => $forward);
        if ($country) {
            $requestParam['country'] = $country;
        }
        if ($operator && ($country == 0 || $country == 1 || $country == 2)) {
            $requestParam['operator'] = $operator;
        }
        if ($ref) {
            $requestParam['ref'] = $ref;
        }
        return $this->request($requestParam, 'POST', true, 1);
    }

    public function setStatus($id, $status, $forward = 0)
    {
        $requestParam = array('api_key' => $this->apiKey, 'action' => __FUNCTION__, 'id' => $id, 'status' => $status);

        if ($forward) {
            $requestParam['forward'] = $forward;
        }

        return $this->request($requestParam, 'POST', null, 3);
    }

    public function getStatus($id)
    {
        return $this->request(array('api_key' => $this->apiKey, 'action' => __FUNCTION__, 'id' => $id), 'GET', false, 2);
    }

    public function getCountries()
    {
        return $this->request(array('api_key' => $this->apiKey, 'action' => __FUNCTION__), 'GET', true);
    }

    public function getAdditionalService($service, $activationId)
    {
        return $this->request(array('api_key' => $this->apiKey, 'action' => __FUNCTION__, 'service' => $service, 'id' => $activationId), 'GET', false, 1);
    }

    public function getFullSms($id)
    {
        return $this->request(array('api_key' => $this->apiKey, 'action' => __FUNCTION__, 'id' => $id), 'GET');
    }

    public function getPrices($country = null, $service = null)
    {
        $requestParam = array('api_key' => $this->apiKey, 'action' => __FUNCTION__);

        if ($country !== null) {
            $requestParam['country'] = $country;
        }
        if ($service) {
            $requestParam['service'] = $service;
        }

        return $this->request($requestParam, 'GET', true);
    }

    public function getRentServicesAndCountries($time = 4, $operator = "any")
    {
        $requestParam = array('api_key' => $this->apiKey, 'action' => __FUNCTION__, 'rent_time' => $time, 'operator' => $operator);
        return $this->requestRent($requestParam, 'POST', true);
    }

    public function getRentNumber($service, $time = 4, $country = 0, $operator = "any", $url = '')
    {
        $requestParam = array('api_key' => $this->apiKey, 'action' => __FUNCTION__, 'service' => $service, 'rent_time' => $time, 'operator' => $operator, 'country' => $country, 'url' => $url);
        return $this->requestRent($requestParam, 'POST', true);
    }

    public function getRentStatus($id)
    {
        $requestParam = array('api_key' => $this->apiKey, 'action' => __FUNCTION__, 'id' => $id);
        return $this->requestRent($requestParam, 'POST', true);
    }

    public function setRentStatus($id, $status)
    {
        $requestParam = array('api_key' => $this->apiKey, 'action' => __FUNCTION__, 'id' => $id, 'status' => $status);
        return $this->requestRent($requestParam, 'POST', true);
    }

    public function getRentList()
    {
        $requestParam = array('api_key' => $this->apiKey, 'action' => __FUNCTION__);
        return $this->requestRent($requestParam, 'POST', true);
    }

    public function continueRentNumber($id, $time = 4)
    {
        $requestParam = array('api_key' => $this->apiKey, 'action' => __FUNCTION__, 'id' => $id, 'rent_time' => $time);
        return $this->requestRent($requestParam, 'POST', true);
    }

    public function getContinueRentPriceNumber($id, $time)
    {
        $requestParam = array('api_key' => $this->apiKey, 'action' => __FUNCTION__, 'id' => $id, 'rent_time' => $time);
        return $this->requestRent($requestParam, 'POST', false);
    }

    /**
     * @param $data
     * @param $method
     * @param null $parseAsJSON
     * @return mixed
     */
    private function request($data, $method, $parseAsJSON = null, $getNumber = null)
    {
        $method = strtoupper($method);

        if (!in_array($method, array('GET', 'POST'))) {
            throw new InvalidArgumentException('Method can only be GET or POST');
        }

        $serializedData = http_build_query($data);

        if ($method === 'GET') {
            $result = file_get_contents("$this->url?$serializedData");
        } else {
            $options = array(
                'http' => array(
                    'header' => "Content-type: application/x-www-form-urlencoded\r\n",
                    'method' => 'POST',
                    'content' => $serializedData
                )
            );
            $context = stream_context_create($options);
            $result = file_get_contents($this->url, false, $context);
        }

        $responseError = new ErrorCodes($result);
        $check = $responseError->checkExist($result);

        try {
            if ($check) {
                throw new RequestError($result);
            }
        } catch (Exception $e) {
            return $e->getResponseCode();
        }

        if ($parseAsJSON) {
            return json_decode($result, true);
        }

        $parsedResponse = explode(':', $result);

        if ($getNumber == 1) {
            return array('id' => $parsedResponse[1], 'number' => $parsedResponse[2]);
        }
        if ($getNumber == 2) {
            return array('status' => $parsedResponse[0], 'code' => $parsedResponse[1]);
        }
        if ($getNumber == 3) {
            return array('status' => $parsedResponse[0]);
        }
        return $parsedResponse[1];
    }

    private function requestRent($data, $method, $parseAsJSON = null, $getNumber = null)
    {
        $method = strtoupper($method);

        if (!in_array($method, array('GET', 'POST'))) {
            throw new InvalidArgumentException('Method can only be GET or POST');
        }
        $serializedData = http_build_query($data);

        if ($method === 'GET') {
            $request_url = "$this->url?$serializedData";
            $result = file_get_contents($request_url);
        } else {
            $options = array(
                'http' => array(
                    'header' => "Content-type: application/x-www-form-urlencoded\r\n",
                    'method' => 'POST',
                    'content' => $serializedData
                )
            );
            $context = stream_context_create($options);
            $result = file_get_contents($this->url, false, $context);
        }

        if ($parseAsJSON) {
            $result = json_decode($result, true);
//            $responsError = new ErrorCodes($result["message"]);
//            $check = $responsError->checkExist($result["message"]);  // раскоментить если необходимо включить исключения для Аренды
//            if ($check) {
//                throw new RequestError($result["message"]);
//            }
            return $result;
        }
        return $result;
    }
}

 

标签:__,Activate,return,requestParam,country,SMS,API,array,id
From: https://www.cnblogs.com/botai/p/SMS-Activate-PHP-SDK.html

相关文章

  • yapi文档使用说明记录
    yapi文档地址:http://192.168.0.97:3000/    在idea下载插件:easy-yapi  配置插件 在 Settings->Other Settings -> EasyAPI 中的 **server **栏中填写服务器地址:http://yapi.gwm.cn/在 Settings->Other Settings -> EasyAPI 的 **tokens **......
  • Springboot 系列 (26) - Springboot+HBase 大数据存储(四)| Springboot 项目通过 HBase
    ApacheHBase是Java语言编写的一款Apache开源的NoSQL型数据库,不支持SQL,不支持事务,不支持Join操作,没有表关系。ApacheHBase构建在ApacheHadoop和ApacheZookeeper之上。ApacheHBase:https://hbase.apache.org/HBase的安装配置,请参考“Springboot系列(24)-......
  • 自动生成接口文档coreapi的使用
    1.安装coreapi  2.路由中配置路由固定格式   3.视图类自动生成接口文档第一种_单一方法的视图   4.第二种_包含多个方法的视图_在类视图的文档字符串中_分开方法定义   5.生成接口文档的setting和路由配置   5_1.生成接口文档的setting......
  • 项目一众筹网05_02_[树形开发]菜单管理、API文档发布到web服务器、配置文件里面修改to
    系列文章目录文章目录系列文章目录08-页面显示树形结构-前端-使用真实数据09-准备zTree的API文档(因为现在没有图标)==API文档发布到web服务器上去==配置文件里面修改tomcat的默认端口号(只需改动3个地方)10-前端-显示图标-分析思路(-页面显示树形结构)11-前端-显示图标-代码实现(-页面......
  • 常用API(Math,System,Runtime,Object,Objects,BigInteger,BigDecimal,正则表达式)
    常用API(Math,System,Runtime,Object,Objects,BigInteger,BigDecimal,正则表达式)多使用帮助文档类型取值范围和默认值Math类:​ 概念:帮助我们进行数学计算的工具类,里面的方法都是静态的,所以无需实例化这个类​ 常用方法:​ abs::获取绝对值 absExact:获取绝对值 rou......
  • 使用Apipost自动化测试工具来优化测试流程
    随着项目研发进程的不断推进,软件功能不断增多,对于软件测试的要求也越来越高。为了提高测试效率和减少测试成本,许多软件测试团队借助于自动化测试工具来优化测试流程。Apipost也提供了自动化测试工具,在本文中,我们将探讨如何借助Apipost自动化测试工具来优化测试流程。Apipost......
  • 细数N个获取天气信息的免费 API ,附超多免费可用API 推荐(三)
    前言市面上有N多个查询天气信息的软件、小程序以及网页入口,基本都是通过调用天气查询API去实现的。今天整理了一下多种场景的天气预报API接口分享给大家,有需要赶紧收藏起来。(apispace.com) 天气预报查询天气预报查询支持全国以及全球多个城市的天气查询,包含国内3400+个......
  • 各类电商平台批量获取商品信息 API 详细操作说明
    前言获取商品信息可以更加快捷的查看商品的详请参数,同理批量获取商品信息的话就可以查看多个商品的信息参数,便于我们查看整个店铺的数据情况方便运营管理。具体操作如下:先获取一个key和secret,登入测试网址,选择API名称-批量获取商品信息,输入自己的key和secret,点击测试​​​​​​......
  • 好饭不怕晚,Google基于人工智能AI大语言对话模型Bard测试和API调用(Python3.10)
    谷歌(Google)作为开源过著名深度学习框架Tensorflow的超级大厂,是人工智能领域一股不可忽视的中坚力量,旗下新产品Bard已经公布测试了一段时间,毁誉参半,很多人把Google的Bard和OpenAI的ChatGPT进行对比,GoogleBard在ChatGPT面前似乎有些技不如人。事实上,GoogleBard并非对标ChatGPT......
  • Asp.Net Core 动态生成WebApi
    在WebApi架构体系中,一般需要先编写应用服务实现,再通过编写Controller来实现应用服务的Web接口。Controller中的代码作用仅仅是调用Service的方法,将Service提升为Web接口,其实完全可以通过动态生成WebApi来减少编码工作。在.Net示例项目ABP中已经实现了动态生成WebApi的功能,Panda.Dy......