Ionic 3 & Woocommerce - retrieve/create customer using woocommerce customer api? - wordpress

I'm completely new to woocommerce. I want to create a sign up page for shop app, so I'm trying to check if the email id entered by a customer while signing up is already exists or not, if not then create his account or else prompt the error "Email id already exists". I got the code from https://woocommerce.github.io/woocommerce-rest-api-docs/#retrieve-a-customer but it is giving me an error while retrieving customer "No route was found matching the URL and request method".
here is my signup.ts code:
import * as WC from 'woocommerce-api';
WooCommerce: any;
newUser: any = {};
constructor()
{
this.WooCommerce = WC({
url: "http://localhost:1432/wordpress/",
consumerKey: "ck_*************************************",
consumerSecret: "cs_*************************************",
wpAPI: true, // Enable the WP REST API integration
queryStringAuth: true,
verifySsl: true,
version: 'wc/v2' // WooCommerce WP REST API version
});
this.newUser.billing_address = {};
this.newUser.shipping_address = {};
}
checkEmail()
{
let validEmail = false;
let reg = /^(([^<>()\[\]\.,;:\s#\"]+(\.[^<>()\[\]\.,;:\s#\"]+)*)|(\".+\"))#(([^<>()[\]\.,;:\s#\"]+\.)+[^<>()[\]\.,;:\s#\"]{2,})$/i;
if(reg.test(this.newUser.email))
{
this.WooCommerce.getAsync('customers/email/'+this.newUser.email)
.then((data) => {
let res = (JSON.parse(data.body));
console.log("data", res);
if(res.errors)
{
validEmail = true;
this.toastCtrl.create({
message: "Congratulations. Email is good to go!",
duration: 2000
}).present();
}
else
{
validEmail = false;
this.toastCtrl.create({
message: "Email already registered, please check.",
showCloseButton: true
}).present();
}
console.log(validEmail);
})
}
else
{
validEmail = false;
this.toastCtrl.create({
message: "Invalid Email. Please check.",
showCloseButton: true
}).present();
console.log(validEmail);
}
}
signup()
{
let customerData = {
customer : {}
}
customerData.customer = {
"email": this.newUser.email,
"first_name": this.newUser.first_name,
"last_name": this.newUser.last_name,
"username": this.newUser.username,
"password": this.newUser.password,
"billing_address": {
"first_name": this.newUser.first_name,
"last_name": this.newUser.last_name,
"company": "",
"address_1": this.newUser.billing_address.address_1,
"address_2": this.newUser.billing_address.address_2,
"city": this.newUser.billing_address.city,
"state": this.newUser.billing_address.state,
"postcode": this.newUser.billing_address.postcode,
"country": this.newUser.billing_address.country,
"email": this.newUser.email,
"phone": this.newUser.billing_address.phone,
},
"shipping_address": {
"first_name": this.newUser.first_name,
"last_name": this.newUser.last_name,
"company": "",
"address_1": this.newUser.shipping_address.address_1,
"address_2": this.newUser.shipping_address.address_2,
"city": this.newUser.shipping_address.city,
"state": this.newUser.shipping_address.state,
"postcode": this.newUser.shipping_address.postcode,
"country": this.newUser.shipping_address.country
}
}
if(this.billing_shipping_same)
{
this.newUser.shipping_address = this.newUser.shipping_address;
}
this.WooCommerce.postAsync('customers',customerData).then((data) =>{
console.log(JSON.parse(data.body));
});
}
Error i'm getting while checking email:

I think you are the little bit confused with the WooCommerce REST API Route.
You trying this route /wp-json/wc/v2/customers/<id> and you are passing the id as customer email id. Correct?
This is not which where you can pass the id as customer email id. for id you have to pass the customer id.
Something like this /wp-json/wc/v2/customers/1
But if you are trying to get customer details by the email id then you can use this route.
/wp-json/wc/v2/customers?email=ajay#xyz.com
This route returns the data of the customer who are assigned with this email id ajay#xyz.com.
import * as WC from 'woocommerce-api';
WooCommerce: any;
newUser: any = {};
constructor()
{
this.WooCommerce = WC({
url: "http://localhost:1432/wordpress/",
consumerKey: "ck_*************************************",
consumerSecret: "cs_*************************************",
wpAPI: true, // Enable the WP REST API integration
queryStringAuth: true,
verifySsl: true,
version: 'wc/v2' // WooCommerce WP REST API version
});
this.newUser.billing_address = {};
this.newUser.shipping_address = {};
}
checkEmail()
{
let validEmail = false;
let reg = /^(([^<>()\[\]\.,;:\s#\"]+(\.[^<>()\[\]\.,;:\s#\"]+)*)|(\".+\"))#(([^<>()[\]\.,;:\s#\"]+\.)+[^<>()[\]\.,;:\s#\"]{2,})$/i;
if(reg.test(this.newUser.email))
{
this.WooCommerce.getAsync('customers?email='+this.newUser.email)
.then((data) => {
let res = (JSON.parse(data.body));
console.log("data", res);
if(res.errors)
{
validEmail = true;
this.toastCtrl.create({
message: "Congratulations. Email is good to go!",
duration: 2000
}).present();
}
else
{
validEmail = false;
this.toastCtrl.create({
message: "Email already registered, please check.",
showCloseButton: true
}).present();
}
console.log(validEmail);
})
}
else
{
validEmail = false;
this.toastCtrl.create({
message: "Invalid Email. Please check.",
showCloseButton: true
}).present();
console.log(validEmail);
}
}
signup()
{
let customerData = {
customer : {}
}
customerData.customer = {
"email": this.newUser.email,
"first_name": this.newUser.first_name,
"last_name": this.newUser.last_name,
"username": this.newUser.username,
"password": this.newUser.password,
"billing_address": {
"first_name": this.newUser.first_name,
"last_name": this.newUser.last_name,
"company": "",
"address_1": this.newUser.billing_address.address_1,
"address_2": this.newUser.billing_address.address_2,
"city": this.newUser.billing_address.city,
"state": this.newUser.billing_address.state,
"postcode": this.newUser.billing_address.postcode,
"country": this.newUser.billing_address.country,
"email": this.newUser.email,
"phone": this.newUser.billing_address.phone,
},
"shipping_address": {
"first_name": this.newUser.first_name,
"last_name": this.newUser.last_name,
"company": "",
"address_1": this.newUser.shipping_address.address_1,
"address_2": this.newUser.shipping_address.address_2,
"city": this.newUser.shipping_address.city,
"state": this.newUser.shipping_address.state,
"postcode": this.newUser.shipping_address.postcode,
"country": this.newUser.shipping_address.country
}
}
if(this.billing_shipping_same)
{
this.newUser.shipping_address = this.newUser.shipping_address;
}
this.WooCommerce.postAsync('customers',customerData).then((data) =>{
console.log(JSON.parse(data.body));
});
}
I have modified the route in your request you can check and let me know here i you are facing any issue.

try this
WooCommerceResult:any=[];
WooCommerce.getAsync('customers/email'+this.newUser.email).then((result) => {
console.log(result.toJSON().body);
this.WooCommerceResult=result.toJSON().body;
//return Promise.resolve(JSON.parse(result.toJSON().body));
// return JSON.parse(result.toJSON().body);
});
Bind WooCommerceResult in a view

remove extra parameters from this
this.WooCommerce = WC({
url: "http://localhost:1432/wordpress/",
consumerKey: "ck_*************************************",
consumerSecret: "cs_*************************************",
wpAPI: true, // Enable the WP REST API integration
queryStringAuth: true,
verifySsl: true,
version: 'wc/v2' // WooCommerce WP REST API version
});
to::
this.WooCommerce = WC({
url: "http://localhost:1432/wordpress/",
consumerKey: "ck_*************************************",
consumerSecret: "cs_*************************************",
});

Related

Flutter Stripe how to set user's billing address and submit it along to create a paymentmethod?

I am having some trouble setting and submitting to the Stripe server my app's customer's billing address for the Card they chose to pay with.
The code below is what I have tried but failed:
Future<PaymentMethod> createPaymentMethod(BuildContext context,
Map<String, String> billingAddress, String name, String phoneNumber) async {
StripePayment.setStripeAccount(null);
// Here to add the credit Card
PaymentMethod paymentMethod = PaymentMethod();
print('This is in paymentMethod: ${paymentMethod.toJson()}');
paymentMethod = await StripePayment.paymentRequestWithCardForm(
CardFormPaymentRequest(),
).then((PaymentMethod paymentMethod) {
paymentMethod.billingDetails = BillingDetails(
address: BillingAddress(
line1: billingAddress['Address'],
city: billingAddress['City'],
state: billingAddress['State'],
postalCode: billingAddress['Zip Code']),
name: name,
phone: phoneNumber);
return paymentMethod;
}).catchError((e) {
print('Error Card: ${e.toString()}');
});
paymentMethod != null
? print('Success')
: AwesomeDialog(
context: context,
title: 'Uh oh! A wild error has appeared!',
desc:
'Seems like we cant process this card. Please double check your input or try a different card',
animType: AnimType.SCALE,
dialogType: DialogType.WARNING,
btnOkOnPress: () {})
.show();
return paymentMethod;
}
The payment method and payment Intent are all successful but in the Response Body from Stripe, I am still only getting:
"billing_details": {
"address": {
"city": null,
"country": "US",
"line1": null,
"line2": null,
"postal_code": null,
"state": null
},
"email": null,
"name": null,
"phone": null
},
On my Response POST body I am only having:
{
"amount": "5178",
"currency": "usd",
"payment_method": "some_payment_method_here",
"confirm": "true",
"confirmation_method": "manual",
"off_session": "false"
}
How should I set my code such that I have finally have the user's billing address in the Response Body so that I can have:
"billing_details": {
"address": {
"city": "Sesame Town",
"country": "US",
"line1": "123 Sesame Street",
"line2": null,
"postal_code": 12345,
"state": "Sesame State"
},
"email": "mayorOfSesameStreet#email.com",
"name": "Mayor Sesame",
"phone": 8889990000
},
Thanks in advance
I’m assuming you’re using the stripe_payment package (https://pub.dev/packages/stripe_payment)? If you already have the customer’s billing address, you can pre-fill it by setting CardFormPaymentRequest.prefilledInformation.billingAddress (https://pub.dev/documentation/stripe_payment/latest/stripe_payment/CardFormPaymentRequest-class.html). Here’s how it would look in your code:
PaymentMethod paymentMethod = PaymentMethod();
CardFormPaymentRequest req = CardFormPaymentRequest(
prefilledInformation: PrefilledInformation (
billingAddress: BillingAddress(
line1: billingAddress['Address'],
city: billingAddress['City'],
state: billingAddress['State'],
postalCode: billingAddress['Zip Code'],
name: name)));
paymentMethod = await StripePayment.paymentRequestWithCardForm(req).then((PaymentMethod paymentMethod) {
return paymentMethod;
}).catchError((e) {
print('Error Card: ${e.toString()}');
});

Where can I get the SourceToken for the customer creation in Stripe?

Where can I get the SourceToken for the customer creation in Stripe?
Here is the example of the code which uses the SourceToken:
if (Request.Form["stripeToken"] != null) {
var customers = new CustomerService();
var charges = new ChargeService();
var customer = customers.Create(new CustomerCreateOptions {
Email = Request.Form["stripeEmail"],
SourceToken = Request.Form["stripeToken"]
});
var charge = charges.Create(new ChargeCreateOptions {
Amount = 500,
Description = "Sample Charge",
Currency = "usd",
CustomerId = customer.Id
});
Console.WriteLine(charge);
}
What is SourceToken out of this json?
{
"id": "tok_1EL43MKfPgrABB02rh7IGG7l",
"object": "token",
"card": {
"id": "card_1EL43MKfPgrABB02yFgReMXc",
"object": "card",
"address_city": null,
"address_country": null,
"address_line1": null,
"address_line1_check": null,
"address_line2": null,
"address_state": null,
"address_zip": null,
"address_zip_check": null,
"brand": "Visa",
"country": "US",
"cvc_check": "pass",
"dynamic_last4": null,
"exp_month": 12,
"exp_year": 2020,
"funding": "credit",
"last4": "4242",
"metadata": {},
"name": "foo#gmail.com",
"tokenization_method": null
},
"client_ip": "194.44.142.6",
"created": 1554278556,
"email": "foo#gmail.com",
"livemode": false,
"type": "card",
"used": false
}
Here is how I got the json:
var stripe = Stripe('pk_test_ob6s7KZxZU1mouJbbsuFBjEe');
var handler = StripeCheckout.configure({
key: 'pk_test_ob6s7KZxZU1mouJbbsuFBjEe',
token: function(token, args) {
var stop = 0;
}
});
document.getElementById('myBtn').addEventListener('click', function(e) {
// Open Checkout with further options
handler.open({
name: 'Demo Site',
description: '2 widgets ($20.00)',
amount: 2000
});
e.preventDefault();
});
on line var stop = 0;.
The example is taken from here.
The SourceToken in that JSON is "tok_1EL43MKfPgrABB02rh7IGG7l".
After the customer is created with the source attached (e.g. that token), you can retrieve the customer which will include that customer's sources (they'll be listed in the sources object under the customer record).
The token itself gets consumed during the creation of the source and customer, and the result is a source that's reusable.

Add a number to a list item with DynamoDB

This is the DynamoDB table structure I'm working on:
{
"userId": "99999999-9999-9999-9999-999999999999",
"userProfile": {
"email": "myemail#gmail.com",
"firstName": "1234124",
"lastName": "123423",
},
"masterCards": [
{
"cardId": 101000000000001,
"cardImage": "logo.png",
"cardName": "VipCard1",
"cardWallet": "0xFDB17d12057b6Fe8c8c425D2DB88d8475674567"
},
{
"cardId": 102000000000002,
"cardImage": "logo.png",
"cardName": "VipCard2",
"cardWallet": "0xFDB17d12057b6Fe8c8c425D2DB88d8183454345"
},
{
"cardId": 103000000000003,
"cardImage": "logo.png",
"cardName": "VipCard3",
"cardWallet": "0xFDB17d12057b6Fe8c8c425D2DB88d8184345345"
}
],
}
I'm trying to increase the cardId field by one for the first list item with this Lambda function:
const dynamoDB = new AWS.DynamoDB({region: 'eu-central-1', apiVersion:'2012-08-10'});
const counterId="99999999-9999-9999-9999-999999999999"
const params = {
TableName:"FidelityCardsUsers",
Key: {"userId":{"S":counterId}},
UpdateExpression:"ADD #masterCards[0].#cardId :increment",
ExpressionAttributeNames:{
"#masterCards": "masterCards",
"#cardId": "cardId"
},
ExpressionAttributeValues:{":increment": {"N": "1"}}
}
dynamoDB.updateItem(params, function(err, data) {
if (err) {
console.log('error getting counter from DynamDB: ',err)
callback(err);
} else {
callback(null,data)
}
})
In return I get only a new top-level attribute named "mastercards[0].cardId[0]" with a value number set to 1.
I have tried to increment In an array and its work fine with AWS.DynamoDB.DocumentClient()
Example :
var AWS = require("aws-sdk");
var docClient = new AWS.DynamoDB.DocumentClient();
let params = {
TableName:'tableName',
Key: {
'venueId': 'VENUE_002'
},
UpdateExpression: "ADD #walk.#coordinates[0] :increment",
ExpressionAttributeNames: {
'#walk': 'walk',
'#coordinates': 'coordinates'
},
ExpressionAttributeValues: {
':increment': 1 // This is from the client
},
ReturnValues: 'UPDATED_NEW'
};
docClient.update(params, function (err, data) {
if (err) {
console.log('failure:updateShuttleDirection:failed');
console.log(err);
} else {
console.log('success:updateShuttleDirection:complete');
console.log(data);
}
});
Sample Data:
"walk": {
"coordinates": [
10,
20
],
"type": "Point"
},
I have tried to increment 10 to 11 and its work fine
Reading the doc here, it seems that:
the ADD action can only be used on top-level attributes, not nested
attributes.

Ember Data FilterBy

I am trying to filter the data coming back from FindAll cause I only want data from a certain provider
// Data coming back from API
{
"-KDinaItb7lkHpai-DlG": {
"email": "johns#test.com",
"name": "John Smith",
"notes": "John is a great employee and is the best",
"phone": "215-543-9830",
"provider": "-KDhzbilOvv7Evuc5S_X"
},
"-KDjS0cCxFWQctcwXg0V": {
"email": "amanda#test.com",
"name": "Amanda Harrington",
"notes": "Amanda is a great employee",
"phone": "215-543-9830",
"provider": "-KDiokWebdhTNKTORWwn"
},
"-KDyf7pU_PyxRQSgFB59": {
"email": "lguy#test.com",
"name": "Larry Guy",
"notes": "He is a funny guy",
"phone": "702-454-2397",
"provider": "-KDhzbilOvv7Evuc5S_X"
}
}
// In the route
let providerId = model.get('provider').get('id');
​
this.store.findAll('employee').then(function(results) {
let prov = results.filterBy('provider', providerId);
​
console.log(prov);
});
When the console log happens and it returns an empty array. I think its because of the ID and its not looking at the nested object. Anyone got any thoughts?
Ok so your hash looks quite odd. Property name shouldn't be some generated hash.
code should be something like that.
I assume you have 1 wrapper object on index 0 within an array.
var filteredEmployees_promise = this.store.findAll('employee').then(function(results) {
var filteredResults = [];
Object.keys(Results[0]).forEach(key => {
var filteredObj = Results[0][key][providerId];
if(Ember.isPresent(filteredObj) {
filteredResults.pushObject(filteredObj)
}
});
return filteredResults;
});
And later
filterEmployees_promise.then(employees => { // Custom stuff })

How do I access the error contents when using futures in Meteor?

I am using futures to make an async call to balanced payments. I want to catch errors and feed them back to the user so I can tell them why their payment failed.
Here is what I get on the server console. How can I parse out the errors[0].status, or errors[0].category_code from this error? I've tried to simply console.log(error[0].status);, but this does nothing.
I20140616-14:38:59.169(0)? "errors": [
I20140616-14:38:59.169(0)? {
I20140616-14:38:59.170(0)? "status": "Conflict",
I20140616-14:38:59.170(0)? "category_code": "card-not-validated",
I20140616-14:38:59.170(0)? "additional": null,
I20140616-14:38:59.170(0)? "status_code": 409,
I20140616-14:38:59.171(0)? "category_type": "logical",
I20140616-14:38:59.171(0)? "extras": {},
I20140616-14:38:59.171(0)? "request_id": "OHMf39d5030f56311e39cde02a
1fe53e539",
I20140616-14:38:59.171(0)? "description": "Card cannot be validated.
Your request id is OHMf39d5030f56311e39cde02a1fe53e539."
I20140616-14:38:59.172(0)? }
I20140616-14:38:59.172(0)? ]
Here is the future function I'm using.
var Future = Npm.require("fibers/future");
function extractFromPromise(promise) {
var fut = new Future();
promise.then(function (result) {
fut["return"](result);
}, function (error) {
fut["throw"](error);
fut.return(error.message);
});
return fut.wait();
}
I call this function from my code using something like this.
var customerData = extractFromPromise(balanced.marketplace.customers.create({
'name': customerInfo.fname + " " + customerInfo.lname,
"address": {
"city": customerInfo.city,
"state": customerInfo.region,
"line1": customerInfo.address_line1,
"line2": customerInfo.address_line2,
"postal_code": customerInfo.postal_code,
},
'email': customerInfo.email_address,
'phone': customerInfo.phone_number
}));
I had some help and got the answer. Hope this helps others. Here is the rewrite of the code I initially wrote.
The future code was both returning and throwing the error, so that was removed, the code was cleaned up a bit as well.
var Future = Npm.require("fibers/future");
function extractFromPromise(promise) {
var fut = new Future();
promise.then(function (result) {
fut.return(result);
}, function (error) {
console.log(error);
fut.throw(error);
});
return fut.wait();
}
And then the whole thing is wrapped in a try catch. I console log out the different parts of the message. Turned out that the JSON was stringified, so that had to be parsed first, then I could access the error like normal JSON data. And I've just learned that no errors will get back to the client unless you use the Meteor.error syntax first.
var customerData;
try {
customerData = extractFromPromise(balanced.marketplace.customers.create({
'name': customerInfo.fname + " " + customerInfo.lname,
"address": {
"city": customerInfo.city,
"state": customerInfo.region,
"line1": customerInfo.address_line1,
"line2": customerInfo.address_line2,
"postal_code": customerInfo.postal_code,
},
'email': customerInfo.email_address,
'phone': customerInfo.phone_number
}));
} catch (e) {
console.log(JSON.parse(e.message).errors[0].extras);
console.log(JSON.parse(e.message).errors[0].category_code);
var error = JSON.parse(e.message).errors[0];
throw new Meteor.Error(error.category_code, error.status_code, error.description, error.extras);
}

Resources