Have to charge sales tax if the order is in Texas, but do not know the address until after customer has entered it. The only event that seemed reasonable was onShippingChange, but after the customer clicks continue, PayPal sends back an error page saying this are not working as expected. I can not be the only person that needs to charge sales tax with these new "Smart" buttons.
<script>
const baseOrderAmount = 20.00;
function initPayPalButton() {
paypal.Buttons({
style: {
shape: 'pill',
color: 'blue',
layout: 'vertical',
label: 'paypal',
},
createOrder: function(data, actions) {
return actions.order.create({
purchase_units: [
{
"description": "Add product to buy",
"custom_id": "xxx-yyy-zzz",
"amount": {
"currency_code": "USD",
"value": baseOrderAmount,
"breakdown": {
"item_total": {
"currency_code": "USD",
"value": baseOrderAmount
},
"tax_total": {
"currency_code": "USD",
"value": 0
}
}
}
}]
});
},
onShippingChange: function (data, actions) {
const taxAmount = (data.shipping_address.state === 'TX' || data.shipping_address.state === 'Texas') ? baseOrderAmount * 0.0825 : '0.00';
return actions.order.patch([
{
op: 'replace',
path: "/purchase_units/##referenceId='default'/amount",
value: {
currency_code: 'USD',
value: (parseFloat(baseOrderAmount) + parseFloat(taxAmount)).toFixed(2),
breakdown: {
item_total: {
currency_code: 'USD',
value: baseOrderAmount
},
tax_total: {
currency_code: 'USD',
value: taxAmount
}
}
}
}
]);
},
onApprove: function(data, actions) {
return actions.order.capture().then(function(orderData) {
const element = document.getElementById('paypal-button-container');
element.innerHTML = '';
element.innerHTML = '<h3>Thank you for your payment!</h3>';
});
},
onError: function(err) {
console.log(err);
}
}).render('#paypal-button-container');
}
initPayPalButton();
</script>
In the browser developer tools Network tab, you can see a 422 or 400 response from the patch operation.
{
"debug_id": "8ff787b4dd2c7",
"details": [
{
"description": "Path should be a valid JSON Pointer https://tools.ietf.org/html/rfc6901 that references a location within the request where the operation is performed.",
"field": "path",
"issue": "INVALID_JSON_POINTER_FORMAT",
"location": "body",
"value": "/purchase_units/##referenceId=default/amount"
}
],
"links": [
{
"href": "https://developer.paypal.com/docs/api/orders/v2/#error-INVALID_JSON_POINTER_FORMAT",
"method": "GET",
"rel": "information_link"
}
],
"message": "The requested action could not be performed, semantically incorrect, or failed business validation.",
"name": "UNPROCESSABLE_ENTITY"
}
Apparently you have an extra at sign (#) in your path, and it has the wrong format...see the SDK reference: https://developer.paypal.com/sdk/js/reference/#onshippingchange
What's given there works:
path: "/purchase_units/#reference_id==\'default\'/amount",
For anyone else trying to implement, you have to modify the script url to add the commit=false as shown below:
<script src="https://www.paypal.com/sdk/js?client-id=<Insert your client Id>&enable-funding=venmo¤cy=USD&commit=false" data-sdk-integration-source="button-factory"></script>
Placed a code block above the paypal script blocks.
#{
var url = #"/purchase_units/#reference_id==\'default\'/amount";
}
and then change with path in the patch
path: "#Html.Raw(url)",
Related
I want to fetch all the data of the corresponding particular field, and have a response of the elastic search.
{
"took": 2,
"timed_out": false,
"_shards": {
"total": 5,
"successful": 5,
"skipped": 0,
"failed": 0
},
"hits": {
"total": {
"value": 35,
"relation": "eq"
},
"max_score": 0.44183275,
"hits": [
{
"_index": "allevents",
"_type": "_doc",
"_id": "jQPDaG0BcOh3oggcguoV",
"_score": 0.44183275,
"_source": {
"category": "sessions",
"contentid": "KqRLj2lWZ3",
"clientname": "omkarpathlab",
------------------
}]
I tried search function it returning an error.
var elasticsearch = require('elasticsearch');
var client = new elasticsearch.Client({
host: 'aaa',
log: 'trace',
apiVersion: '7.1'
});
client.search({
"size": 20,
"query": {
"query_string": {
"default_field": "clientname",
"query": "omkarlab"
}
}
}).then((res) => {
console.log("resultData", res);
}, (err) => {
console.log("err", err);
});
enter code here
Error showing:
{ Error: [illegal_argument_exception] request [/_search] contains unrecognized parameter: [query]
Please suggest me how to solve this kind of problem.
You should specify your field under default_field, not the value you are looking for. The field you are trying to query is clientname in your case, and the value you are looking for is omkarpathlab. So your query should be as follows:
"query": {
"query_string": {
"default_field": "clientname",
"query": "omkarpathlab"
}
}
edit. But your query inside of the body property:
client.search({
"size": 20,
"body": {
"query": {
"query_string": {
"default_field": "clientname",
"query": "omkarlab"
}
}
}
}).then((res) => {
console.log("resultData", res);
}, (err) => {
console.log("err", err);
});
You can use below code to connect to elasticsearch. I have tested it on 5.6 version
'use strict'
const { Client } = require('#elastic/elasticsearch')
const client = new Client({ node: 'http://XXX:9200' })
async function run () {
// Let's search!
const { body } = await client.search({
index: 'XXX',
type : 'XXX',
body: {
query: {
match_all: {}
}
}
})
console.log(body.hits.hits)
}
run().catch(console.log)
Code is a sample from https://www.elastic.co/guide/en/elasticsearch/client/javascript-api/current/search_examples.html site.
for search documentation check below link
https://www.elastic.co/guide/en/elasticsearch/client/javascript-api/current/api-reference.html#_search
I would like to add more properties in the paypal's actions.order.create function. Properties like tax_total, shipping, insurance, list of items that the customer bought etc.
I have implemented the code from their website and it works fine, What is left is adding the extra details in the code. This is their documentation: https://developer.paypal.com/docs/api/orders/v2/#orders_create.
<script>
paypal.Buttons({
createOrder: function(data, actions) {
return actions.order.create({
purchase_units: [{
amount: {
// value: '350.00',
breakdown: {
item_total: '300.00',
tax_total: '20.00',
shipping: '10.00',
handling: '10.00',
insurance: '10.00'
},
}
}]
});
},
onApprove: function(data, actions) {
// Capture the funds from the transaction
return actions.order.capture().then(function(details) {
// Show a success message to your buyer
console.log(data, actions);
alert('Transaction completed by ' + details.payer.name.given_name);
// Call your server to save the transaction
return fetch('/paypal-transaction-complete', {
method: 'post',
headers: {
'content-type': 'application/json',
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
},
body: JSON.stringify({
orderID: data.orderID
})
});
});
}
}).render('#paypal-button-container');
</script>
The code above is what I have tried, I expected that the breakdown properties will be part of the payload as shown in the documentation but I get an error from the console instead.
So what will be the right way to add these properties? Thanks in advance :)
I found an answer here:
https://github.com/paypal/paypal-checkout-components/issues/1098
The example in that link had a currency code that didn't work for me. Below is a similar example:
var createOrder = function createOrder(data, actions) {
return actions.order.create({
"purchase_units": [
{
"reference_id": 1234,
"description": "Attempt n.1 for Quote ID 1234",
"amount": {
"currency_code": "USD",
"value": 14.4,
"breakdown": {
"item_total": { "currency_code":"USD", "value":"12"},
"shipping": { "currency_code":"USD", "value":"1"},
"tax_total": { "currency_code":"USD", "value":"1.4"},
"discount": { "currency_code":"USD", "value":"0"}
}
},
"items": [
{
"name": "OnePlus 6 T-rex 12\" name for 14\"\" blabla \" more double quotes",
"unit_amount": {
"currency_code": "USD",
"value": 12
},
"tax": {
"currency_code": "USD",
"value": 1.4
},
"quantity": 1,
"sku": "OnePlus61",
"category": "PHYSICAL_GOODS"
}
],
"shipping": {
"address": {
"address_line_1": "Some line 1",
"address_line_2": "Some line 2",
"admin_area_2": "Some city",
"admin_area_1": "some state",
"postal_code": "12345",
"country_code": "GB"
}
}
}
]
});
};
Note that each amount must add up to the total value (in this case 14.4). Also note that in this example the values for the keys tax_total and tax must match. This may not be the case if you have more than one item as part of the order.
I'm attempting to perform an aggregate function to calculate the sum of the cost and margin values based on the name value. So if multiple results have the name "Fake Provider' I want the sum of the cost results and the sum of the margin results.
Query statement:
Pharmacy.aggregate([
{
$match: {
$and: [{ 'prescription.status': 'Ready for Pickup' }]
}
},
{
$project: {
'insurance.primary.name': 1,
'prescription.financial.cost': 1,
'prescription.financial.margin': 1
}
}
])
Results are similar to:
[
{
"_id": "5cab98cd293bd54e94c40461",
"insurance": {
"primary": {
"name": "Fake Provider 1"
}
},
"prescription": [
{
"financial": {
"cost": "2.89",
"margin": "5.60"
}
},
{
"financial": {
"cost": "0.88",
"margin": "1.24"
}
}
]
},
{
"_id": "5cab98d0293bd54e94c40470",
"insurance": {
"primary": {
"name": "Fake Provider 1"
}
},
"prescription": [
{
"financial": {
"cost": "3.22",
"margin": "9.94"
}
},
{
"financial": {
"cost": "2.57",
"margin": "9.29"
}
},
{
"financial": {
"cost": "2.03",
"margin": "10.17"
}
}
]
}
]
I have attempted to create a group statement without any luck. Also, the cost and margin values are currently stored as strings.
$group: {
_id: '$insurance.primary.name',
Financial: {
$push: {
id: '$insurance.primary.name',
name: '$insurance.primary.name',
cost: '$prescription.financial.cost',
margin: '$prescription.financial.margin'
}
}
}
I would like to get results similar to:
[
{
"primaryInsurance": "Fake Provider 1",
"totalFinancialCost": "11.59",
"totalFinancialMargin": "36.24"
},
{
"primaryInsurance": "Fake Provider 2",
"totalFinancialCost": "12.82",
"totalFinancialMargin": "22.16"
}
]
I think I have a solution that returns the results using a find and projection then using javascript to map thru the results and perform the addition. However, I would prefer to do this at the Database level.
You must first unwind the 'prescription' field then perform a group. Try this pipeline:
let pipeline = [
{
$unwind: {
path: '$prescription'
}
},
{
$group: {
_id: '$insurance.primary.name',
totalFinancialCost: {
$sum: { $convert: { input: '$prescription.financial.cost', to: "decimal" } }
},
totalFinancialMargin: {
$sum: { $convert: { input: '$prescription.financial.margin', to: "decimal" } }
}
}
}]
Notice how the values are converted to decimal in order to perform the sum.
Below i mentioned the design document.
{
"_id": "_design/link",
"_rev": "62-0c0f00dd9dbedab5c2cca61c356bbff4",
"views": {
"link": {
"map": "function(doc) {\n if (doc.projects) { for (var i in doc.projects) { emit(doc._id, {_id: doc.projects[i].proj_id}); }} \n}"
},
"lists": {
"sample": "function(head, req) {while(row = getRow()){ send(row.doc.proj_name);} }"
}
}
}
The view result:
{
total_rows: 1,
offset: 0,
rows: [
{
id: "SCI130202",
key: "SCI130202",
value: {
_id: "PID00034"
},
doc: {
_id: "PID00034",
_rev: "1-0a363e98a605a72fd71bb4ac62e0b138",
client_id: "E000022",
client_name: "Edinburgh Steel",
type: "manage projects",
proj_id: "PID00034",
proj_name: "Global_upgrade_Oracle",
proj_domain: "Information Technology",
proj_start_date: "2014-10-08",
proj_end_date: "2015-07-07",
delivery_manager: null,
proj_standards: null,
proj_currency_type: "INR",
onsite: "No",
location: "Edinburgh",
proj_status: "Noy yet Start",
budgeted_margin: 45,
budgeted_hrs: 300,
projected_revenue: 200000,
billing_rate: 30,
unit_measure: "per month",
billing_cycle: "Milestone",
proj_core_tech_skills: [ ],
proj_secon_skills: [ ],
proj_sdlc_skills: [ ],
tag: "",
margin: [
{
desired_onsite: null,
desired_offshore: null,
lower_limit: null
}
]
}
}
]
}
I tried but the error comes like
function raised error: (new TypeError("row.doc is undefined", ""))
How to get the proj_name,proj_start_date and proj_end_date using couchdb list function?
You need to add the include_docs=true option to the URL you are using to query the view/list. Views do not automatically include the document.
And maybe you shouldn't use a list to filter your view result - just let the view emit what you need:
emit(doc._id, {
_id: doc.projects[i].proj_id
});
Turns into:
emit(doc.proj_id, {
proj_name: doc.proj_name,
proj_id: doc.proj_id,
proj_start_date: doc.proj_start_date,
proj_end_date: doc.proj_end_date
});
You don't need to emit the doc._id - it is automatically emitted for every row.
This is my JSON output:
[
{
"Business": [
{
"id": "5739"
},
{
"userid": ""
},
{
"name": "Ben Electric"
},
{
"description": ""
},
{
"address": ""
},
{
"email": "*****#gmail.com"
},
{
"phone2": "050*****88"
},
{
"phone3": ""
},
{
"mobile": "050****88"
},
{
"opentimes": ""
},
{
"services": ""
},
{
"places": ""
},
{
"logo": null
},
{
"image": null
},
{
"video": ""
},
{
"owner_name": "Ben Brant"
},
{
"owners": "1"
},
{
"userpic": "http://graph.facebook.com/****/picture"
},
{
"circle": "3"
},
{
"fc": "0"
},
{
"rating_friends": ""
},
{
"rating_global": "3.3333"
},
{
"advice": ""
},
{
"subscription": "none"
}
]
},
{
"Business": [
{
"id": "5850"
},
{
"userid": ""
},
{
"name": "Bla Bla"
},
{
"description": ""
},
{
"address": ""
},
{
"email": "*****#gmail.com"
},
{
"phone2": ""
},
{
"phone3": ""
},
{
"mobile": "0*****995"
},
{
"opentimes": ""
},
{
"services": ""
},
{
"places": ""
},
{
"logo": null
},
{
"image": null
},
{
"video": ""
},
{
"owner_name": "Ben VBlooo"
},
{
"owners": "1"
},
{
"userpic": "http://graph.facebook.com/******/picture"
},
{
"circle": "3"
},
{
"fc": "0"
},
{
"rating_friends": ""
},
{
"rating_global": "2.0000"
},
{
"advice": ""
},
{
"subscription": "none"
}
]
},
{
"Info": {
"message": "No user for the business"
}
},
{
"OK": {
"message": "By Circle"
}
}
]
I'm trying to get the objects in javascript in this way but it doesnt work, should i loop through each Business object?? is there a way to access the real data objects directly?
Here's what I'm trying:
$.ajax({
type: 'POST',
url: 'BLABLA',
data: { BLABLA },
dataType: 'json',
success: function( resp ) {
if(resp.length == 0) {
$('.searchol').append('<li>No results found.</li>');
return;
}
$.each(resp, function(index, element) {
$('.searchol').append('Users Picture: '+element.Business.userpic);
But I cant seem to get to the object?
I just tried this code using your sample json like that
$.each(resp, function(index,element){
$.each(element, function(ind,ele){
if(ele.length){
$.each(ele,function(ind,ele){
if(ele.userpic)
console.log(ele.userpic)
})
}
})
})
"Business" is referring to an array (square bracket), so element.Business.userpic does not exist (element.Business[0].userpic exists though). Depending on what you want to achieve, you'll either have to loop through Business or access userpic of a particular array item.
Your business object is a array of object
"Business": [
{
"id": "5850"
},
Check this JSFiddle script on how to read that
Sample output
Picture: undefined (index):192
Picture: http://graph.facebook.com/****/picture
This will help you out
$.each(resp, function(index, element) {
$('.searchol').append('Users Picture: '+element.Business["userpic"]);
Your JSON is weird. Instead of :
Business : [
{ id : 'id1' }
{ name : 'name1' }
]
Business[0].id // access id
Business[1].name // access name
Where you have to remember where each attribute is in the array (or loop over the array to find it), you should have:
Business : {
id : 'id1',
name : 'name1'
}
Business.id // access id
Business.name // access name
If you can't change the JSON, you can use the following 2 methods to quickly get a property of Business:
var propMap = {
id : 0,
userid : 1,
name : 2 // etc
}
function getBusinessProp(business, prop) {
return business[propMap[prop]][prop];
}
// usage :
$('.searchol').append('Users Picture: '+ getBusinessProp(element.Business, 'userpic'));
If your array can be missing some items or the items can be in a different order for each business, then you need to iterate to find the property you're interested in:
function getBusinessProp(business, prop) {
for (var i=0; i<business.length; i++) {
if (business[i].hasOwnProperty(prop)) {
return business[i][prop];
}
}
}
// same usage, no need for the map anymore
The second method is probably better because it won't break if you change the order of the array or add new items in the array, etc and the performance boost given by using the map is probably not enough to justify the added maintenance cost.