使用 Google Apps 脚本在 Blogger 中创建帖子

2 blogger urlfetch google-apps-script

到目前为止,我还没有找到一个好的代码来使用 Google 脚本在 Blogger 中创建帖子。

\n

在 API 控制台中,我获得了以下凭据:

\n
    \n
  • 客户ID
  • \n
  • 客户秘密
  • \n
  • API密钥
  • \n
\n

此外,库已添加到 Google 脚本中:

\n
    \n
  • OAuth2 库 \xe2\x86\x92 MswhXl8fVhTFUH_Q3UOJbXvxhMjh3Sh48
  • \n
  • 博主库\xe2\x86\x92 M2CuWgtxF1cPLI9mdRG5_9sh00DPSBbB3
  • \n
\n

我尝试了一些代码,这是当前的代码:

\n
function create_blog_post() {\n  var payload =\n      {\n        "kind": "blogger#post",\n        "blog": {\n          "id": "12345........" // YOUR_BLOG_ID\n        },\n        "title": "New post",\n        "content": "With content..."\n      };\nvar headers = {\n    "Authorization": "Bearer " + getService().getAccessToken(), // \xe2\x86\x90 THIS IS WRONG\n    "X-HTTP-Method-Override": "PATCH"\n  };\n  var options =\n      {\n        "method" : "post",\n        "headers" : { "Authorization" : "Bearer" + getService().getAccessToken()},\n        "contentType" : "application/json",\n        "payload" : '{ "kind": "blogger#post", "blog": { "id": "12345........" }, "title": "New post", "content": "With content..." }'\n      };\n  try {\n    var result = UrlFetchApp.fetch(\n      "https://www.googleapis.com/blogger/v3/blogs/12345......../posts", options);\n    Logger.log(result);\n    } catch (e) {Logger.log(e);}\n}\n
Run Code Online (Sandbox Code Playgroud)\n

请帮我用最简单的代码解决这个问题。

\n

The*_*ter 6

必读:

\n\n

问题:

\n
    \n
  • 在同步服务器端使用异步客户端浏览器示例。
  • \n
\n

解决方案:

\n
    \n
  • 可以使用 Google Apps 脚本访问 Blogger apiUrlFetchApp
  • \n
  • 可以使用以下提供的 oauth 令牌绕过完整的 OAuth 流程ScriptApp
  • \n
  • 在 appsscript.json 清单文件中包含范围。
  • \n
  • 切换到标准 GCP 并启用 blogger api
  • \n
\n

片段:

\n
function createBlogPost(){\n  var postUrl = "https://www.googleapis.com/blogger/v3/blogs/blogId/posts";\n  var blogId = /*"YOUR_BLOG_ID"*/;\n  postUrl = postUrl.replace("blogId",blogId);\n  var options = {\n    method:"post",\n    contentType:"application/json",\n    headers: { Authorization: "Bearer "+ ScriptApp.getOAuthToken()},\n    muteHttpExceptions: true,\n    payload: JSON.stringify({\n      title: "Hello from Apps Script!",\n      content: "This post is automatically created by Apps script"\n    })\n  }\n  var res = UrlFetchApp.fetch(postUrl, options).getContentText();\n  console.log(res);//or Logger.log(res)\n}\n
Run Code Online (Sandbox Code Playgroud)\n

清单范围:

\n
"oauthScopes": [\n  "https://www.googleapis.com/auth/blogger",\n  "https://www.googleapis.com/auth/script.external_request"\n]\n
Run Code Online (Sandbox Code Playgroud)\n