Answer the question
In order to leave comments, you need to log in
How to login to Instagram via mgp25/Instagram-API?
Good afternoon.
There was a problem with authorization when posting to Instagram.
Debugging displays the following error: "Posting failed. User not logged in. Please call login() and then try again.".
Using SSH socks5, I set up a proxy server with the server from which Instagram requests are sent, logged in through the web version and confirmed there that I was logged in, but next time the error will appear again.
Please tell me how to solve this problem.
Thanks a lot.
Answer the question
In order to leave comments, you need to log in
if we are talking about OAuth, then it is obvious that the browser must use the same proxy as the php code
This is because Instagram does not trust your IP from which you are trying to auto-post. Usually, when this nonsense, as in the screenshot, pops up in your application or in the web version, Insta gives an error "Challenge required" when auto-publishing (look at the logs).
In order to defeat this, you need to receive an SMS from insta and send it from the server as confirmation that your robot is not a robot.
I did like this:
1) Since. in the mgp25/Instagram-API library, the _setUser() method is private, you cannot access it from outside. Therefore, we make a "laying": in the Instagram() class in the Instagram-API\src\Instagram.php file, at the very beginning of the class, add a public method:
public function changeUser( $username, $password )
{
$this->_setUser($username, $password);
}
# код из SMS (возможно, вы иначе принимаете GET)
$code = isset($_GET['code']) ? $_GET['code'] : false;
# данные от аккаунта Instagram
$username = '******';
$password = '******';
# папка с файлами данных авторизации робота (путь от корня сайта)
$user_path = app_path('Core/Classes/Instagram-API/sessions/'.$username);
# временный файл с данными от Инсты
$user_tmp_file = $user_path.'/'.$username.'-custom-response.dat';
# если код еще не отправлялся - его надо отправить
if (empty($code))
{
# для начала ВАЖНО удалить старые файлы от предыдущих авторизаций
if (file_exists($user_path.'/'.$username.'-settings.dat')) {
unlink($user_path.'/'.$username.'-settings.dat');
}
if (file_exists($user_path.'/'.$username.'-cookies.dat')) {
unlink($user_path.'/'.$username.'-cookies.dat');
}
\InstagramAPI\Instagram::$allowDangerousWebUsageAtMyOwnRisk = true;
$ig = new \InstagramAPI\Instagram(false, false);
# затем ВАЖНО произвести попытку авторизации без старых данных авторизации (которые только что удалили)
try {
$instagram_login = $ig->login($username, $password);
} catch (\Exception $e) {
# Если IG вернул ошибку "Challenge required"
if ( ($check = mb_strpos( mb_strtolower($e->getMessage()), 'challenge required') ) !== false) {
# отправляем SMS
$custom_response = $ig->request(mb_substr(
$e->getResponse()->
getChallenge()->
getApiPath()
, 1))->
setNeedsAuth(false)->
addPost("choice", 0)->
getDecodedResponse();
# сохраняем временные данные, которые пришли от Инсты при отправке SMS (тут нам важен "nonce_code")
@mkdir($user_path, 0777);
file_put_contents($user_tmp_file, json_encode($custom_response), LOCK_EX);
var_dump($custom_response);
}
}
# иначе, если вы уже отправили код и передали его в GET, то отправляем Инсте ответ:
} else {
if (file_exists($user_tmp_file)) {
$tmp_data = json_decode(file_get_contents($user_tmp_file), true);
\InstagramAPI\Instagram::$allowDangerousWebUsageAtMyOwnRisk = true;
$ig = new \InstagramAPI\Instagram(false, false);
try {
# изменяем данные аккаунта нашим методом changeUser()
$ig->changeUser($username, $password);
# и шлем инсте ответ с кодом из SMS
$custom_response = $ig->request("challenge/".$tmp_data['user_id']."/".$tmp_data['nonce_code']."/")->setNeedsAuth(false)->addPost("security_code", $code)->getDecodedResponse();
var_dump($custom_response);
} catch (Exception $e) {
exit("Error ".$e->getMessage());
}
}
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question