Почему не удается с помощью cURL не удается подключиться к api по url?

Поставил локальный сервер с cURL.

введите сюда описание изображения

Хочу подключиться к api стороннего сервиса. Использую при этом следующий скрипт:

class Auth {
public $url = "https://xxxxxxxxxxxxxxxxx";
public $credentials = [
    'user_name' => 'xxxxxxxxxxxx',
    'user_pass' => 'xxxxxxxxxxxx',
    'product_code' => 'xxx'
    ];

    function moveaway () {
        $access = json_encode($credentials);
        $getting = curl_init($url);
        curl_setopt($getting, CURLOPT_POST, 1);
        curl_setopt($getting, CURLOPT_POSTFIELDS, $access);
        curl_setopt($getting, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($getting, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($getting, CURLOPT_HEADER, false);
        $output = curl_exec($getting);
        curl_close($getting);
        echo $output;
    }
}

Почему-то этот код не подключается к api. В консоли никаких ответов сервера, но и никаких ошибок:

введите сюда описание изображения

Подскажите, пожалуйста, что я делаю не так!?


Ответы (2 шт):

Автор решения: webxak

Может так сделать.

$access = json_encode($this->credentials);
$getting = curl_init($this->url);

Как ты обращаешься к свойствам класса? $url) $this->url так наверное будет лучше. Добавь спецификатор у метода public function moveaway () {} сделай свойства private если ты их не будешь использовать открыто, переопределять к примеру...

→ Ссылка
Автор решения: cy4oHok

Если вкратце, то ошибка в том, что Вы внутри функции класса обращаетесь к переменной которая видна только функции. Поменяйте

$access = json_encode($credentials);

на

$access = json_encode($this->credentials);

Ну, а лучше перепишите класс на более правильный вариант. Что-то вроде вот такого

class Auth {
     private $url = null;
     private $user_name = null;
     private $user_pass = null;
     private $product_code = null;

     public function setURL( $url ) {
         $this->url = $url;
     }
     public function getURL() {
         return $this->url;
     }

     public function setUserName( $user_name ) {
         $this->user_name = $user_name;
     }
     public function getUserName() {
         return $this->user_name;
     }

     public function setUserPass( $user_pass ) {
         $this->user_pass = $user_pass;
     }
     public function getUserPass() {
         return $this->user_pass;
     }

     public function setProductCode( $product_code ) {
         $this->product_code = $product_code;
     }
     public function getProductCode() {
         return $this->product_code;
     }

    public function moveAway () {
        $ch = curl_init($this->url);
        curl_setopt($ch ,CURLOPT_HTTPHEADER, ["Accept:application/json", "Content-Type: application/json"]);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode([
            'user_name' => $this->user_name,
            'user_pass' => $this->user_pass,
            'product_code' => $this->product_code
        ]));
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_HEADER, false);//<-- true for debug headers
        curl_setopt($ch, CURLOPT_USERAGENT, "curl/7.58.0"); //<-- set another useragent if need
        //curl_setopt($ch, CURLOPT_VERBOSE, 1); //<-- debug
        $output = curl_exec($ch);
        curl_close($ch);
        echo $output;
    }
}

Через сеттеры выставляете все переменные, затем вызываете moveAway

→ Ссылка