Are Square Connect's HTTP V1 and V2 endpoints compatible? - square-connect

Long story short: I attempted to create an order with the V2 endpoint, and then edit it with the V1 endpoint.
First, I created the order, and I got the following as a result:
{
"order": {
"id": "OaL2MCgsn4gdBsemaz8wIFaxM2WMKLLDR7BwdeCl8T...",
"location_id": "8Q5T7REMOVED",
"reference_id": "my-order-001",
(and so on)
}
}
Then I attempted to close out the order with the following URL:
https://connect.squareup.com/v1/{{location_id}}/orders/OaL2MCgsn4gdBsemaz8wIFaxM2WMKLLDR7BwdeCl8Te...
But the reply was
{
"type": "not_found",
"message": "NotFound"
}
Since it's not finding the order I just made, I suspect that V1 and V2 endpoints aren't compatible. That, or my methodology is incorrect.
Are the square V1 and V2 endpoints compatible?

Generally, v1 and v2 endpoints are compatible. If you look up a transaction in v1 Payments, you'll see the same info in v2 Transactions.
The issue here is that order doesn't mean the same thing in the v1 and v2 worlds. In v1, orders are for Online Store orders, so when you try to update an order, you are attempting to modify an order made with Online Store (Updates the details of an online store order.). Whereas the order you created with the v2 endpoint was inteded to Creates an Order that can then be referenced as order_id in a request to the Charge endpoint.
If you are trying to modify an order that you will then send the id to the Charge endpoint, you cannot at this time and should instead just make a new order.

Related

Amplify and AppSync not updating data on mutation from multiple sources

I have been attempting to interact with AppSync/GraphQL from:
Lambda - Create (works) Update (does not change data)
Angular - Create/Update subscription received, but object is null
Angular - Spoof update (does not change data)
AppSync Console - Spoof update (does not change data)
Post:
mutation MyMutation {
updateAsset(input: {
id: "b34d3aa3-fbc4-48b5-acba-xxxxxxxxxxx",
owner: "51b691a5-d088-4ac0-9f46-xxxxxxxxxxxx",
description: "AppSync"
}) {
id
owner
description
}
}
Response:
{
"data": {
"updateAsset": {
"id": "b34d3aa3-fbc4-48b5-acba-xxxxxxxxxx",
"owner": "51b691a5-d088-4ac0-9f46-xxxxxxxxxxx",
"description": "Edit Edit from AppSync"
}
}
The version in DynamoDB gets auto-incremented each time I send the query. But the description remains the same as originally set.
Auth Rules on Schema -
#auth(
rules: [
{ allow: public, provider: apiKey, operations: [create, update, read] },
{ allow: private, provider: userPools, operations: [read, create, update, delete] }
{ allow: groups, groups: ["admin"], operations: [read, create, update, delete] }
])
For now on the Frontend I'm cheating and just requesting the data after I received a null subscription event. But as I've stated I only seem to be able to set any of the data once and then I can't update it.
Any insight appreciated.
Update: I even decided to try a DeleteAsset statement and it won't delete but revs the version.
I guess maybe the next sane thing to do is to either stand up a new environment or attempt to stand this up in a fresh account.
Update: I have a working theory this has something to do with Conflict detection / rejection. When I try to delete via AppSync direct I get a rejection. From Angular I just get the record back with no delete.
After adding additional Auth on the API, I remember it asked about conflict resolution and I chose "AutoMerge". Doc on this at https://docs.aws.amazon.com/appsync/latest/devguide/conflict-detection-and-sync.html
After further review I'll note what happened in the hopes it helps someone else.
Created amplify add api
This walked me thru a wizard. I used the existing Cognito UserPool since I had not foreseen I would need to call this API from a S3 Trigger (Lambda Function) later.
Now needing to grant apiKey or preferably IAM access from the Lambda to AppSync/GraphQL API I performed amplify update api and added the additional Auth setting.
This asked me how I wanted to solve conflict, since more than one source can edit the data. Because I just hit "agree" on Terms and Conditions and rarely read the manual; I selected 'AutoMerge' .. sounds nice right?
So now if you read the fine print, edits made to a table will be rejected as we now have this _version (Int) that would need to get passed so AutoMerge can decide if it wants to take your change.
It also creates an extra DataStore Table in DynamoDB tracking versions. So in order to properly deal with this strategy you'd need to extend your schema to include _version not just id or whatever primary key you opted to use.
Also note: if you delete it sets _delete Bool to true. This actually still is returned to the UI so now your initial query needs to filter off (or not) deleted records.
Determined I also didn't need this. I don't want to use a Datastore (least not now) so: I found the offender in transform.conf.json within the API. After executing amplify update api, GraphQL, I chose 'Disable Datastore for entire API` and it got rid of the ConflictHandler an ConflictDetection.
This was also agitating my Angular 11 subscription to Create/Update as the added values this created broke the expected model. Not to mention the even back due to nothing changing was null.
Great information here, Mark. Thanks for the write up and updates.
I was playing around with this and with the Auto Merge conflict resolution strategy I was able to post an update using a GraphQL mutation by sending the current _version member along.
This function:
await API.graphql(
graphqlOperation(updateAsset, {
input: {
id: assetToUpdate.id,
name: "Updated name",
_version: assetToUpdate._version
}
}
));
Properly updates, contacts AppSync, and propagates the changes to DynamoDB/DataStore. Using the current version tells AppSync that we are up-to-date and able to edit the content. Then AppSync manages/increments the _version/_createdAt/etc.
Adding _version to my mutation worked very well.
API.graphql({
query: yourQuery,
variables: {
input: {
id: 'your-id',
...
_version: version,
},
},
});

Apollo Client: can apollo-link-rest resolve relations between endpoints?

The rest api that I have to use provides data over multiple endpoints. The objects in the results might have relations that are are not resolved directly by the api, it rather provides ids that point to the actual resource.
Example:
For simplicity's sake let's say a Person can own multiple Books.
Now the api/person/{i} endpoint returns this:
{ id: 1, name: "Phil", books: [1, 5, 17, 31] }
The api/book/{i} endpoint returns this (note that author might be a relation again):
{ id: 5, title: "SPRINT", author: 123 }
Is there any way I can teach the apollo client to resolve those endpoints in a way that I can write the following (or a similar) query:
query fetchBooksOfUser($id: ID) {
person (id: $id) {
name,
books {
title
}
}
}
I didn't try it (yet) in one query but sould be possible.
Read docs strating from this
At the beggining I would try with sth like:
query fetchBooksOfUser($id: ID) {
person (id: $id) #rest(type: "Person", path: "api/person/{args.id}") {
name,
books #rest(type: "Book", path: "api/book/{data.person.books.id}") {
id,
title
}
}
}
... but it probably won't work - probably it's not smart enough to work with arrays.
UPDATE: See note for similiar example but using one, common parent-resolved param. In your case we have partially resolved books as arrays of objects with id. I don't know how to use these ids to resolve missing fields () on the same 'tree' level.
Other possibility - make related subrequests/subqueries (someway) in Person type patcher. Should be possible.
Is this really needed to be one query? You can provide ids to child containers, each of them runing own query when needed.
UPDATE: Apollo will take care on batching (Not for REST, not for all graphql servers - read docs).
'it's handy' to construct one query but apollo will cache it normalizing response by types - data will be stored separately. Using one query keeps you within overfetching camp or template thinking (collect all possible data before one step rendering).
Ract thinking keeps your data and view decomposed, used when needed, more specialised etc.
<Person/> container will query for data needed to render itself and list of child-needed ids. Each <Book/> will query for own data using passed id.
As an alternative, you could set up your own GraphQL back-end as an intermediary between your front-end and the REST API you're planning to use.
It's fairly easy to implement REST APIs as data sources in GraphQL using Apollo Server and a package such as apollo-datasource-rest which is maintained by the authors behind Apollo Server.
It would also allow you to scale if you ever have to use other data sources (DBs, 3rd party APIs, etc.) and would give you full control about exactly what data your queries return.

How to structure Shopify data into a Firestore collection that can be queried efficiently

The Background
In an attempt to build some back-end services for my e-commerce (Shopify based) site I have set up a Firestore trigger that writes order details with every new order created which is updated by a web hook POST function provided by Shopify - (orders/Create webhook).
My current cloud function -
exports.saveOrderDetails = functions.https.onRequest((req, res) => {
var docRef = db.collection('orders').doc(req.body.name);
const details = req.body;
var setData = docRef.set(req.body).then( a =>{
res.status(200).send();
});
});
Which is able to capture the data from the webhook and store it in the order number's "name" document within my "orders" collection. This is how it looks in Firestore:
My question is - with the help of body-parser (already parsing out "name" which is represented as #9999 in my screenshot, to set my document name value) - how could I improve my cloud function to handle storing this webhook POST in a better data structure for Firestore and to query it later?
After reviewing the comments on this question, I moved this question over to Firebase-Talk and it appears the feature I am attempting here would be close to what is known as "collection group queries" and was informed I should adjust my data model approach since this feature is currently still on the road map - and perhaps look into the Firestore REST API as suggested by #jason-berryman
Besides the REST APi, #frank-van-puffelen made a great suggestion to look into working with Arrays, Lists, Sets for Firebase/Firestore
Another approach that could mitigate this in my scenario is to have my HTTP Firestore cloud trigger have multiple parsing arguments that create top more top level documents - however this could cause a point of scaling failure or an increase of cost factor due to putting more parsing processing logic in my cloud function and adding additional latency...
I will mark my question as answered for the time being to hopefully help others to understand how to work with documents in a single collection in Firestore and not attempt to query groups of collections before they get too far into modelling and need to restructure their app.

/v2/locations/location_id/transactions endpoint won't save TAX

I'm trying to push a transaction into square via the API, using the following endpoint:
POST https://connect.squareup.com/v2/locations/location_id/transactions
// Below the data pushed
{
"card_nonce": "-card_nonce-",
"idempotency_key": "-idempotency_key-",
"reference_id": "-reference_id-",
"amount_money": {
"amount": 100,
"currency": "-currency-"
}
}
The problem is that, when I look at the transaction in the dashboard, the details won't display the TAX withheld for the payment. I've also created in the "taxes" tab, an appropriate tax element, which is applied to all the items.
This seems to be working fine for the payments that go through the square app, although, it doesn't work for the payments that go through the API endpoint mentioned above.
Is there any way to specify the tax in the transaction payload? if not, is there any way to solve this issue?
Thanks.
To get your desired outcome, I think you want to create an order first.
You should be able to create the order (with the appropriate taxes, but also itemizations and discounts as well) and then pass the order_id to the charge endpoint. Then your taxes should be correctly calculated, and more details reflected in Dashboard.

Parse.com Stripe: Creating a charge that is not captured

I'm working on an iOS app that uses Stripe to process payments. We are moving from a system that uses two separate charges for initial purchase and tip to a system that uses a single charge that begins as a hold on the user's account and then is captured upon setting the tip. This was the system that Stripe recommended to us when we inquired how to work with a single charge but also validate that the card can handle a charge of the designated amount.
For our back end, we are using Parse.com to track our orders, and so we are using Stripe's integration with Parse.com's Cloud Code as our server. Our main issue is that Parse.com doesn't seem to outright support most of Stripe's functionality (i.e. capturing charges). After some searching, I found that http POST requests were the best option to interact with Stripe.js and actually capture charges. However, I haven't been able to get quite that far because Parse.com is giving me a Code 141 error (Received unknown parameter: captured) when I try to create a charge that is uncaptured. Parse.com's Stripe API suggests that you can set all parameters through their Stripe.Charges.create, but it won't accept captured as a valid parameter.
To abstract for anyone else with this issue, how can I create a charge that has the parameter captured set to false using Parse.com Stripe API?
I have posted some of my Cloud Code below that should define a method to create a charge that has not yet been captured. This method is what is giving me the error that captured is not a valid parameter.
/**
* Create Hold on Card
* Required:
* orderCostInCents -- in cents ex. $10.24 = 1024
* customer -- cus_11EXEXEXEXEXEX
* description -- order.objectId to link it with order item.
*/
Parse.Cloud.define("holdAccount", function(request, response) {
//response.success("Not Charged");
var Stripe = require("stripe");
Stripe.initialize(kStripePrivateKey);
Stripe.Charges.create({
amount : request.params.orderCostInCents,
currency : "usd",
customer : request.params.customer,
captured : false,
description : request.params.description
},{
success: function(httpResponse) {
console.log(httpResponse);
response.success(httpResponse);
},
error: function(httpResponse) {
console.log(httpResponse.message);
response.error("Failed to create charge");
}
});
});
I believe that I can structure an http (POST) request after creating the charge by following the guidelines set at https://www.parse.com/questions/stripe-payment-capture-method-not-available. This guide might be very helpful to anyone else with my issue!
Best, and thanks for your help!
Edit: I realized that I didn't post the version of Cloud Code that we are using. It is 1.2.19.
Well, after taking a break from my hours of staring at the screen, I certainly feel like a doofus! The parameter I was using was captured, where the correct parameter should be capture. I was able to fix my issue by simply removing the "d" from the parameter name while creating the charge.
Whoops! I would still be open to advice on http requests via comments, but I will test those on my own and post a separate thread if I run into issues there as that issue is tangential to this one and thus off-topic.
For everyone joining, the answer is that the above code works perfectly if you replace the parameter captured with capture
Edit: For anyone else that is interested, the follow-up to this question was about actually making the capture via http requests on Parse Cloud Code. The following method works after much searching and trial and error. The hardest part here was figuring out how to format the URL since this is my first foray into http requests. If you need to chain parameters, simply add "&{parameter-name}={parameter-value}"
//kStripePrivateKey is your stripe private key
//Must pass in chargeID = stripe charge id and
//orderCostInCents = capture amount in cents as parameters
var captureURL = "https://"+ kStripePrivateKey +
":#api.stripe.com/v1/charges/"+
request.params.chargeID+
"/capture?amount="+request.params.orderCostInCents;
Parse.Cloud.httpRequest({
url: captureURL,
method: 'POST',
success: function(httpResponse) {
// Handle any success actions here
response.success(httpResponse);
}, error: function(httpResponse) {
response.error(httpResponse);
}
});

Resources