A
A
Alexander Stepanov2019-02-08 16:48:34
API
Alexander Stepanov, 2019-02-08 16:48:34

How to make the Instagram Oauth API work?

Good afternoon!
There is a site trip.imperiaweb.ru, there is a button "Register via Instagram".
How to fix the error related to SandBox?
I will say right away - I googled, but I did not find anything worthwhile.
The "bydlokod" is presented below:

<?php

  require __DIR__.'/config.php';
  require __DIR__.'/vendor/autoload.php';
  
  \InstagramAPI\Instagram::$allowDangerousWebUsageAtMyOwnRisk = true;
  use Medoo\Medoo;
  
  $database = new Medoo([
    'database_type' => DB_TYPE,
    'database_name' => DB_NAME,
    'server'        => DB_HOST,
    'username'      => DB_USER,
    'password'      => DB_PASS
  ]);
  
  $ig = new \InstagramAPI\Instagram($debug, $truncatedDebug, $storageConfig = []);      

  // вход в профиль админа
  $ig->login(INSTAGRAM_USERNAME, INSTAGRAM_PASSWORD);

  // работаем через проксю
  $ig->setProxy('http://'.INSTAGRAM_PROXYHOST.':'.INSTAGRAM_PROXYPORT);

  // ссылка для авторизация участника
  $login_url = 'https://api.instagram.com/oauth/authorize/?client_id=' . INSTAGRAM_CLIENT_ID . '&redirect_uri=' . urlencode(INSTAGRAM_REDIRECT_URI) . '&response_type=code&scope=basic';

  session_start();

  if ($_GET['code'] != '') { 
    		
      // Get the access token 
    	$access_token = GetAccessToken(INSTAGRAM_CLIENT_ID, INSTAGRAM_REDIRECT_URI, INSTAGRAM_CLIENT_SECRET, $_GET['code']);
    		
    	// Get user information
    	$user_info = GetUserProfileInfo($access_token);
    
    	// Now that the user is logged in you may want to start some session variables
    	$_SESSION['logged_in'] = 1;
      
      $userIds = array($user_info["id"]);
    
      $recipients = [
        'users' => $userIds // must be an [array] of valid UserPK IDs
      ];
        
      $userID = $user_info["id"];
        
      $count = $database->count("users", [
      	"userID" => $userID
      ]);
        
      if ($count == 0) {
        
        $dateReg = rus_date("l, j F Y г. в H:i");
        
        // Что ещё добавлять в базу, может имя или фотку??
        
        $database->insert('users', [
          'userID' => $userID,
          'reg' => true,
          'dateTime' => $dateReg
        ]);
        
        $text = "Вы успешно зарегистировались на вебинар! Ваша ссылка: google.ru. Дата и время:".$dateReg;
          
        $ig->direct->sendText($recipients, $text);
          
        header('Location: /index.php?do=success');
        die();       
        
      } else {
      
        header('Location: /index.php?do=repeat');
        die();
        
      }
          
  }
  
  function rus_date() {
    $translate = array(
    "am" => "дп",
    "pm" => "пп",
    "AM" => "ДП",
    "PM" => "ПП",
    "Monday" => "Понедельник",
    "Mon" => "Пн",
    "Tuesday" => "Вторник",
    "Tue" => "Вт",
    "Wednesday" => "Среда",
    "Wed" => "Ср",
    "Thursday" => "Четверг",
    "Thu" => "Чт",
    "Friday" => "Пятница",
    "Fri" => "Пт",
    "Saturday" => "Суббота",
    "Sat" => "Сб",
    "Sunday" => "Воскресенье",
    "Sun" => "Вс",
    "January" => "Января",
    "Jan" => "Янв",
    "February" => "Февраля",
    "Feb" => "Фев",
    "March" => "Марта",
    "Mar" => "Мар",
    "April" => "Апреля",
    "Apr" => "Апр",
    "May" => "Мая",
    "May" => "Мая",
    "June" => "Июня",
    "Jun" => "Июн",
    "July" => "Июля",
    "Jul" => "Июл",
    "August" => "Августа",
    "Aug" => "Авг",
    "September" => "Сентября",
    "Sep" => "Сен",
    "October" => "Октября",
    "Oct" => "Окт",
    "November" => "Ноября",
    "Nov" => "Ноя",
    "December" => "Декабря",
    "Dec" => "Дек",
    "st" => "ое",
    "nd" => "ое",
    "rd" => "е",
    "th" => "ое"
    );
    
    if (func_num_args() > 1) {
        $timestamp = func_get_arg(1);
        return strtr(date(func_get_arg(0), $timestamp), $translate);
    } else {
        return strtr(date(func_get_arg(0)), $translate);
    }
  } 
    
    // функция получения токена
    
    function GetAccessToken($client_id, $redirect_uri, $client_secret, $code) {		
    	$apiData = array(
         'client_id'       => $client_id,
         'client_secret'   => $client_secret,
         'grant_type'      => 'authorization_code',
         'redirect_uri'    => $redirect_uri,
         'code'            => $code
       );
       
       $apiHost = 'https://api.instagram.com/oauth/access_token';
       
       $ch = curl_init();
       curl_setopt($ch, CURLOPT_URL, $apiHost);
       curl_setopt($ch, CURLOPT_POST, count($apiData));
       curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($apiData));
       curl_setopt($ch, CURLOPT_HTTPHEADER, array('Accept: application/json'));
       curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
       $jsonData = curl_exec($ch);
       curl_close($ch);
       
       
       $user = @json_decode($jsonData); 
       
       $access_token = $user->access_token; //this is your access token
       
       return $access_token;	
    }
    
    
    //функция получения информации о пользователе
    
    function GetUserProfileInfo($access_token) { 
    	$url = 'https://api.instagram.com/v1/users/self/?access_token=' . $access_token;	
    	$ch = curl_init();		
    	curl_setopt($ch, CURLOPT_URL, $url);		
    	curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);	
    	curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
    	$data = json_decode(curl_exec($ch), true);
    	$http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);	
    	curl_close($ch); 
    	if($data['meta']['code'] != 200 || $http_code != 200)
    		throw new Exception('Error : Failed to get user information');  
    	return $data['data'];
    }     
  
  function generateTitle(){
    $type = $_GET["type"];
    switch ($type) {
      case "travel":
        $title = "Узнай, как выйти на пассивный доход от 650$ до 50000$ и зарабатывать в любой точке мира без графиков, начальников и стресса";
        break;
      case "business":
        $title = "Узнай, как выйти на пассивный доход от 2000$ в мес за 45 дней, используя новый подход к туристическому бизнесу";
        break;
      case "network":
        $title = "Узнай, как быстро выйти в топ и зарабатывать 45000$ на пассиве без продаж, приглашений и списков! Уникальный партнерский проект для путешественников";
        break;
      default:
        $title = "Узнай, как выйти на пассивный доход от 2000$ в мес за 45 дней, используя новый подход к туристическому бизнесу";
        break;
    }
    return $title;    
  }

?>

<!DOCTYPE html>
<html>
<head>
  <meta charset="UTF-8">
  <title>Клуб путешественников</title>
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <link rel="apple-touch-icon" sizes="57x57" href="favicon/apple-icon-57x57.png">
  <link rel="apple-touch-icon" sizes="60x60" href="favicon/apple-icon-60x60.png">
  <link rel="apple-touch-icon" sizes="72x72" href="favicon/apple-icon-72x72.png">
  <link rel="apple-touch-icon" sizes="76x76" href="favicon/apple-icon-76x76.png">
  <link rel="apple-touch-icon" sizes="114x114" href="favicon/apple-icon-114x114.png">
  <link rel="apple-touch-icon" sizes="120x120" href="favicon/apple-icon-120x120.png">
  <link rel="apple-touch-icon" sizes="144x144" href="favicon/apple-icon-144x144.png">
  <link rel="apple-touch-icon" sizes="152x152" href="favicon/apple-icon-152x152.png">
  <link rel="apple-touch-icon" sizes="180x180" href="favicon/apple-icon-180x180.png">
  <link rel="icon" type="image/png" sizes="192x192"  href="favicon/android-icon-192x192.png">
  <link rel="icon" type="image/png" sizes="32x32" href="favicon/favicon-32x32.png">
  <link rel="icon" type="image/png" sizes="96x96" href="favicon/favicon-96x96.png">
  <link rel="icon" type="image/png" sizes="16x16" href="favicon/favicon-16x16.png">
  <link rel="manifest" href="favicon/manifest.json">
  <meta name="msapplication-TileColor" content="#ffffff">
  <meta name="msapplication-TileImage" content="favicon/ms-icon-144x144.png">
  <meta name="theme-color" content="#ffffff">
</head>
<body>

  <div class="wrap">
    <div class="main">
      <h1 class="main-title"><?=generateTitle()?></h1>
      <div class="main-video">
        <video poster="/path/to/poster.jpg" id="player" playsinline controls>
          <source src="video.mp4" type="video/mp4">
          <source src="video.webm" type="video/webm">
        </video>  
      </div>
      <div class="main-btn-wrap">
        <a href="<?=$login_url?>" class="main-btn <?=$btn_show;?>" title="Через Instagram">Регистрация на вебинар с помощью Instagram</a>
      </div>
    </div>
  </div>
  
  <div id="success" class="modal">
    <p class="modal-title">Поздравляем с успешной регистрацией!</p>
    <p>Дата и время вебинара, а также ссылка для входа<br> отправлены Вам в Instagram Директ.</p>
  </div>
  
  <div id="repeat" class="modal">
    <p class="modal-title">Вы уже были зарегистированы!</p>
    <p>Если Вы этого не делали, сообщите нам: <a href="instagram.com/vadbiz">instagram.com/vadbiz</a></p>
  </div>
  
  <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/plyr/3.4.8/plyr.min.js"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-modal/0.9.1/jquery.modal.min.js"></script>
  <script src="main.js"></script>     
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/meyer-reset/2.0/reset.min.css" />
  <link href="https://fonts.googleapis.com/css?family=Ubuntu+Condensed&amp;subset=cyrillic" rel="stylesheet">
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/plyr/3.4.8/plyr.css" />
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/jquery-modal/0.9.1/jquery.modal.min.css" />
  <link rel="stylesheet" href="styles.css" />
  
</body>
</html>

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Aalexeich, 2019-04-15
@zloycoder

The application is currently in sandbox mode . After you finish developing and debugging your application, you need to submit it for moderation.
This is done in the "Permissions" section, I recommend that you first carefully read the rules for creating moderation requests in the Instagram documentation .
Related article: https://bobmckay.com/web/simple-tutorial-for-getti...

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question