开启辅助访问 切换到宽版

精易论坛

 找回密码
 注册

QQ登录

只需一步,快速开始

用微信号发送消息登录论坛

新人指南 邀请好友注册 - 我关注人的新帖 教你赚取精币 - 每日签到


求职/招聘- 论坛接单- 开发者大厅

论坛版规 总版规 - 建议/投诉 - 应聘版主 - 精华帖总集 积分说明 - 禁言标准 - 有奖举报

查看: 840|回复: 5
收起左侧

[精币悬赏] 求大神帮我翻译下这段PHP语言

[复制链接]
结帖率:56% (5/9)
发表于 2021-3-8 21:08:23 | 显示全部楼层 |阅读模式   内蒙古自治区赤峰市
5精币
<?php


class RequestError extends Exception {
    private $responseCode;
    protected $errorCodes = array(
        'NO_NUMBERS' => 'Нет свободных номеров для приёма смс от текущего сервиса',
        'NO_BALANCE' => 'Закончился баланс',
        'BAD_ACTION' => 'Некорректное действие (параметр action)',
        'BAD_SERVICE' => 'Некорректное наименование сервиса (параметр service)',
        'BAD_KEY' => 'Неверный API ключ доступа',
        'ERROR_SQL' => 'Один из параметров имеет недопустимое значение',
        'SQL_ERROR'=> 'Один из параметров имеет недопустимое значение',
        'NO_ACTIVATION' => 'Указанного id активации не существует',
        'BAD_STATUS' => 'Попытка установить несуществующий статус',
        'STATUS_CANCEL' => 'Текущая активация отменена и больше не доступна',
        'BANNED' => 'Аккаунт заблокирован',
        'NO_CONNECTION' => 'Нет соединения с серверами sms-activate',
        'ACCOUNT_INACTIVE' => 'Свободных номеров нет',
        'NO_ID_RENT' => 'Не указан id аренды',
        'INVALID_PHONE' => 'Номер арендован не вами (неправильный id аренды)',
        'STATUS_FINISH' => 'Аренда оплачна и завершена',
        'STATUS_CANCEL' => 'Аренда отменена с возвратом денег',
        'STATUS_WAIT_CODE' => 'Ожидание первой смс',
        'INCORECT_STATUS' => 'Отсутствует или неправильно указан статус',
        'CANT_CANCEL' => 'Невозможно отменить аренду (прошло более 20 мин.)',
        'ALREADY_FINISH' => 'Аренда уже завершена',
        'ALREADY_CANCEL' => 'Аренда уже отменена',

    );

    public function __construct($errorCode) {
        $this->responseCode = $errorCode;
        $message = "Error in {$this->getFile()}, line: {$this->getLine()}: {$this->errorCodes[$errorCode]}";
        parent::__construct($message);
    }

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


}

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


class SMSActivate {
    private $url = 'https://sms-activate.ru/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 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['service'] = $operator;
        }
        if($ref){
            $requestParam['ref'] = $ref;
        }
        return $this->request($requestParam, 'POST',null,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',null,2);
    }

    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 getQiwiRequisites(){
        return $this->request(array('api_key' => $this->apiKey,'action' => __FUNCTION__),'GET',true);
    }

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

    public function getRentNumber($service, $time = 1, $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);
    }
    /**
     * @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);
        }

        $responsError = new ErrorCodes($result);
        $check = $responsError->checkExist($result);
        if ($check) {
            throw new RequestError($result);
        }


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


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

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


        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') {
            $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);
        }


        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;
    }



}



结帖率:95% (37/39)

签到天数: 7 天

发表于 2021-3-8 21:19:56 | 显示全部楼层   浙江省杭州市
给你个建议。你这翻译这么长一段,才5精币,大神没空理你的。
回复

使用道具 举报

结帖率:0% (0/1)
发表于 2021-3-8 21:49:34 | 显示全部楼层   广东省江门市
以下内容出出google翻译

<?php


类RequestError扩展了异常{
    private $ responseCode;
    保护$ ErrorCode的=阵列
        ('NO_NUMBERS'=> 'Нетсвободныхномеровдляприёмасмсоттекущего сервиса ',
        'NO_BALANCE'=> 'Закончилсябаланс',
        'BAD_ACTION'=> 'Некорректноедействие(параметр动作)',
        'BAD_SERVICE' > 'Некорректноенаименованиесервиса(параметр服务)',
        'BAD_KEY'=> 'НеверныйAPIключдоступа',
        'ERROR_SQL'=> 'одинизпараметровимеетнедопустимоезначение',
        'SQL_ERROR'=>“одинизпараметровимеетнедопустимоезначение ',
        '
        'BAD_STATUS'=> 'Попыткаустановитьнесуществующийстатус',
        'STATUS_CANCEL'=> 'Текущаяактивацияотмененаибольшенедоступна',
        'BANNED'=> 'Аккаунтзаблокирован',
        'NO_CONNECTION'=>“НетсоединенияссерверамиSMS-激活',
        'ACCOUNT_INACTIVE'=>'Свободныхномеровнет',
        'NO_ID_RENT'=>'Неуказанidаренды',
        'INVALID_PHONE'=>'Номераренден
        ' изавершена',
        'STATUS_CANCEL'=>'Арендаотмененасвозвратомденег',
        'STATUS_WAIT_CODE'=>'Ожиданиепервойсмс',
        'INCORECT_STATUS'=>'Отсутствуетилинеправильноуказанстатус',
        'CANT_CANCEL'=> 'Невозможноотменитьаренду(прошлоболее20мин。)',
        'ALREADY_FINISH'=> 'Арендаужезавершена',
        'ALREADY_CANCEL'=> 'Арендаужеотменена',

    );

    公共功能__construct($ errorCode){
        $ this-> responseCode = $ errorCode;
        $ message =“ {$ this-> getFile()}中的错误,行:{$ this-> getLine()}:{$ this-> errorCodes [$ errorCode]}”;
        父母:: __ construct($ message);
    }

    公共功能getResponseCode(){
        返回$ this-> responseCode;
    }


}

类ErrorCodes扩展了RequestError {
    公共函数checkExist($ errorCode){
        返回array_key_exists($ errorCode,$ this-> errorCodes);
    }
}


类SMSActivate {
    private $ url ='https: //sms-activate.ru/stubs/handler_api.php ';
    私人$ apiKey;

    公共功能__construct($ apiKey){
        $ this-> apiKey = $ apiKey;
    }

    公共函数getBalance(){
        返回$ this-> request(array('api_key'=> $ this-> apiKey,'action'=> __FUNCTION__),'GET');
    }
        公共函数getNumbersStatus($ country = null,$ operator = null){
        $ requestParam = array('api_key'=> $ this-> apiKey,'action'=> __FUNCTION__);


        }
        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);
        返回$ response;
    }
    公共函数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 ['service'] = $ operator;
        }
        if($ ref){
            $ requestParam ['ref'] = $ ref;
        }
        return $ this-> request($ requestParam,'POST',null,1);
    }
    公共函数setStatus($ id,$ status,$ forward = 0){
        $ requestParam = array('api_key'=> $ this-> apiKey,'

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

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

    公共函数getStatus($ id){
        返回$ this-> request(array('api_key'=> $ this-> apiKey,'action'=> __FUNCTION __,'id'=> $ id),'GET',null ,2);
    }

    公共函数getPrices($ country = null,$ service = null){
        $ requestParam = array('api_key'=> $ this-> apiKey,'action'=> __FUNCTION__);

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

        返回$ this-> request($ requestParam,'GET',true);
    }
    公共函数getQiwiRequisites(){
        返回$ this-> request(array('api_key'=> $ this-> apiKey,'action'=> __FUNCTION __),'GET',true);
    }

    公共函数getRentServicesAndCountries($ time = 1,$ operator =“ any”){
        $ requestParam = array('api_key'=> $ this-> apiKey,'action'=> __FUNCTION __,'rent_time'=> $ time,'运算符'=> $ operator);
        返回$ this-> request($ requestParam,'POST',true);
    }

    公共函数getRentNumber($ service,$ time = 1,$ country = 0,$ operator =“ any”,$ url =''){
        $ requestParam = array('api_key'=> $ this-> apiKey,'action'=> __FUNCTION__,'service'=> $ service,'rent_time'=> $ time,'operator'=> $ operator,'country' => $ country,'url'=> $ url);
        返回$ this-> requestRent($ requestParam,'POST',true);
    }

    公共函数getRentStatus($ id){
        $ requestParam = array('api_key'=> $ this-> apiKey,'action'=> __FUNCTION __,'id'=> $ id);
        返回$ this-> requestRent($ requestParam,'POST',true);
    }
    公共函数setRentStatus($ id,$ status){
        $ requestParam = array('api_key'=> $ this-> apiKey,'action'=> __FUNCTION __,'id' => $ id,'status'=> $ status);
        返回$ this-> requestRent($ requestParam,'POST',true);
    }
    / **
     * @param $ data
     * @param $ method
     * @param null $ parseAsJSON
     * @Return Mixed
     * /
    私有函数请求($ data,$ method,$ parseAsJSON = null,$ getNumber = null){
        $ method = strtoupper($ method );

        如果(!in_array($ method,array('GET','POST')))
            抛出新的InvalidArgumentException('方法只能是GET或POST');

        $ serializedData = http_build_query($ data);

        如果($ method ==='GET'){
            $ result = file_get_contents(“ $ this-> url?$ serializedData”);
        } else {
            $ options = array(
                'http'
                    'header'=>“内容类型:application / x-www-form-urlencoded \ r \ n”,
                    'method'=>'POST',
                    'content'=> $ serializedData
                )
            );

            $ context = stream_context_create($ options);
            $ result = file_get_contents($ this-> url,false,$ context);
        }

        $ responsError = new ErrorCodes($ result);
        $ check = $ responsError-> checkExist($ result);
        如果($ check){
            抛出新的RequestError($ result);
        }


        如果($ parseAsJSON)
            返回json_decode($ result,true);




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


        返回$ parsedResponse [1];
    }

    私有函数requestRent($ data,$ method,$ parseAsJSON = null,$ getNumber = null){
        $ method = strtoupper($ method);

        如果(!in_array($ method,array('GET','POST')))
            抛出新的InvalidArgumentException('方法只能是GET或POST');

        $ serializedData = http_build_query($ data);

        如果($ method ==='GET'){
            $ result = file_get_contents(“ $ this-> url?$ serializedData”);
        } else {
            $ options = array(
                'http'=> array(
                    'header'=>“内容类型:application / x-www-form-urlencoded \ r \ n”,
                    'method'=>'POST',
                    '内容'=>



            $ 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){
//抛出新的RequestError($ result [“ message”]);
//}
            返回$ result;
        }


        返回$ result;
    }



}

点评

骚..   安徽省滁州市  发表于 2021-3-8 22:32
回复

使用道具 举报

结帖率:0% (0/2)

签到天数: 16 天

发表于 2021-3-8 23:15:05 | 显示全部楼层   浙江省温州市
你直接拿PHP中间件翻译好了
回复

使用道具 举报

发表于 2021-3-11 12:03:39 | 显示全部楼层   广东省广州市
其实很简单,而且官方也给出了使用例子,照葫芦画瓢就好
//sms-activate.ru/cn/api2
如果是不知道怎么搭建环境,装个集成工具 xampp 或者 phpstudy 便可
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 注册

本版积分规则 致发广告者

发布主题 收藏帖子 返回列表

sitemap| 易语言源码| 易语言教程| 易语言论坛| 诚聘英才| 易语言模块| 手机版| 广告投放| 精易论坛
拒绝任何人以任何形式在本论坛发表与中华人民共和国法律相抵触的言论,本站内容均为会员发表,并不代表精易立场!
论坛帖子内容仅用于技术交流学习和研究的目的,严禁用于非法目的,否则造成一切后果自负!如帖子内容侵害到你的权益,请联系我们!
防范网络诈骗,远离网络犯罪 违法和不良信息举报电话0663-3422125,QQ: 800073686,邮箱:800073686@b.qq.com
Powered by Discuz! X3.4 揭阳市揭东区精易科技有限公司 ( 粤ICP备12094385号-1) 粤公网安备 44522102000125 增值电信业务经营许可证 粤B2-20192173

快速回复 返回顶部 返回列表