How to Display Value Created from API Onto My Browser? - javascript

So I am working with this API and it auto calculates the delivery fee based on the address you input.
Here's the API docs I am using
https://developer.doordash.com/en-US/api/drive#operation/DeliveryQuote
So when I add my values to my form and get my data, it logs the fee in my console like this
My issue is how do I get this value from the data field?
I tried to do
const response = await client.createDelivery(
{
order_value: req.body.item1,
fee: fee,
tip: req.body.item1,
},
console.log(fee)
);
console.log(response);
res.send(response);
}
)
But it says fee is not defined?
I also tried fee: "" and that doesn't work either.
I even put console.log(data.fee) and it says data is not defined
My last attempt I change it to console.log(response.fee) and it still showed undefined in the console?
How do I even get the fee value to console.log?
Note I am using express and for my tip value I have my input form named "item1" so I can access it by saying req.body.item1 to get that value
However, for the fee value its auto generated by the API, so I can't change it or update it manually myself.

Try using
console.log(response.data.fee)
And I am not sure what your client.createDelivery does. If it sends response, then you need to display it like
const response = await client.createDelivery(
{
order_value: req.body.item1,
fee: fee,
tip: req.body.item1,
},
console.log(fee)
).then((res) => res.json()).then((resData) => console.log(resData.data.fee));

this is what the return object looks like
{
data {
currency: 'USD',
fee: 975,
otherData: otherData,
}
}
what you must do to fix your problem is first dive into the data object then retrieve fee from that object like data.fee
const response = await client.createDelivery(
{
order_value: req.body.item1,
fee: data.fee, // changed from fee to data.fee
tip: req.body.item1,
},
console.log(data.fee)
);
without retrieving it from the data object there would be no fee object to grab which is whats making it undefined...

Related

Stripe business profile is not showing on request body

I'm in test mode, I create a custom connected account successfully using JavaScript in frontend and PHP in backend.
The account created successfully but for some reason, the business profile is not showing on request body (I see this in stripe log in dashboard).
I see a warning message before form submition:
business_profile is not a recognized parameter
For your reference, here’s the API coding I used when I did my test:
https://stripe.com/docs/api/accounts/create?lang=php#create_account-business_profile
JavaScript
const accountResult = await stripe.createToken('account', {
business_type: 'company',
company: {...},
business_profile: {
mcc: "5812",
support_email: "test#example.com",
url: "https://example.com",
},
tos_shown_and_accepted: true,
});
PHP
// ...
$account = \Stripe\Account::create([
"country" => "FR",
"type" => "custom",
"account_token" => $account_token,
]);
// ...
stripe.createToken doesn't take a business_profile value, nor does it manage Stripe\Account objects at all - it creates a Stripe\Token. You'll have to update that information via a separate call to the Stripe API. The parameters it does take are documented here:
name, address_line1,address_line2, address_city, address_state, address_zip, address_country, currency

How to create a Stripe subscription with a variable quantity?

Right now I'm successfully creating a Stripe subscription that has a hardcoded quantity:
customer = stripe.Customer.create(email=request.form['stripeEmail'], source=request.form['stripeToken'])
# For the moment, change the quantity parameter for each customer
subscription = stripe.Subscription.create(
customer = customer.id,
items = [
{
'plan': 'plan_*************',
'quantity': 7,
},
],
)
The idea would be to obtain that value for quantity from the frontend. I already have a selector that sets the quantity value programmatically and I'm actually using it to print variable amounts in Stripe Checkout:
<script>
var handler = StripeCheckout.configure({
key: "{{pub_key}}",
image: "https://stripe.com/img/documentation/checkout/marketplace.png",
locale: "auto",
zipCode: true,
token: function(token) {
// You can access the token ID with `token.id`.
// Get the token ID to your server-side code for use.
}
});
document.getElementById("customButton").addEventListener("click", function(e) {
var quantity = document.getElementsByName("selectedQuantity")[0];
var text = quantity.options[quantity.selectedIndex].text;
// Open Checkout with further options:
handler.open({
name: "Company, Inc.",
description: text + " Subscriptions",
amount: 900 * text
});
e.preventDefault();
});
// Close Checkout on page navigation:
window.addEventListener("popstate", function() {
handler.close();
});
</script>
Notice that I'm getting the public key from the backend, but I don't know how to retrieve the quantity value from the frontend in the backend.
How do I do that?
EDIT:
When I wasn't using a custom Checkout integration I had a form that would do this:
<form action="{{ url_for('pay') }}" method="POST">
But there is no form here, so I'm not sure what should the next step be.
How are you submitting the token to your backend server(i.e. how have you implemented the token function)? Once you've done that, you can just submit the quantity in the same way.
One way to do this might be to use a form, add the Stripe token to a hidden input in that form, and then submit it with Javascript.
Here's an example : https://jsfiddle.net/53u96kvw/
Or if you don't have a form at all, you can make an AJAX request with the same information : https://jsfiddle.net/kcp12o3z/

Priority-Web-SDK: Filtering a form

I am trying to understand how to use the setSearchFilter function in the Priority Web SDK. I can run formStart() followed by form.getRows(1) to get the entire form, but I only need ~5 of the over 100 rows.
login(configuration)
.then(() => formStart('ORDERS', null, null, 'demo',1))
.then(form => form.setSearchFilter({
or: 0,
ignorecase: 1,
QueryValues: [{
field: 'TOTPRICE',
fromval: '100',
op: '>'
}]
}))
.then(filter => filter.getRows(1))
.then(rows => console.log(rows))
.catch(err => console.log(err));
If I comment out the then-setSearchFilter line, I get the entire form. With it in, I get filter undefined.
This is for a phone app so how much data I download seems important.
As you can see in the documentation setSearchFilter doesn't return a filter object. After defining the filter each call to getRows will return rows according to the filter. You should call it like this: form.getRows not filter.getRows.
In addition, when defining a Filter you must define all of its members.

pouchdb put is still rejected with _rev

I'm using pouchDB for the first time, and as indicated in the docs I'm using put() so it will automatically handle revisions. However, when the code is running and there's an existing item with the same ID, it's still rejecting even when including a _rev.
Here's my code:
var db = new PouchDB('blog')
...
function saveCategory(category) {
var savedCategory = {
_id: 'category' + category.id,
_rev: '2-' + String(new Date().toISOString()),
name: category.name,
nicename: category.slug,
post_count: category.count,
description: category.description,
link: category.link,
parent: category.parent
}
return db.put(savedCategory).then((response) => {
$log.log(response)
}).catch((error) => {
$log.error('error saving category ',error)
})
}
This is not the purpose of the _rev field. It is always generated by the server and not by your code. To update a document you must pull the entire document (including the _rev field), update the desired fields, and then put the document. The value of _rev should be the same as when you got it from the server.
If you have a new record, you do not need to set _rev.
The pocketDB guide has a very useful section about this.

correct way to use Stripe's stripe_account header from oauth with meteor

I'm trying to build a platform based on Meteor that uses Stripe Connect. I want to use the "preferred" authentication method from Stripe (Authentication via the Stripe-Account header, https://stripe.com/docs/connect/authentication) so that I can create plans and subscribe customers on behalf of my users. I cannot get it to work. I tried with a second params object, similar to the exemple in the documentation:
var stripeplancreate = Meteor.wrapAsync(Stripe.plans.create, Stripe.plans);
var plan = stripeplancreate({
amount: prod.price,
interval: prod.interv,
name: prod.name,
currency: prod.curr,
id: prod.id+"-"+prod.price+"-"+prod.curr+"-"+prod.interv,
metadata: { prodId: prod._id, orgId: org._id },
statement_descriptor: prod.descr
},{stripe_account: org.stripe_user_id});
but I get "Exception while invoking method 'createStripeProduct' Error: Stripe: Unknown arguments ([object Object]). Did you mean to pass an options object? See https://github.com/stripe/stripe-node/wiki/Passing-Options." which does not seem to accurately reflect the issue but prompted me to try adding stripe_account in the params object itself:
var stripeplancreate = Meteor.wrapAsync(Stripe.plans.create, Stripe.plans);
var plan = stripeplancreate({
amount: prod.price,
(...)
statement_descriptor: prod.descr,
stripe_account: org.stripe_user_id
});
I then get the following error: "Exception while invoking method 'createStripeProduct' Error: Received unknown parameter: stripe_account"
Any ideas? Has anybody managed to have Stripe Connect stripe_account authentication work with Meteor, especially with Meteor.wrapAsync(...)?
This should work for wrapAsync, HOWEVER check out my answer here for possible issues with wrapAsync - Wrapping Stripe create customer callbacks in Fibers in Meteor:
Here is also a great video on wrapAsync: https://www.eventedmind.com/feed/meteor-meteor-wrapasync
var createStripePlanAsync = function(shoppingCartObject, callback){
stripe.plans.create({
amount: shoppingCartObject.plan.totalPrice,
interval: shoppingCartObject.plan.interval,
name: shoppingCartObject.plan.planName,
currency: "usd",
id: shoppingCartObject.plan.sku //this ID needs to be unique!
}, function(err, plan) {
// asynchronously called
callback(err, plan);
});
};
var createStripePlanSync = Meteor.wrapAsync(createStripePlanAsync);
var myShoppingCart = {
customerInfo: {
name: "Igor Trout"
},
plan: {
totalPrice: 5000,
interval: "month",
name: "Set Sail For Fail Plan",
sku: "062015SSFF"
}
};
// Creates the plan in your Stripe Account
createStripePlanSync(myShoppingCart);
Later when you subscribe a customer to a plan you just refer to the plan via the id that you gave the plan when you first created it.
After much trying multiple things, for now, I just managed to get it working using the stripe-sync package instead of the "normal" one + wrapAsync.
try{
var plan = Stripe.plans.create({
amount: prod.price,
...
},{stripe_account: org.stripe_user_id});
}catch(error){
// ... process error
}

Categories

Resources