最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Implement oAuth 1.0 in ky + react-query - Stack Overflow

programmeradmin0浏览0评论

I want to implement oAuth 1.0 in ky, here is my code(s):

export const wooApiV3 = ky.extend({
  headers: {
    Accept: "application/json",
  },
  hooks: {
    beforeRequest: [
      (request, options) => {
        const extendedOptions = options as ExtendedOptions;
        const url = new URL(request.url, extendedOptions.prefixUrl);
        const existingParams = new URLSearchParams(url.searchParams);
        
        const oauthParams: Record<string, string> = {
          oauth_consumer_key: process.env.CUSTOMER_KEY!,
          oauth_nonce: generateNonce(),
          oauth_signature_method: 'HMAC-SHA1',
          oauth_timestamp: generateTimestamp().toString(),
          oauth_version: '1.0',
        };
        for (const [key, value] of Object.entries(oauthParams)) {
          existingParams.set(key, value);
        }
        const signature = generateOAuthSignature(
          request.method || 'GET',
          url.origin + url.pathname,
          Object.fromEntries(existingParams),
          process.env.CUSTOMER_SECRET!
        );
        existingParams.set('oauth_signature', signature);
        extendedOptions.searchParams = existingParams;
      },
    ]
  },
  prefixUrl: wooPrefixUrl,
});

Helpers function(s):

import CryptoJS from 'crypto-js';

export const generateNonce = (): string => Math.random().toString(36).slice(2, 15);
export const generateTimestamp = (): number => Math.floor(Date.now() / 1000);

export const generateOAuthSignature = (
  method: string,
  url: string,
  params: Record<string, string>,
  consumerSecret: string
): string => {
  const sortedParams = Object.keys(params)
    .sort()
    .map(
      key =>
        `${encodeURIComponent(key)}=${encodeURIComponent(params[key])}`
    )
    .join('&');
  const baseString = [
    method.toUpperCase(),
    encodeURIComponent(url),
    encodeURIComponent(sortedParams),
  ].join('&');

  const signingKey = `${encodeURIComponent(consumerSecret)}&`;
  const hash = CryptoJS.HmacSHA1(baseString, signingKey);
  return CryptoJS.enc.Base64.stringify(hash);
};

Same functionality from Postman is working, but in combination with @tanstack/react-query data is always undefined.

import { wooApiV3 } from "@/services/instance";
import { productSchema } from "./schema";

export const ProductServices = {
  fetchAll: async () => {
    const response = await wooApiV3.get(`products`).json();
    return productSchema.parse(response);
  },
};

Woo response without oAuth:

{
    "code": "woocommerce_rest_cannot_view",
    "message": "Sorry, you cannot list resources.",
    "data": {
        "status": 401
    }
}

Woo response with oAuth:

[] - array of products, status code 200

What is the problem here? Have a nice day!

发布评论

评论列表(0)

  1. 暂无评论