API를 이용하여 인스타그램에 사진을 올리는 방법
사용자가 직접 Instagram에 업로드한 사진을 게시해야 하는 php 어플리케이션을 만들고 있는데, 빠른 검색 결과 API에 그런 기능이 없는 것을 알 수 있었습니다.왜냐하면 그들은 하나를 제공해야 하기 때문이다.php를 사용하여 사진을 업로드 할 수 있는 다른 방법(안드로이드용 앱이나 iOS용 앱 제외)은 없는지 잘 모르겠습니다.혹시 가능하다면 어떤 아이디어라도 주세요.
나도 이걸 읽었어
PHP를 사용하여 Instagram과 링크 및 사진을 공유하는 방법
업데이트:
Instagram은 현재 이 방법으로 계정을 금지하고 이미지를 삭제합니다.주의해서 사용해 주세요.
은 '아주 좋다'는한 것 같습니다.it can't be done어느 정도 맞습니다.API Instagram입니다.그러나 API를 리버스엔지니어링하면 가능합니다.
function SendRequest($url, $post, $post_data, $user_agent, $cookies) {
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://i.instagram.com/api/v1/'.$url);
curl_setopt($ch, CURLOPT_USERAGENT, $user_agent);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
if($post) {
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);
}
if($cookies) {
curl_setopt($ch, CURLOPT_COOKIEFILE, 'cookies.txt');
} else {
curl_setopt($ch, CURLOPT_COOKIEJAR, 'cookies.txt');
}
$response = curl_exec($ch);
$http = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
return array($http, $response);
}
function GenerateGuid() {
return sprintf('%04x%04x-%04x-%04x-%04x-%04x%04x%04x',
mt_rand(0, 65535),
mt_rand(0, 65535),
mt_rand(0, 65535),
mt_rand(16384, 20479),
mt_rand(32768, 49151),
mt_rand(0, 65535),
mt_rand(0, 65535),
mt_rand(0, 65535));
}
function GenerateUserAgent() {
$resolutions = array('720x1280', '320x480', '480x800', '1024x768', '1280x720', '768x1024', '480x320');
$versions = array('GT-N7000', 'SM-N9000', 'GT-I9220', 'GT-I9100');
$dpis = array('120', '160', '320', '240');
$ver = $versions[array_rand($versions)];
$dpi = $dpis[array_rand($dpis)];
$res = $resolutions[array_rand($resolutions)];
return 'Instagram 4.'.mt_rand(1,2).'.'.mt_rand(0,2).' Android ('.mt_rand(10,11).'/'.mt_rand(1,3).'.'.mt_rand(3,5).'.'.mt_rand(0,5).'; '.$dpi.'; '.$res.'; samsung; '.$ver.'; '.$ver.'; smdkc210; en_US)';
}
function GenerateSignature($data) {
return hash_hmac('sha256', $data, 'b4a23f5e39b5929e0666ac5de94c89d1618a2916');
}
function GetPostData($filename) {
if(!$filename) {
echo "The image doesn't exist ".$filename;
} else {
$post_data = array('device_timestamp' => time(),
'photo' => '@'.$filename);
return $post_data;
}
}
// Set the username and password of the account that you wish to post a photo to
$username = 'ig_username';
$password = 'ig_password';
// Set the path to the file that you wish to post.
// This must be jpeg format and it must be a perfect square
$filename = 'pictures/test.jpg';
// Set the caption for the photo
$caption = "Test caption";
// Define the user agent
$agent = GenerateUserAgent();
// Define the GuID
$guid = GenerateGuid();
// Set the devide ID
$device_id = "android-".$guid;
/* LOG IN */
// You must be logged in to the account that you wish to post a photo too
// Set all of the parameters in the string, and then sign it with their API key using SHA-256
$data ='{"device_id":"'.$device_id.'","guid":"'.$guid.'","username":"'.$username.'","password":"'.$password.'","Content-Type":"application/x-www-form-urlencoded; charset=UTF-8"}';
$sig = GenerateSignature($data);
$data = 'signed_body='.$sig.'.'.urlencode($data).'&ig_sig_key_version=4';
$login = SendRequest('accounts/login/', true, $data, $agent, false);
if(strpos($login[1], "Sorry, an error occurred while processing this request.")) {
echo "Request failed, there's a chance that this proxy/ip is blocked";
} else {
if(empty($login[1])) {
echo "Empty response received from the server while trying to login";
} else {
// Decode the array that is returned
$obj = @json_decode($login[1], true);
if(empty($obj)) {
echo "Could not decode the response: ".$body;
} else {
// Post the picture
$data = GetPostData($filename);
$post = SendRequest('media/upload/', true, $data, $agent, true);
if(empty($post[1])) {
echo "Empty response received from the server while trying to post the image";
} else {
// Decode the response
$obj = @json_decode($post[1], true);
if(empty($obj)) {
echo "Could not decode the response";
} else {
$status = $obj['status'];
if($status == 'ok') {
// Remove and line breaks from the caption
$caption = preg_replace("/\r|\n/", "", $caption);
$media_id = $obj['media_id'];
$device_id = "android-".$guid;
$data = '{"device_id":"'.$device_id.'","guid":"'.$guid.'","media_id":"'.$media_id.'","caption":"'.trim($caption).'","device_timestamp":"'.time().'","source_type":"5","filter_type":"0","extra":"{}","Content-Type":"application/x-www-form-urlencoded; charset=UTF-8"}';
$sig = GenerateSignature($data);
$new_data = 'signed_body='.$sig.'.'.urlencode($data).'&ig_sig_key_version=4';
// Now, configure the photo
$conf = SendRequest('media/configure/', true, $new_data, $agent, true);
if(empty($conf[1])) {
echo "Empty response received from the server while trying to configure the image";
} else {
if(strpos($conf[1], "login_required")) {
echo "You are not logged in. There's a chance that the account is banned";
} else {
$obj = @json_decode($conf[1], true);
$status = $obj['status'];
if($status != 'fail') {
echo "Success";
} else {
echo 'Fail';
}
}
}
} else {
echo "Status isn't okay";
}
}
}
}
}
}
위의 코드를 텍스트 에디터에 복사하여 붙여넣기만 하면 됩니다.그렇게 몇 가지 변수를 변경하여 VOILA!기사를 썼는데 여러 번 해봤어요.데모를 보려면 여기를 클릭하십시오.
공유한 링크를 읽을 경우 허용되는 답변은 다음과 같습니다.
API를 통해 Instagram에 사진을 올릴 수 없습니다.
Instagram은 다음과 같이 말하고 있습니다.
2021년 1월 26일부터 Instagram APIs(New) 효과로 콘텐츠를 게시할 수 있게 되었습니다!
https://developers.facebook.com/blog/post/2021/01/26/introducing-instagram-content-publishing-api/
운이 좋으시길 바랍니다.
Instagram은 이제 기업들이 새로운 컨텐츠 퍼블리싱 베타 엔드포인트를 사용하여 게시물을 예약할 수 있게 되었습니다.
https://developers.facebook.com/blog/post/2018/01/30/instagram-graph-api-updates/
단, 이 블로그 투고 https://business.instagram.com/blog/instagram-api-features-updates에서는 이 API를 페이스북 마케팅 파트너 또는 Instagram 파트너에게만 개방하고 있음을 명확히 하고 있습니다.
투고 스케줄링을 시작하려면 Facebook 마케팅 파트너 또는 Instagram 파트너 중 하나와 협력해 주십시오.
Facebook의 이 링크(https://developers.facebook.com/docs/instagram-api/content-publishing)는 비공개 베타로 나열됩니다.
Content Publishing API는 Facebook Marketing Partners 및 Instagram Partners에서만 비공개 베타판입니다.현재 신규 지원자는 접수하지 않습니다.
하지만 이렇게 하면 됩니다.
사진 한 장...
https://www.example.com/images/bronz-fonz.jpg
해시태그 #BronzFonz와 함께 게시하려고 합니다.
해서 '아까불까불까불까불까불까불까불까불까불까불까불까불까불까불까불까요?/user/media하여 다음과 같이.
POST graph.facebook.com
/17841400008460056/media?
image_url=https%3A%2F%2Fwww.example.com%2Fimages%2Fbronz-fonz.jpg&
caption=%23BronzFonz
이렇게 하면 컨테이너 ID(17889455560051444)가 반환됩니다.이 ID는 다음과 같이 /user/media_publish 엣지를 사용하여 게시됩니다.
POST graph.facebook.com
/17841405822304914/media_publish
?creation_id=17889455560051444
다음 예시는 문서에서 보여 줍니다.
IFTT를 비롯한 여러 서비스를 사용해 보았지만, 모두 Instagram이 아닌 Instagram에서 다른 플랫폼으로 무언가를 하거나 글을 올리고 있었습니다.더 읽어보니 현재 Instagram은 그런 API를 제공하지 않습니다.
파란색 스택을 사용하려면 다시 많은 양의 설치와 수동 작업만 수행해야 합니다.
그러나 데스크톱 버전에서 Google Chrome을 사용하여 Instagram에 게시할 수 있습니다.좀 손봐야겠어요.
- 크롬을 열고 Instagram.com을 방문합니다.
- Chrome을 마우스 오른쪽 버튼으로 클릭하여 요소를 검사합니다.
- 개발자 도구의 오른쪽 상단 모서리 메뉴 드롭다운에서 추가 도구를 선택합니다.
- 네트워크 조건을 추가로 선택합니다.
- 네트워크 선택 섹션에서 이름이 지정된 사용자 에이전트의 두 번째 섹션을 참조하십시오.
- 자동으로 선택을 취소하고 지정된 사용자 에이전트 목록에서 Android용 크롬을 선택합니다.
- Instagram.com 페이지를 갱신합니다.
UI의 변경과 Instagram에 투고할 수 있는 옵션이 표시됩니다.이제 당신의 삶은 편안합니다.더 쉬운 방법이 있으면 알려주세요.
나는 그것에 대해 https://www.inteligentcomp.com/2018/11/how-to-upload-to-instagram-from-pc-mac.html에 썼다.
작업 스크린샷
AWS lamda와 puppeteer(chrome-aws-lambda)를 사용하여 Instagram에 글을 올리는 방법을 찾고 있는 분들을 위해.이 솔루션에서는, 투고 마다 1매의 포토를 투고할 수 있는 것에 주의해 주세요.람다를 사용하지 않을 경우 교체만 하면 됩니다.chrome-aws-lambdapuppeteer.
lamda의 첫 번째 부팅에서는 Instagram이 "Suspicious login attempt"를 검출하기 때문에 작동하지 않는 것은 정상입니다.PC를 사용하여 Instagram 페이지를 열고 승인만 하면 됩니다.
내 코드는 다음과 같습니다. 자유롭게 최적화할 수 있습니다.
// instagram.js
const chromium = require('chrome-aws-lambda');
const username = process.env.IG_USERNAME;
const password = process.env.IG_PASSWORD;
module.exports.post = async function(fileToUpload, caption){
const browser = await chromium.puppeteer.launch({
args: [...chromium.args, '--window-size=520,700'],
defaultViewport: chromium.defaultViewport,
executablePath: await chromium.executablePath,
headless: false,
ignoreHTTPSErrors: true,
});
const page = await browser.newPage();
await page.setUserAgent('Mozilla/5.0 (iPhone; CPU iPhone OS 10_3_2 like Mac OS X) AppleWebKit/603.2.4 (KHTML, like Gecko) FxiOS/7.5b3349 Mobile/14F89 Safari/603.2.4');
await page.goto('https://www.instagram.com/', {waitUntil: 'networkidle2'});
const [buttonLogIn] = await page.$x("//button[contains(., 'Log In')]");
if (buttonLogIn) {
await buttonLogIn.click();
}
await page.waitFor('input[name="username"]');
await page.type('input[name="username"]', username)
await page.type('input[name="password"]', password)
await page.click('form button[type="submit"]');
await page.waitFor(3000);
const [buttonSaveInfo] = await page.$x("//button[contains(., 'Not Now')]");
if (buttonSaveInfo) {
await buttonSaveInfo.click();
}
await page.waitFor(3000);
const [buttonNotificationNotNow] = await page.$x("//button[contains(., 'Not Now')]");
const [buttonNotificationCancel] = await page.$x("//button[contains(., 'Cancel')]");
if (buttonNotificationNotNow) {
await buttonNotificationNotNow.click();
} else if (buttonNotificationCancel) {
await buttonNotificationCancel.click();
}
await page.waitFor('form[enctype="multipart/form-data"]');
const inputUploadHandle = await page.$('form[enctype="multipart/form-data"] input[type=file]');
await page.waitFor(5000);
const [buttonPopUpNotNow] = await page.$x("//button[contains(., 'Not Now')]");
const [buttonPopUpCancel] = await page.$x("//button[contains(., 'Cancel')]");
if (buttonPopUpNotNow) {
await buttonPopUpNotNow.click();
} else if (buttonPopUpCancel) {
await buttonPopUpCancel.click();
}
await page.click('[data-testid="new-post-button"]')
await inputUploadHandle.uploadFile(fileToUpload);
await page.waitFor(3000);
const [buttonNext] = await page.$x("//button[contains(., 'Next')]");
await buttonNext.click();
await page.waitFor(3000);
await page.type('textarea', caption);
const [buttonShare] = await page.$x("//button[contains(., 'Share')]");
await buttonShare.click();
await page.waitFor(3000);
return true;
};
// handler.js
await instagram.post('/tmp/image.png', '#text');
로컬 파일 경로여야 합니다.url일 경우 먼저 /tmp 폴더에 다운로드하십시오.
갱신일 :
Instagram은 실행할 때마다 수동으로 승인하지 않는 한 의심스러운 로그인 시도를 차단합니다.이 문제를 해결하려면 쿠키를 json으로 저장하고 puppeteer로 가져오는 것이 좋습니다.
이 질문을 발견한 사용자는 iPhone 후크를 사용하여 iPhone의 Instagram 공유 플로우(앱에서 필터 화면으로)에 사진을 전달할 수 있습니다: http://help.instagram.com/355896521173347 그 외에는 현재 api 버전1에서는 방법이 없습니다.
UI가 있으면 "API"가 있는 것입니다.다음 예를 사용합니다.새로 만든 블로그 게시물에 사용하는 사진을 게시하고 싶습니다.워드프레스라고 가정해봅시다.
- RSS를 통해 블로그를 지속적으로 모니터링하는 서비스를 만듭니다.
- 새로운 블로그 투고가 게시되면 사진을 다운로드하세요.
- (선택사항) 일부 오버레이 등을 사진에 적용하려면 서드파티 API를 사용합니다.
- PC 또는 서버의 잘 알려진 위치에 사진을 배치합니다.
- 브라우저를 모바일로 사용할 수 있도록 Chrome(위 참조)를 설정합니다.
- Selenium(또는 다른 라이브러리)을 사용하여 Instagram에 게시하는 모든 과정을 시뮬레이션합니다.
- 됐어요. 드셔야 해요.
API를 사용하여 Instagram에 사진을 게시하는 API는 없지만, 간단한 방법은 구글 확장자 "User Agent"를 설치하는 것입니다. 이것은 브라우저를 안드로이드 모바일 크롬 버전으로 변환합니다.다음은 확장 링크 https://chrome.google.com/webstore/detail/user-agent-switcher/clddifkhlkcojbojppdojfeeikdkgiae?utm_source=chrome-ntp-icon 입니다.
확장 아이콘을 클릭하고 안드로이드용 크롬을 선택한 후 Instagram.com을 엽니다.
언급URL : https://stackoverflow.com/questions/18844706/how-to-post-pictures-to-instagram-using-api
'source' 카테고리의 다른 글
| JSON에서 새로운 회선을 처리하려면 어떻게 해야 합니까? (0) | 2023.01.06 |
|---|---|
| 여러 콘텍스트 매니저에 "with" 블록을 생성하시겠습니까? (0) | 2023.01.06 |
| 비동기 화살표 함수의 구문 (0) | 2023.01.06 |
| MySQL Alias 값을 기반으로 한 더하기 및 빼기 (0) | 2023.01.06 |
| JavaScript에서 커스텀에러를 작성하려면 어떻게 해야 하나요? (0) | 2023.01.06 |

