首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >制作一个Cloudflare工作人员,通过我的Twitter开发者API转发。无法让CryptoJS.HmacSHA1为获取请求创建签名

制作一个Cloudflare工作人员,通过我的Twitter开发者API转发。无法让CryptoJS.HmacSHA1为获取请求创建签名
EN

Stack Overflow用户
提问于 2022-04-24 20:03:22
回答 1查看 237关注 0票数 0

我正在制作一个Cloudflare工作程序,每当我向工作人员发出空白GET请求时,它就会从我的Twitter开发人员API中转发。起初,您可能会认为“这很容易使用npm的twitter-api-v2”,但这是行不通的,因为Cloudflare工作人员需要使用纯javascript/类型记录,并且不能依赖任何外部模块。所以我尝试用下面的代码来做这件事。

index.ts

代码语言:javascript
复制
import { handleRequest } from './handler'

addEventListener('fetch', (event) => {
  event.respondWith(handleRequest(event.request))
})

handler.ts

代码语言:javascript
复制
import * as CryptoJS from 'crypto-js'

function getRandomString(length) {
    const randomChars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
    let result = '';
    for ( let i = 0; i < length; i++ ) {
        result += randomChars.charAt(Math.floor(Math.random() * randomChars.length));
    }
    return result;
}
function hexToBase64(str) {
  const stringChange = str.toString()
  return btoa(String.fromCharCode.apply(null, stringChange.replace(/\r|\n/g, "").replace(/([\da-fA-F]{2}) ?/g, "0x$1 ").replace(/ +$/, "").split(" ")));
}
async function postTweet() {

  const oauth_consumer_key = '<OAUTH CONSUMER KEY HERE>'
  const oauth_consumer_secret = '<OAUTH CONSUMER SECRET HERE>'
  const oauth_token = '<OAUTH TOKEN HERE>'
  const oauth_token_secret = '<OAUTH TOKEN SECRET HERE>'
  const oauth_signature_method = 'HMAC-SHA1'
  const oauth_version = '1.0'
  const oauth_nonce = getRandomString(42)
  const oauth_timestamp = Math.round(Date.now() / 1000)

  const endpointURL = 'https://api.twitter.com/1.1/statuses/update.json?status';
  
  const tweetData = {
    status: 'I am Tweeting this now'
  }
  
  const encodedTweet = encodeURIComponent(tweetData.status).replace(/!/g, '%21')

  const params = 'POST&' + encodeURIComponent('https://api.twitter.com/1.1/statuses/update.json') + '&include_entities' + encodeURIComponent('=true&') + 'oauth_consumer_key' + encodeURIComponent('='+oauth_consumer_key+'&') + 'oauth_nonce' + encodeURIComponent('='+oauth_nonce+'&') + 'oauth_signature_method' + encodeURIComponent('='+oauth_signature_method+'&') + 'oauth_timestamp' + encodeURIComponent('='+oauth_timestamp+'&') + 'oauth_token' + encodeURIComponent('='+oauth_token+'&') + 'oauth_version' + encodeURIComponent('='+oauth_version+'&') + 'status' + encodeURIComponent('='+encodedTweet)
  const signingKey = encodeURIComponent(oauth_consumer_secret) + '&' + encodeURIComponent(oauth_token_secret)
  //////HMAC-SHA1 Functionality//////
  const hexStr = CryptoJS.HmacSHA1(params, signingKey)
  console.log(hexStr)
  const signature = hexToBase64(hexStr)
  const oauth_signature = encodeURIComponent(signature)
  fetch('https://api.twitter.com/1.1/statuses/update.json', {
    method: 'post',
    headers: {
      'Authorization': 'OAuth oauth_consumer_key="'+oauth_consumer_key+'",oauth_token="'+oauth_token+'",oauth_signature_method="HMAC-SHA1",oauth_timestamp="'+oauth_timestamp+'",oauth_nonce="'+oauth_nonce+'",oauth_version="1.0",oauth_signature="'+oauth_signature+'"',
      'Content-Type': 'application/x-www-form-urlencoded' // 'application/json'
    },
    body: JSON.stringify(tweetData)
  }).then(function(response) {
    return response.json();
  }).then(function(data) {
    console.log('result:', data);
  });
  console.log('postTweet ran')
}

export async function handleRequest(request: Request): Promise<Response> {
  await postTweet()
  return new Response(`Hello worker! this is a ${request.method} request`, {
    headers: { 'content-type': 'text/plain' },
  });
}

但是,当我使用wrangler dev运行代码,然后用Postman对http://127.0.0.1:8787执行空白GET请求时,我在终端中得到了如下信息:

代码语言:javascript
复制
<myusername>@<mycomputername> <myappname> % wrangler dev
  Listening on http://127.0.0.1:8787
  Detected changes...
  Ignoring stale first change
[2022-04-24 15:42:37] GET <myappname>.<myworkername>.workers.dev/ HTTP/1.1 200 OK
{unknown object}
postTweet ran
^C
<myusername>@<mycomputername> <myappname> %

我注意到问题可能始于const hexStr = CryptoJS.HmacSHA1(params, signingKey)失败这一事实。在输出中可以看到console.log(hexStr)正在打印{unknown object}

我做错了什么?我怎样才能让我的Cloudflare工作人员根据要求发短信呢?

EN

回答 1

Stack Overflow用户

发布于 2022-05-13 13:28:43

不能工作的

,因为Cloudflare工作人员需要在纯javascript/typescript中,并且不能依赖任何外部模块

不是这样的,Node.js支持是最近宣布的:https://blog.cloudflare.com/node-js-support-cloudflare-workers/

还有一个与工人一起工作的库列表(来自npm):https://workers.cloudflare.com/works

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/71991940

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档