Create a service using:
ng g s services/woocommerce
This will create files woocommerce.service.spec.ts and woocommerce.service.ts under the directory src/app/services/woocommerce
In the woocommerce.service.ts, add the following code (note: you need to install 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;
}
}
The authenticateApi function builds and returns the url to be used for the woocommerce api call. The code is self explanatory, and I will not get into explaining it, but just in case refer to this link on how the url is built. It's actually more about building the auth-signature parameter.
Here is how we will use this service in any component say for example a product component we import this service:
import { WordpressService } from '../services/wordpress/wordpress.service';
Also import Router and ActivatedRoute as follows:
import { Router, ActivatedRoute } from '@angular/router';
We want this to get the slug part of the url. To do that, pass parameters in the constructor as follows:
constructor(private woocommerce: WoocommerceService, private http: HttpClient, private router: Router, private route: ActivatedRoute) {
this.route.params.subscribe( params => this.productSlug = params.slug )
}
Here we are going to use the woocommerce service . We created httpclient for making http request to the woocommerce api, and activated route to get product slug. The params.slug refers to the variable used in angular routing routes i.e.
{
path: 'product/:slug',
component: ProductComponent
},
You also need to create productSlug variable in the component to hold the slug:
productSlug: string;
On ng init, call the service:
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;
});
});
}
As you see, here I am getting all product with a particular slug. Then getting all variations of that product, and getting related products
here is the full code of product component:
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;
});
});
}
}