我试图连接我的woocommerce rest与角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代码!!我创造了消费者的钥匙和秘密
然后我尝试使用具有不同身份验证的邮递员,例如
OAuth 1.0适用于邮递员。
如何使用woocommerce api实现身份验证角6?
或者我怎样才能像邮递员一样使用OAuth 1.0的角度6呢?
发布于 2018-09-19 08:17:01
使用以下方法创建服务:
ng g s services/woocommerce这将在目录woocommerce.service.spec.ts和woocommerce.service.ts下创建src/app/services/woocommerce文件。
在woocommerce.service.ts中,添加以下代码(注意:您需要安装crypto: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。这段代码是不言自明的,我不会解释它,只是为了以防万一,请参考此链接是如何构建url的。它实际上更多地是关于构建auth-signature参数的。
下面是我们将如何在任何组件中使用该服务,例如,我们导入该服务的产品组件:
import { WordpressService } from '../services/wordpress/wordpress.service';
还导入路由器和ActivatedRoute,如下所示:
import { Router, ActivatedRoute } from '@angular/router';我们希望这个能让鼻涕虫部分进入url。为此,在构造函数中传递参数如下:
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请求,并启动了获取产品段塞的路由。params.slug是指角路由中使用的变量,即
{
path: 'product/:slug',
component: ProductComponent
},您还需要在组件中创建productSlug变量来保存弹格:
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;
});
});
}正如你所看到的,在这里,我用一种特殊的鼻涕虫获得所有的产品。然后获取该产品的所有变体,并在这里获取相关产品,这是产品组件的完整代码:
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;
});
});
}
}https://stackoverflow.com/questions/52177791
复制相似问题