首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >角6 woocommerce REST认证

角6 woocommerce REST认证
EN

Stack Overflow用户
提问于 2018-09-05 05:39:41
回答 1查看 2.3K关注 0票数 2

我试图连接我的woocommerce rest与角6。

代码语言:javascript
复制
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代码!!我创造了消费者的钥匙和秘密

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

  • 没有八月
  • 基本8月份
  • OAuth 2.0

OAuth 1.0适用于邮递员。

如何使用woocommerce api实现身份验证角6?

或者我怎样才能像邮递员一样使用OAuth 1.0的角度6呢?

邮递员截图

EN

回答 1

Stack Overflow用户

发布于 2018-09-19 08:17:01

使用以下方法创建服务:

代码语言:javascript
复制
ng g s services/woocommerce

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

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

代码语言:javascript
复制
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,如下所示:

代码语言:javascript
复制
import { Router, ActivatedRoute } from '@angular/router';

我们希望这个能让鼻涕虫部分进入url。为此,在构造函数中传递参数如下:

代码语言:javascript
复制
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是指角路由中使用的变量,即

代码语言:javascript
复制
{
    path: 'product/:slug',
    component: ProductComponent
},

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

代码语言:javascript
复制
productSlug: string;

在ng init上,调用服务:

代码语言:javascript
复制
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;            
        });         
    }); 
 }

正如你所看到的,在这里,我用一种特殊的鼻涕虫获得所有的产品。然后获取该产品的所有变体,并在这里获取相关产品,这是产品组件的完整代码:

代码语言:javascript
复制
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;            
        });         
    }); 
  }
}
票数 5
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/52177791

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档