wordpress - REST API 身份验证错误:WooCommerce
问题描述
现在一直试图从 WooCommerce REST API 获取产品,我的大脑正在流血:'(我遵循了关于woocommerce和github/woocommerce的所有说明,但我一生都无法通过基本身份验证在 Postman 中获得任何东西:
但是当我选择Auth 1.0 - 我得到所有产品:
但是,如果我将Auth 1.0生成的 URL 放入我的浏览器中:
.. Authentication over HTTP(此处)下的说明描述了当我在 Postman 中选择Auth 1.0时在 URL 中自动生成的参数- 但是我将如何在我的 React 组件中生成这些参数?
const APP_URL = 'http://0.0.0.0:80'
const CONSUMER_KEY = 'ck_xxxx'
const CONSUMER_SECRET = 'cs_xxxx'
const PRODUCT_URL = `${APP_URL}/wp-json/wc/v2/products?consumer_key=${CONSUMER_KEY}&consumer_secret=${CONSUMER_SECRET}`
fetch(PRODUCT_URL).then(res => {
if(res.status === 200){
return json
} else {
console.log("ERROR RESPONSE STATUS: " + status);
}
}).then( json => {
console.log(json)
})
})
非常感谢所有输入!
解决方案
我认为这个问题可以通过下面使用“拦截器”概念的代码来解决......
import {
Injectable,
// Injector
} from '@angular/core';
import {
HttpRequest,
HttpHandler,
HttpEvent,
HttpInterceptor,
HttpErrorResponse
} from '@angular/common/http';
// import { Router } from '@angular/router';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/catch';
import 'rxjs/add/observable/throw';
// import { AuthService } from './auth.service';
import { config } from '../config/config';
@Injectable()
export class AppInterceptor implements HttpInterceptor {
constructor(
// private injector: Injector,
// private router: Router
) { }
private includeWooAuth(url) {
const wooAuth = `consumer_key=${config.consumerKey}&consumer_secret=${config.secretKey}`;
const hasQuery = url.includes('?');
let return_url = '';
if (hasQuery) {
return_url = wooAuth;
} else {
return_url = '?' + wooAuth;
}
return return_url;
}
intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
// const auth = this.injector.get(AuthService);
const authRequest = request.clone({
setHeaders: {
// Authorization: `Bearer ${auth.getToken()}`
},
url: `${config.basePath}/${request.url}${this.includeWooAuth(request.url)}`
});
return next.handle(authRequest)
.catch(err => {
if (err instanceof HttpErrorResponse && err.status === 0) {
console.log('Check Your Internet Connection And Try again Later');
} else if (err instanceof HttpErrorResponse && err.status === 401) {
// auth.setToken(null);
// this.router.navigate(['/', 'login']);
}
return Observable.throw(err);
});
}
}
此代码将保存在http.interceptor.ts中。显然,您应该将 woocommerce API 的消费者密钥和其他详细信息初始化为一个常量变量。之后,您创建一个服务来显示产品列表,如下所示:
retriveProducts(query: ProductQuery = {}): Observable<RetriveProductsResponse> {
return this.httpClient.get(`products`, {params: this.wooHelper.includeQuery(query), observe: 'response'})
.pipe(
map(value => this.wooHelper.includeResponseHeader(value)),
catchError(err => this.wooHelper.handleError(err)));
}
并将此服务调用到product.ts文件,如下所示:
getProducts() {
this.woocommerceProductsService.retriveProducts()
.subscribe(productResponse => {
this.products = productResponse.products;
}, error => this.errorMessage = <any>error);
}
我已经在我的项目中使用了上面的这些代码。我想它会对你有所帮助。
推荐阅读
- c# - 是否可以将 listBox 选定的项目从一个 wpf 页面传递到另一个页面
- php - SMARTY:如何从数据库 foreach 循环中填充新数组
- javascript - 为什么使用 jsPDF justify for text 保持其他文本的字间距?
- javascript - ngFor 值(数字)的 Angular 2 摘要
- ios - 遍历 Swift 4 中的可选对象
- axapta - 如何获取 dbo.CUSTTRANS 中一行的位置?
- sql - sql队列分析
- python - 从装饰函数设置可调用上下文管理器装饰器中的属性
- c - openmp 串行比并行快
- android - 如何在 Flutter App 中接听电话?