gpt4 book ai didi

rest - 角度 6 woocommerce REST 身份验证

转载 作者:行者123 更新时间:2023-12-02 20:17:02 25 4
gpt4 key购买 nike

我正在尝试将我的 woocommerce rest api 与角度 6 连接。

export class RestService {
_urlwc = 'http://127.0.0.1/wp-json/wc/v2/products'; //woocommerce
_urlwp = 'http://127.0.0.1/wp-json/wp/v2/posts'; //wordpress

constructor(private http: HttpClient) { }

getPosts() {
return this.http.get(this._urlwp);
}
getProducts() {

let headers = new HttpHeaders();
headers = headers.append("Authorization", "Basic " + btoa("ck_9c9293adb7d3fb19f60a1dccd0cb5d4a251e9e03:cs_77a221d4655d5fb8fc2a5c85b7259c2364d59a8c"));
headers = headers.append("Content-Type", "application/x-www-form-urlencoded");
return this.http.get(this._urlwc, { headers: headers });

}
}

只有 Wordpress get 方法即使在未经授权的情况下也能正常工作,但 Woocommerce 给我未授权的 401 代码!! [我已经创建了消费者 key 和 secret ]

然后我尝试使用具有不同身份验证的 Postman,例如

  • 无授权
  • 基本授权
  • OAuth 2.0

OAuth 1.0 与 postman 配合良好。
我如何使用 woocommerce api 实现身份验证 angular 6?
或者我如何像 postman 一样在 Angular 6 中使用 OAuth 1.0?
Postman Screenshoot

最佳答案

使用以下方法创建服务:

ng g s services/woocommerce

这将在目录 src/app/services/woocommerce 下创建文件 woocommerce.service.spec.tswoocommerce.service.ts >

woocommerce.service.ts中添加如下代码(注意:需要安装crypto-js : https://github.com/brix/crypto-js):

import { Injectable } from '@angular/core';
import hmacSHA1 from 'crypto-js/hmac-sha1';
import Base64 from 'crypto-js/enc-base64';

@Injectable({
providedIn: 'root'
})
export class WoocommerceService {
nonce: string = ''
currentTimestamp: number = 0
customer_key: string = 'ck_2e777dd6fdca2df7b19f26dcf58e2988c5ed1f6d';
customer_secret: string = 'cs_0176cb5343903fbaebdd584c3c947ff034ecab90';
constructor() { }

authenticateApi(method,url,params) {
var possible = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
this.nonce ='';
for(var i = 0; i < 6; i++) {
this.nonce += possible.charAt(Math.floor(Math.random() * possible.length));
}
this.currentTimestamp = Math.floor(new Date().getTime() / 1000);

let authParam:object ={
oauth_consumer_key : this.customer_key,
oauth_nonce : this.nonce,
oauth_signature_method : 'HMAC-SHA1',
oauth_timestamp : this.currentTimestamp,
oauth_version : '1.0',
}
let parameters = Object.assign({}, authParam, params);
let signatureStr:string = '';
Object.keys(parameters).sort().forEach(function(key) {
if(signatureStr == '')
signatureStr += key+'='+parameters[key];
else
signatureStr += '&'+key+'='+parameters[key];
});
let paramStr:string = '';
Object.keys(params).sort().forEach(function(key) {

paramStr += '&'+key+'='+parameters[key];
});
return url+'?oauth_consumer_key='+this.customer_key+'&oauth_nonce='+this.nonce+'&oauth_signature_method=HMAC-SHA1&oauth_timestamp='+this.currentTimestamp+'&oauth_version=1.0&oauth_signature='+Base64.stringify(hmacSHA1(method+'&'+encodeURIComponent(url)+'&'+encodeURIComponent(signatureStr),this.customer_secret+'&'))+paramStr;

}
}


authenticateApi 函数构建并返回用于 woocommerce api 调用的 url。代码是不言自明的,我不会解释它,但为了以防万一引用 this link 关于如何构建 url。它实际上更多地是关于构建 auth-signature 参数。

以下是我们将如何在任何组件中使用此服务,例如我们导入此服务的产品组件:

从 '../services/wordpress/wordpress.service' 导入 { WordpressService };

同时导入 Router 和 ActivatedRoute 如下:

import { Router, ActivatedRoute } from '@angular/router';

我们希望它获取 url 的 slug 部分。为此,请按如下方式在构造函数中传递参数:

constructor(private woocommerce: WoocommerceService, private http: HttpClient, private router: Router, private route: ActivatedRoute) {
this.route.params.subscribe( params => this.productSlug = params.slug )
}


在这里,我们将使用 woocommerce 服务。我们创建了 httpclient 来向 woocommerce api 发出 http 请求,并激活了获取产品 slug 的路由。 params.slug 指的是角度路由中使用的变量,即

{
path: 'product/:slug',
component: ProductComponent
},

您还需要在组件中创建 productSlug 变量来保存 slug:

productSlug: string;

在 ng init 上,调用服务:

ngOnInit() {     
this.params = {slug:this.productSlug}
let producturl:string = this.woocommerce.authenticateApi('GET','http://localhost/shop/wp-json/wc/v2/products',this.params);
this.http.get(producturl).subscribe((wc_data:any) => {
this.product = wc_data[0];
this.params = {}
let productvariationurl:string = this.woocommerce.authenticateApi('GET','http://localhost/shop/wp-json/wc/v2/products/'+this.product.id+'/variations',this.params);
this.http.get(productvariationurl).subscribe((wc_pv_data:any) => {
this.productVariations = wc_pv_data;
});
this.params = {include:this.product.related_ids}
let productrelatedurl:string = this.woocommerce.authenticateApi('GET','http://localhost/shop/wp-json/wc/v2/products',this.params);
this.http.get(productrelatedurl).subscribe((wc_r_data:any) => {
this.productRelated = wc_r_data;
});
});
}


如您所见,我在这里获得了所有带有特定 slug 的产品。然后获取该产品的所有变体,并获取相关产品这是产品组件的完整代码:

import { Component, OnInit } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { WoocommerceService } from '../services/woocommerce/woocommerce.service';
import { Router, ActivatedRoute } from '@angular/router';
@Component({
selector: 'app-product',
templateUrl: './product.component.html',
styleUrls: ['./product.component.scss']
})
export class ProductComponent implements OnInit {

product: any;
productVariations: any;
selectedvariation: number;
selectedquantity: number;
productRelated: any;
productSlug: number;
variationSelected: string;
params: object = {}
constructor( private woocommerce: WoocommerceService, private http: HttpClient, private router: Router, private route: ActivatedRoute) {
this.route.params.subscribe( params => this.productSlug = params.slug )
}

ngOnInit() {
this.params = {slug:this.productSlug}
let producturl:string = this.woocommerce.authenticateApi('GET','http://localhost/shop/wp-json/wc/v2/products',this.params);
this.http.get(producturl).subscribe((wc_data:any) => {
this.product = wc_data[0];
this.params = {}
let productvariationurl:string = this.woocommerce.authenticateApi('GET','http://localhost/shop/wp-json/wc/v2/products/'+this.product.id+'/variations',this.params);
this.http.get(productvariationurl).subscribe((wc_pv_data:any) => {
this.productVariations = wc_pv_data;
});
this.params = {include:this.product.related_ids}
let productrelatedurl:string = this.woocommerce.authenticateApi('GET','http://localhost/shop/wp-json/wc/v2/products',this.params);
this.http.get(productrelatedurl).subscribe((wc_r_data:any) => {
this.productRelated = wc_r_data;
});
});
}
}

关于rest - 角度 6 woocommerce REST 身份验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52177791/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com