angular 6 woocommerce REST身份验证

问题描述 投票:1回答:1

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

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代码! [我创建了消费者密钥和秘密]

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

  • 没有Auth
  • 基本认证
  • OAuth 2.0

OAuth 1.0适用于邮递员。 如何使用woocommerce api实现身份验证角度6? 或者我如何在角6中像邮递员那样使用OAuth 1.0? Postman Screenshoot

rest authentication woocommerce angular6
1个回答
1
投票

使用以下方法创建服务

ng g s services/woocommerce

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

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。它实际上更多的是建立auth-signature参数。

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

import { WordpressService } from '../services/wordpress/wordpress.service';

同时导入Router和ActivatedRoute如下:

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

我们希望这可以获得网址的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;

在炎热的时候,打电话给服务:

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;            
        });         
    }); 
  }
}
© www.soinside.com 2019 - 2024. All rights reserved.