[英]How to refresh Instagram Basic Display API token automatically?
I'm trying to set up an instagram feed (just images and links) of a public instagram account for my Nextjs app.我正在尝试为我的 Nextjs 应用程序设置公共 instagram 帐户的 instagram 提要(仅图像和链接)。
I know I need to use the Instagram Basic Display API and get a Long-Lived Access Token but it expires after 60 days and I don't want to have to manually refresh it.我知道我需要使用Instagram 基本显示 API并获取长期访问令牌,但它会在 60 天后过期,我不想手动刷新它。 Does anyone know a good, preferably free, way of doing this automatically?
有谁知道自动执行此操作的好方法,最好是免费的?
I have looked at instagram-token-agent but that setup uses Heroku and an add-on that costs $30 a month which seems high.我看过instagram-token-agent但该设置使用 Heroku 和一个每月花费 30 美元的附加组件,这似乎很高。
Any ideas or links would be really helpful, thanks!任何想法或链接都会非常有帮助,谢谢!
I eventually ended up using Google Cloud Secret Manager.我最终使用了 Google Cloud Secret Manager。
Overview: Secret Manager stores long-lived token and every rotation triggers a pub/sub that then triggers a cloud function.概述:Secret Manager 存储长期存在的令牌,每次轮换都会触发 pub/sub,然后触发云函数。 The cloud function refreshes the token for a new one and then adds a new version to the secret.
云函数为新的令牌刷新令牌,然后向密钥添加新版本。
Name it "instagram-token" and add your long lived token as the secret value.将其命名为“instagram-token”并将您的长期存在的令牌添加为秘密值。 For now leave everything else default and create secret.
现在保留其他一切默认并创建秘密。
Create a service account for secret manager为 secret manager 创建一个服务帐号
In your terminal:在您的终端中:
gcloud auth login
then然后
gcloud beta services identity create \
--service "secretmanager.googleapis.com" \
--project "YOUR_GCP_PROJECT_ID"
Create pub/sub topic 创建发布/订阅主题
Create a new topic and name it "instagram-token-refresh" and leave the rest default.创建一个新主题并将其命名为“instagram-token-refresh”,其余保持默认。
Give secret manager permission to publish pub/sub 授予秘密管理员发布发布/订阅的权限
In your new pub/sub topic go to permissions -> Add Principle.在您的新发布/订阅主题中,转到权限 -> 添加原则。 Search and add service-{id}@gcp-sa-secretmanager.iam.gserviceaccount.com.
搜索并添加 service-{id}@gcp-sa-secretmanager.iam.gserviceaccount.com。 Add the new role Pub/Sub Publisher
添加新角色 Pub/Sub 发布者
Add rotation and pub/sub to secret将轮换和发布/订阅添加到秘密
Now every 50 days your "instagram-token-refresh" pub/sub will be triggered.现在每 50 天您的“instagram-token-refresh”发布/订阅将被触发。
Create Cloud Function创建云函数
package.json包.json
{ "name": "refresh-instagram-token", "version": "0.0.1", "dependencies": { "@google-cloud/pubsub": "^0.18.0", "@google-cloud/secret-manager": "^3.10.1", "axios": "^0.24.0" } }
index.js索引.js
// Import the Secret Manager client const { SecretManagerServiceClient } = require("@google-cloud/secret-manager"); const axios = require('axios'); // name of function is the same as entry point exports.refreshInstaToken = async (event, context) => { // check pub/sub message is rotation to prevent infinte looping const event_type = event && event.attributes.eventType; //allowing SECRET_VERSION_ENABLE lets you manually trigger this function by disabling the secret and then enabling it (rather than waiting for rotation trigger) if (event_type != "SECRET_ROTATE" && event_type != "SECRET_VERSION_ENABLE") { return null; } // secret name const parent = event.attributes.secretId; const name = parent + "/versions/latest"; // Instantiates a client const client = new SecretManagerServiceClient(); // get latest secret const [version] = await client.accessSecretVersion({ name: name, }); // Extract the payload as a string. const secret = version.payload.data.toString(); // refresh token const requesturl = `https://graph.instagram.com/refresh_access_token?grant_type=ig_refresh_token&access_token=${secret}`; const response = await axios.get(requesturl); const data = await response.data; // data = {"access_token", "token_type", "expires_in"} // check access_token isn't null if (data && data.access_token) { // Payload is the plaintext data to store in the secret const newSecret = Buffer.from(data.access_token, "utf8"); // add new secret version (the refreshed token) const [newVersion] = await client.addSecretVersion({ parent: parent, payload: { data: newSecret, }, }); console.log(`Added new secret version ${newVersion.name}`); // get new secret version number let newVersionN = newVersion.name.split("/"); newVersionN = newVersionN[newVersionN.length - 1]; if (newVersionN > 1) { // if is a second version delete one before it const nameToDestroy = parent + "/versions/" + (newVersionN - 1); const [deletedVersion] = await client.destroySecretVersion({ name: nameToDestroy, }); console.info(`Destroyed ${deletedVersion.name}`); } } };
Adding/Accessing Secrets Ref 添加/访问 Secrets Ref
Consume event notifications with Cloud Functions Ref 使用 Cloud Functions Ref 使用事件通知
Give cloud functions permissions to Secret为 Secret 授予云函数权限
Accessing Secret Manager from service account从服务帐户访问 Secret Manager
Setup credentials environment variable设置凭据环境变量
create .env.local file in next js root directory在下一个 js 根目录中创建 .env.local 文件
add new empty value GOOGLE_APPLICATION_CREDENTIALS=
添加新的空值
GOOGLE_APPLICATION_CREDENTIALS=
Convert JSON file to Base64 key and copy to clipboard 将 JSON 文件转换为 Base64 密钥并复制到剪贴板
openssl base64 < /Users/{username}/Desktop/service-account.json | tr -d '\\n' | pbcopy
paste to variable so you will have something like GOOGLE_APPLICATION_CREDENTIALS=faGdfdSytDsdcDg...
粘贴到变量,这样你就会有类似
GOOGLE_APPLICATION_CREDENTIALS=faGdfdSytDsdcDg...
Authenticating GCP in Next.js 在 Next.js 中验证 GCP
Install @google-cloud/secret-manager npm i @google-cloud/secret-manager
安装 @google-cloud/secret-manager
npm i @google-cloud/secret-manager
const { SecretManagerServiceClient } = require("@google-cloud/secret-manager"); // parse your base 64 env variable to a JSON object const credentials = JSON.parse( Buffer.from( process.env.GOOGLE_APPLICATION_CREDENTIALS, "base64" ).toString() ); const projectId = "GCP-Project-Name"; // set up credentials config const config = { projectId, credentials, }; // init secret manager with credentials const client = new SecretManagerServiceClient(config); const secretId = "instagram-token"; // Access the secret. const [accessResponse] = await client.accessSecretVersion({ name: secretName, }); const instaToken = accessResponse.payload.data.toString("utf8"); // do whatever with your insta token!!!
Add GOOGLE_APPLICATION_CREDENTIALS and key to vercel when deploying.部署时将 GOOGLE_APPLICATION_CREDENTIALS 和 key 添加到 vercel。
Done!完毕! I might make a video tutorial on this as there's not much out there, let me know if that would be helpful :)
我可能会制作一个关于此的视频教程,因为那里没有太多,让我知道这是否有帮助:)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.