instagram怎么用_用PHP和Instagram API征服Instagram

instagram怎么用

Instagram’s API allows us to interact with data such as user info, media (photos and videos), likes, comments, and tags. For example, you can search for media around a specific location and filter the results by time. The API also allows us to post comments or like specific media. For now, only uploading media isn’t supported. You can always look at the API endpoints documentation if you want to know about the full functionality.

InstagramAPI允许我们与用户信息,媒体(照片和视频),喜欢,评论和标签等数据进行交互。 例如,您可以搜索特定位置周围的媒体并按时间过滤结果。 该API还允许我们发布评论或喜欢特定的媒体。 目前,仅不支持上传媒体。 如果您想了解全部功能,可以随时查看API端点文档

alt

API调用和限制 (API Calls and Limits)

There are two types of API calls you can perform with the Instagram API: Unauthenticated and Authenticated. Unauthenticated API calls only need the client ID, and authenticated API calls use OAuth, specifically OAuth 2.0. If you don’t know what OAuth is, check out this Introduction to OAuth 2 article on DigitalOcean.

您可以使用Instagram API执行两种类型的API调用:未认证和已认证。 未经身份验证的API调用仅需要客户端ID,经过身份验证的API调用使用OAuth,尤其是OAuth 2.0。 如果您不知道什么是OAuth,请参阅DigitalOcean上的这篇OAuth简介2文章

Before we move on, it’s important to understand that there are limits to this API. At the moment of writing of this article, you can only perform 5000 authenticated calls per token and 5000 unauthenticated calls to the API. This is regardless of the endpoint that you use, though there are specific endpoints each of which has its own limits. You can check out the endpoint-specific rate limits section in the limits page if you want to learn more.

在继续之前,重要的是要了解此API的局限性。 在撰写本文时,每个令牌只能执行5000个经过身份验证的调用,而对API只能进行5000个未经身份验证的调用。 尽管有特定的终结点,每个终结点都有其自己的限制,但这与您使用的终结点无关。 如果您想了解更多信息,可以在限制页面中查看特定于端点的速率限制部分。

注册申请 (Registering an Application)

Needless to say, you need to have your own Instagram account in order to work with the Instagram API. Then, sign up as a developer.

不用说,您需要拥有自己的Instagram帐户才能使用Instagram API。 然后,注册为开发人员

instagram developer signup

Next we have to register an application. We can do that by going to the Instagram Developer page and clicking on the ‘Register Your Application’ button. If you’ve never created an app before, you’ll be redirected to the app registration page which looks like this:

接下来,我们必须注册一个应用程序。 我们可以通过转到Instagram开发人员页面并单击“注册您的应用程序”按钮来实现。 如果您以前从未创建过应用程序,那么您将被重定向到如下所示的应用程序注册页面:

register new application

If you have already created an app previously, then it leads you to the app management page which lists all your existing apps. From there, all you have to do is to click on the ‘Register a New Client’ button which would lead you to the same page as above.

如果您之前已经创建了一个应用程序,那么它将带您进入应用程序管理页面 ,其中列出了所有现有应用程序。 在这里,您所要做的就是单击“注册新客户”按钮,这将带您进入与上述相同的页面。

Once you’re on the app registration page, fill in all the fields. The website URL is the URL to your app’s website. The redirect URI is the URL where the user will be redirected after giving access permission to your app. This has to be an HTTPS URL. If you do not have an HTTPS server, you can use Apache and Ngrok. Download the ngrok version for your operating system, extract it and then execute the following command in your preferred install directory. Replace 80 with the port where your server is running:

进入应用程序注册页面后,填写所有字段。 网站网址是您应用程序网站的网址。 重定向URI是在授予对您的应用访问权限后将重定向用户的URL。 这必须是HTTPS URL。 如果没有HTTPS服务器,则可以使用Apache和Ngrok下载适用于您的操作系统的ngrok版本 ,解压缩该版本,然后在您的首选安装目录中执行以下命令。 将80替换为服务器运行端口:

ngrok http 80

What this does is assign an HTTP and HTTPS URL to your Apache server running on localhost. You can then use the HTTPS URL for testing. Use this URL for the Website URL and Redirect URI fields in the app registration page.

这是为在本地主机上运行的Apache服务器分配HTTP和HTTPS URL。 然后,您可以使用HTTPS URL进行测试。 将此URL用于应用程序注册页面中的“网站URL”和“重定向URI”字段。

Once that’s done, just click on the ‘Register’ button to finish the registration. If all went well, you will be greeted with a client ID and client secret. We will be using these later on to perform requests to the API.

完成后,只需单击“注册”按钮即可完成注册。 如果一切顺利,将为您提供一个客户端ID和客户端密码。 我们稍后将使用它们来执行对API的请求。

API控制台 (API Console)

You can use the API console to play around the requests which you can make with the Instagram API. To use the API console, expand the API method selection menu on the left side of the console. From there, you can select a method you want to use for your request. Most methods require authentication so you have to select OAuth 2 from the Authentication drop-down and then sign in with your existing Instagram account. Do note that any requests you perform are performed on your behalf. This means that any action you do, such as liking a photo or following a user will be performed by your account.

您可以使用API控制台来处理可以使用Instagram API发出的请求。 要使用API​​控制台,请展开控制台左侧的API方法选择菜单。 从那里,您可以选择要用于请求的方法。 大多数方法都需要身份验证,因此您必须从“身份验证”下拉菜单中选择“ OAuth 2”,然后使用现有的Instagram帐户登录。 请注意,您执行的所有请求均以您的名义执行。 这意味着您执行的任何操作(例如,喜欢照片或关注用户)将由您的帐户执行。

API Console

The API Console is pretty self-explanatory. You can select what type of HTTP request (GET, POST, DELETE, PUT) you want to use, enter the URL where the request will be submitted, and enter required query parameters. You can see the actual request and response that have been made after you click the ‘Send’ button.

API控制台非常不言自明。 您可以选择要使用的HTTP请求类型(GET,POST,DELETE,PUT),输入将在其中提交请求的URL,然后输入所需的查询参数。 单击“发送”按钮后,您可以看到实际的请求和响应。

使用PHP进行API调用 (Making API Calls with PHP)

Now we’re ready to interact with the API using PHP. We can do that with Guzzle, an HTTP client for PHP. Install it with Composer:

现在,我们准备使用PHP与API进行交互。 我们可以使用PHP的HTTP客户端Guzzle做到这一点 。 使用Composer安装它:

composer require guzzlehttp/guzzle:~5.0

Optionally, you can install the Slim PHP framework if you want to follow along with the demo project. Note that we’re using version 5 of Guzzle because version 6 is based on PSR-7 and thus lacking many of the practical features of past iterations.

(可选)如果要与演示项目一起进行,则可以安装Slim PHP框架。 请注意,我们使用的是Guzzle的第5版,因为第6版基于PSR-7,因此缺少过去迭代的许多实用功能。

composer require slim/slim

If you want to use Slim, you need to install Twig, as well as Slim Views, so you can use Twig from within Slim.

如果要使用Slim,则需要安装Twig和Slim Views,以便可以在Slim中使用Twig。

composer require twig/twig
composer require slim/views

Once that’s done, create a new PHP file and add the following code:

完成后,创建一个新PHP文件并添加以下代码:

<?php
require 'vendor/autoload.php';

use GuzzleHttp\Client;

$client = new Client();

Next, add the client ID, client secret and redirect URL of your Instagram app.

接下来,添加您的Instagram应用程序的客户端ID,客户端密码和重定向URL。

define("CLIENT_ID", "YOUR CLIENT ID");
define("CLIENT_SECRET", "YOUR CLIENT SECRET");
define("REDIRECT_URL", "YOUR REDIRECT URL");

Set up Slim to make use of Twig for handling views. Also, enable error reporting and set the directory for caching the views:

设置Slim以使用Twig处理视图。 另外,启用错误报告并设置用于缓存视图的目录:

app = new \Slim\Slim(array(
    'view' => new \Slim\Views\Twig() //use twig for handling views
));

$view = $app->view();
$view->parserOptions = array(
    'debug' => true, //enable error reporting in the view
    'cache' => dirname(__FILE__) . '/cache' //set directory for caching views
);

获取访问令牌 (Getting the Access Token)

To get an access token, we first need to construct the login URL. The login URL points to the page that asks the user to grant permission to the app. The base login URL is: https://api.instagram.com/oauth/authorize. And then we need to pass in the client_id, redirect_uri, scope and response_type as query parameters.

要获得访问令牌,我们首先需要构造登录URL。 登录URL指向要求用户向应用授予权限的页面。 基本登录URL是: https://api.instagram.com/oauth/authorize : https://api.instagram.com/oauth/authorize 。 然后我们需要传入client_idredirect_uriscoperesponse_type作为查询参数。

https://api.instagram.com/oauth/authorize?client_id={$client_id}&redirect_uri={$redirect_url}&scope=basic&response_type=code

You already know what the client_id and redirect_url are, so let’s talk about the scope and the response_type.

您已经知道client_idredirect_url是什么,因此让我们讨论一下scoperesponse_type

  • scope – this is where you specify what your app can do. Currently, the scopes available are basic, comments, relationships, and likes. basic is provided by default. This gives you read access to all of the API endpoints. The other 3, however, require your app to be submitted for review, because they allow your app to like, comment, follow or unfollow a specific user.

    scope –您可以在此处指定应用程序可以执行的操作。 当前,可用范围是basiccommentsrelationshipslikes 。 默认情况下提供basic 。 这使您可以读取所有API端点。 但是,其他3条要求将您的应用提交审核,因为它们允许您的应用喜欢,评论,关注或取消关注特定用户。

  • response_type – the type of response we will get once the user grants permission to the app. On the server-side, this should be code and on the client-side this should be token. We’re primarily working on the server so this should be code. This means that an authorization code is returned after permission has been granted.

    response_type –用户授予应用权限后,我们将获得的响应类型。 在服务器端,这应该是code而在客户端,这应该是token 。 我们主要在服务器上工作,因此应该是code 。 这意味着在授予权限后将返回授权码。

Once the user has granted permission to the app, he will be redirected to the redirect URL that was specified. The authorization code is passed along with this URL as a query parameter. Next we need to make a POST request to the /oauth/access_token endpoint, additionally passing in the client ID, client secret, grant type, redirect URL and the code. The grant type is how the access token will be acquired after the user has granted permission to your app. In this case, we’re using authorization_code. This is the code that is passed as a query parameter in the redirect URL. Once the request is made, we convert the response from JSON to an array by calling the json method on the response. Finally, we render the view.

一旦用户授予了该应用程序的权限,他将被重定向到指定的重定向URL。 授权代码与该URL一起作为查询参数传递。 接下来,我们需要向/oauth/access_token端点发出POST请求,另外传递客户端ID,客户端密码,授权类型,重定向URL和代码。 授予类型是用户向您的应用授予权限后如何获取访问令牌。 在这种情况下,我们使用的是authorization_code 。 这是在重定向URL中作为查询参数传递的代码。 发出请求后,我们通过在响应上调用json方法,将响应从JSON转换为数组。 最后,我们渲染视图。

$app->get('/login', function () use ($app, $client) {

    $data = array();
    $login_url = '';

    if($app->request->get('code')){

        $code = $app->request->get('code');

        $response = $client->post('https://api.instagram.com/oauth/access_token', array('body' => array(
            'client_id' => CLIENT_ID,
            'client_secret' => CLIENT_SECRET,
            'grant_type' => 'authorization_code',
            'redirect_uri' => REDIRECT_URL,
            'code' => $code
        )));

        $data = $response->json();

    }else{

        $login_url = "https://api.instagram.com/oauth/authorize?client_id={$client_id}&redirect_uri={$redirect_url}&scope=basic&response_type=code";

    }


    $app->render('home.php', array('data' => $data, 'login_url' => $login_url));

});

Views in Slim are stored in the templates directory by default. Here are the contents of the home.php view.

默认情况下,Slim中的视图存储在templates目录中。 这是home.php视图的内容。

{% if login_url %}
<a href="{{ login_url }}">login with instagram</a>
{% else %}
    <div>
        <img src="{{ data.user.profile_picture }}" alt="{{ data.user.username }}">
    </div>
    <ul>
        <li>username: {{ data.user.username }}</li>
        <li>bio: {{ data.user.bio }}</li>
        <li>website: {{ data.user.website }}</li>
        <li>id: {{ data.user.id }}</li>
        <li>access token: {{ data.access_token }}</li>
    </ul>
{% endif %}

At this point you can now extract the access token and store it somewhere safe. Instagram didn’t mention how long an access token will last. All the documentation says is that it will expire at a time in the future. Therefore, we need to handle the event where the access token expires. You can do that by checking the error_type under the meta item in the response. If the value is OAuthAccessTokenError, then it means your access token has expired. You will only need to check for this item if the code in the meta item has a value other than 200. 200 means OK, just like the HTTP status code. 400 means error.

此时,您现在可以提取访问令牌并将其存储在安全的地方。 Instagram没有提到访问令牌将持续多长时间。 所有文件都说它将在将来的某个时间到期 。 因此,我们需要处理访问令牌过期的事件。 您可以通过检查做error_typemeta在响应项目。 如果值为OAuthAccessTokenError ,则表示您的访问令牌已过期。 如果meta项目中的code的值不是200,则只需检查该项目。200表示OK,就像HTTP状态代码一样。 400表示错误。

Now we can make authenticated calls to the API. First, let’s try searching for recent photos taken in Niagara Falls via tag searching. Remember that tags don’t have spaces in them so we have to stick with camelCase:

现在我们可以对API进行身份验证的调用。 首先,让我们尝试通过标签搜索来搜索在尼亚加拉大瀑布拍摄的近期照片。 请记住,标签中没有空格,因此我们必须坚持使用camelCase:

$app->get('/tags/search', function() use($app, $client, $access_token) {

    $tag = 'niagaraFalls';
    $response = $client->get("https://api.instagram.com/v1/tags/{$tag}/media/recent?access_token={$access_token}");
    $results = $response->json();

    $app->render('images.php', array('results' => $results));

});

The images.php view just loops through all the results that are returned and extracts the low resolution image URL. We then use that as a source for the image tag.

images.php视图仅循环浏览返回的所有结果,并提取低分辨率图像URL。 然后,我们将其用作图像标签的来源。

{% for row in results.data %}
    <img src="{{ row.images.low_resolution.url }}"> 
{% endfor %}

By default, Instagram returns a maximum of 20 photos per request. You can, however, specify the count as one of the query parameters to increase or limit the number of photos returned.

默认情况下,Instagram每个请求最多返回20张照片。 但是,您可以将count指定为查询参数之一,以增加或限制返回的照片数量。

If you’re not sure if the tag that you are using exists, you can first perform a tag search and then use the first result that comes out:

如果不确定所使用的标签是否存在,则可以先执行标签搜索,然后使用出现的第一个结果:

$app->get('/tags/search-with-tagvalidation', function() use($app, $client, $access_token) {

    $query = 'Niagara Falls';
    $response = $client->get("https://api.instagram.com/v1/tags/search?access_token={$access_token}&q={$query}");
    $result = $response->json();

    if(!empty($result['data'])){
        $tag = $result['data'][0]['name'];

        $response = $client->get("https://api.instagram.com/v1/tags/{$tag}/media/recent?access_token={$access_token}");
        $results = $response->json();
        $app->render('images.php', array('results' => $results));
    }else{
        echo 'no results';
    }

});

用户供稿 (User Feed)

The user feed can be accessed by submitting a GET request to the /users/self/feed endpoint:

可以通过向/users/self/feed端点提交GET请求来访问/users/self/feed

$app->get('/user/feed', function() use($app, $client, $access_token) {

    $response = $client->get("https://api.instagram.com/v1/users/self/feed?access_token={$access_token}");
    $results = $response->json();

});

Here’s a screenshot of a sample user feed response:

这是示例用户供稿响应的屏幕截图:

user feed

搜索用户 (Searching for Users)

Let’s try searching for users who have ‘Ash Ketchum’ as their name:

让我们尝试搜索名称为“ Ash Ketchum”的用户:

$app->get('/user/search', function() use($app, $client, $access_token) {

    $query = 'Ash Ketchum';
    $response = $client->get("https://api.instagram.com/v1/users/search?q={$query}&access_token={$access_token}");
    $results = $response->json();

});

The call above returns the username, id, profile_picture, and full_name of the user. Not all of the results are exact matches though.

上面的调用返回usernameidprofile_picturefull_name 。 并非所有结果都是完全匹配。

Here’s the screenshot of the response that I got:

这是我得到的响应的屏幕截图:

user search

在特定位置搜索照片 (Searching for Photos in a Specific Place)

You can also search for photos or videos uploaded in a specific place by using the Google Geocoding API. We use the Google Geocoding API to convert our query to coordinates (latitude and longitude) which the Instagram API requires. Here’s an example:

您还可以使用Google Geocoding API搜索在特定位置上传的照片或视频。 我们使用Google Geocoding API将查询转换为Instagram API所需的坐标(纬度和经度)。 这是一个例子:

$app->get('/geo/search', function() use($app, $client, $access_token) {

    $query = 'banaue rice terraces';

    //make a request to the Google Geocoding API
    $place_response = $client->get("http://maps.googleapis.com/maps/api/geocode/json?address={$query}&sensor=false");
    $place_result = $place_response->json();

    if($place_result['status'] == 'OK'){

        //extract the lat and lng values 
        $lat = $place_result['results'][0]['geometry']['location']['lat'];
        $lng = $place_result['results'][0]['geometry']['location']['lng'];

        //make a request to the Instagram API using the lat and lng
        $response = $client->get("https://api.instagram.com/v1/media/search?access_token={$access_token}&lat={$lat}&lng={$lng}");

        $results = $response->json();

        if(!empty($results['data'])){   

            $app->render('images.php', array('results' => $results));

        }else{
            echo 'no photos found';
        }

    }else{
        echo 'place not found';
    }

});

Note that you can also specify the distance, min_timestamp, and max_timestamp to this endpoint to further filter the results. The default distance is 1km and you can specify up to 5km. min_timestamp and max_timestamp are unix timestamps for limiting results to photos that were taken within a specific time period. You can use Carbon to easily generate timestamps based on user input such as ‘yesterday’, ‘5 days ago’, ‘1 week ago’.

请注意,您还可以指定到该端点的distancemin_timestampmax_timestamp ,以进一步过滤结果。 默认距离为1公里,您最多可以指定5公里。 min_timestampmax_timestamp是unix时间戳,用于将结果限制为在特定时间段内拍摄的照片。 您可以使用Carbon轻松根据用户输入(例如“昨天”,“ 5天前”,“ 1周前”)生成时间戳。

分页 (Pagination)

You may have noticed that the Instagram API already makes our life easy with pagination. If the results of a specific API call have a next page on it, you can just use the value of next_url under the pagination item as the URL to be used on the next request. This allows you to access the next page easily. Though do keep in mind that you need to store the id of the first item on the current page so that you can still access that page after you have navigated to the next page.

您可能已经注意到,Instagram API通过分页已经使我们的生活变得轻松。 如果特定API调用的结果上有下一页,则可以仅使用pagination项下的next_url的值作为下一个请求要使用的URL。 这使您可以轻松访问下一页。 尽管要记住,您需要将第一项的id存储在当前页面上,以便在导航到下一页后仍可以访问该页面。

PHP客户端 (PHP Client)

If you want to make your life even easier when working with the Instagram API, there’s a PHP library called Instagram-PHP-API which provides convenience methods. To install it, execute composer require cosenary/instagram.

如果您想在使用Instagram API时让生活更轻松,则有一个名为Instagram-PHP-APIPHP库提供了便捷的方法。 要安装它,请执行composer require cosenary/instagram

Once that’s done, you can use it by adding the following code:

完成后,您可以通过添加以下代码来使用它:

use MetzWeb\Instagram\Instagram;

$instagram = new Instagram(array(
    'apiKey' => CLIENT_ID,
    'apiSecret' => CLIENT_SECRET,
    'apiCallback' => REDIRECT_URL
));

Here are a few examples.

这里有一些例子。

获取登录URL (Getting the Login URL)

$instagram->getLoginUrl(array('basic', 'relationships'));

The array argument is optional. It contains the scopes that you want to use.

数组参数是可选的。 它包含您要使用的范围。

获取访问令牌 (Getting the Access Token)

Pretty much the same as what we did earlier using Guzzle, only this time, we’re calling methods and the data that we need becomes readily available.

与我们之前使用Guzzle进行的操作几乎相同,只是这次,我们正在调用方法,并且所需的数据随时可用。

$app->get('/login2', function () use ($app, $instagram) {

    $login_url = $instagram->getLoginUrl(array('basic', 'likes'));

    if(!empty($_GET['code'])){

        $code = $_GET['code'];
        $data = $instagram->getOAuthToken($code); //get access token using the authorization code

        $instagram->setAccessToken($data);

        $access_token = $instagram->getAccessToken();

        //do anything you want with the access token

    }else{
       $app->render('login.php', array('login_url' => $login_url));
    }

});

获取用户信息 (Getting User Info)

You can get the user info by calling the getUser method. $user_id can be omitted if you only want to get the user info of the currently logged in user.

您可以通过调用getUser方法获取用户信息。 如果只想获取当前登录用户的用户信息,则可以省略$user_id

$user_data = $instagram->getUser($user_id);

Laravel (Laravel)

If you use Laravel, someone has also created a Laravel Wrapper which uses this library. You can check it out here.

如果您使用Laravel,则还会创建一个使用此库的Laravel包装器。 您可以在这里查看

结论 (Conclusion)

In this tutorial, we learned how to work with the Instagram API using the Guzzle HTTP Client and an Instagram client for PHP. The Instagram API is a really nice way to interact with an Instagram users’ data. With it, you can build some really interesting applications.

在本教程中,我们学习了如何使用Guzzle HTTP客户端和适用于PHP的Instagram客户端来使用Instagram API。 Instagram API是与Instagram用户数据进行交互的一种非常好的方法。 有了它,您可以构建一些非常有趣的应用程序。

Have you built anything with the API? Do you prefer Guzzle or the Instagram PHP library? Why? Let us know in the comments!

您是否使用API​​构建了任何东西? 您喜欢Guzzle还是Instagram PHP库? 为什么? 让我们在评论中知道!

翻译自: https://www.sitepoint.com/conquering-instagram-with-php-and-the-instagram-api/

instagram怎么用

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值