I'm using vbscript to test a REST web service which accepts json as request and responds also in json format. I'm getting HTTP 500 - Internal Server Error as response. Here's the code:
Set objStream = CreateObject("ADODB.Stream")
objStream.CharSet = "utf-8"
objStream.Open
objStream.LoadFromFile("C:\request.txt")
restRequest = objStream.ReadText()
objStream.Close
Set objStream = Nothing
contentType ="application/json"
Set oWinHttp = CreateObject("WinHttp.WinHttpRequest.5.1")
oWinHttp.Open "POST", "http://czcholsint1048.prg-dc.dhl.com:8180/efoms/fulfillOrder", False
oWinHttp.setRequestHeader "Content-Type", contentType
oWinHttp.Send restRequest
response = oWinHttp.StatusText
'response' turns out as "Internal Server Error"
I just wonder whether the json i'm converting to string before sending as request is creating any problem. Maybe beacuse of vbcrlf's it has.
Below is the json i'm sending as request:
{
"fulfillOrderReq": {
"hdr": {
"messageType": "SALESORDER",
"messageID": "d264502f-aaa2-42a5-a38d-c981ccb99379", "messageVersion": "0.1",
"messageDateTime": "2015-03-20 09:48:29",
"appId": "OMS",
"clientId": "PEP-ESB",
"reqCompId": "77000001"
},
"bd": {
"orders": [
{
"order": {
"orderNumber": "BAYLINETEST512",
"salesChannelOrderNumber": "TMALLTEST512",
"shopName": "拜仁慕尼黑海外旗舰店",
"salesChannel": "天猫订单",
"payType": "支付宝",
"created": "2015-03-20 15:35:58",
"salesChannelMemberName": "mariahliu621",
"salesChannelMemberNo": "M-9837423",
"idCard": "12312",
"idType": "NATIONAL_IDENTIFICATION_NUMBER",
"cnee": {
"name": "SANTOSH",
"address1": "CHINA",
"address3": "CHINA",
"state": "CHINA",
"city": "CHINA",
"country": "CN",
"postCode": "50470",
"telephone": "18610041036",
"mobilePhone": "18610041036"
},
"cneeMemo": "",
"cneeMessage": "",
"sellerMemo": "",
"otherMemo": "",
"actualOrderAmount": "792.0",
"agioAmount": "0.0",
"discountFee": "0.0",
"deliveryCost": "70.0",
"promotionInfo": "",
"orderItems": [
{
"orderItem": {
"productNumber": "184005",
"productName": "蜂拥而至CL克 Flock CL gr.",
"skuNumber": "184005",
"skuName": "Ribéry",
"barcode": "",
"orderGroup": "0",
"productQty": "1",
"amount": "75.0",
"discountFee": "0.0",
"agioPrice": "90.0",
"price": "110.0",
"taxCharges": "100",
"untaxPrice": "50",
"dutyCharges": "9",
"refundStatus": "Normal",
"memo": ""
}
}
]
}
}
]
}
}
}
You may have seen this already however wanted to share this here since they are related. http://forum.universal-devices.com/topic/4335-vbscript-rest-example/
Option Explicit
Dim restReq, url, userName, password
Set restReq = CreateObject("Microsoft.XMLHTTP")
' Replace <node> with the address of your INSTEON device
' Additionally, any REST command will work here
url = "http://isy/rest/nodes/<node>/ST"
' If auth is required, replace the userName and password values
' with the ones you use on your ISY
userName = "admin"
password = "<yourpassword>"
restReq.open "GET", url, false, userName, password
restReq.send
WScript.echo restReq.responseText
Related
I am using authorize.net's sandbox API to test their gateway in my wix (corvid/code) environment. Funny thing is that when i send JSON to the sandbox API i get a valid JSON response approving the (fake) transaction. however when i set it up thru wix i get data errors in my console. I have built on existing files that i have been able to run basic API responses, and more advanced auths with token responses. so the code works, just not with authorize.net. given my level of expertise, i think it might be something im doing wrong. i've done my due diligence, and there are no questions on this topic. here is my code:
///front end, from the corvid page's code
import {buyIt} from 'backend/authorizeNet';
export function button1_click(event) {
buyIt();
}
pretty basic, just calling code from my backend onClick. the filepath is correct. here is the module on the backend:
//// backend/authorizeNet.jsw
import {fetch} from 'wix-fetch';
export function buyIt() {
let data = {
"createTransactionRequest": {
"merchantAuthentication": {
"name": "***************",
"transactionKey": "****************"
},
"refId": "123456",
"transactionRequest": {
"transactionType": "authCaptureTransaction",
"amount": "5",
"payment": {
"creditCard": {
"cardNumber": "5424000000000015",
"expirationDate": "2020-12",
"cardCode": "999"
}
},
"lineItems": {
"lineItem": {
"itemId": "1",
"name": "vase",
"description": "Cannes logo",
"quantity": "18",
"unitPrice": "45.00"
}
},
"tax": {
"amount": "4.26",
"name": "level2 tax name",
"description": "level2 tax"
},
"duty": {
"amount": "8.55",
"name": "duty name",
"description": "duty description"
},
"shipping": {
"amount": "4.26",
"name": "level2 tax name",
"description": "level2 tax"
},
"poNumber": "456654",
"customer": {
"id": "99999456654"
},
"billTo": {
"firstName": "Ellen",
"lastName": "Johnson",
"company": "Souveniropolis",
"address": "14 Main Street",
"city": "Pecan Springs",
"state": "TX",
"zip": "44628",
"country": "USA"
},
"shipTo": {
"firstName": "China",
"lastName": "Bayles",
"company": "Thyme for Tea",
"address": "12 Main Street",
"city": "Pecan Springs",
"state": "TX",
"zip": "44628",
"country": "USA"
},
"customerIP": "192.168.1.1",
"transactionSettings": {
"setting": {
"settingName": "testRequest",
"settingValue": "false"
}
},
"userFields": {
"userField": [
{
"name": "MerchantDefinedFieldName1",
"value": "MerchantDefinedFieldValue1"
},
{
"name": "favorite_color",
"value": "blue"
}
]
}
}
}
}
return fetch("https://test.authorize.net/xml/v1/request.api", {
"method": "post",
"headers": {"Content-Type": "application/json"},
"body": data
})
.then(response => {console.log(response.json())});///if response.text is used, it gives details
}
note at the end of the backend code, calling response.json give me a json error, due to the return code contains HTML saying that i've requested invalid data. if i change it to response.text i get this in my console:
//console response with response.text
{...}
isFulfilled:
true
isRejected:
false
fulfillmentValue:
"<HTML><HEAD>\n<TITLE>Bad Request</TITLE>\n</HEAD><BODY>\n<H1>Bad Request</H1>\nYour browser sent a request that this server could not understand.<P>\nReference #7.1d60fea5.1557756725.387c74\n</BODY>\n</HTML>\n"
how do i get a good response from the API? like ive done with the same code in postman?
thanks in advance
return fetch(url, {
method: "post",
headers: {"Content-Type": "application/json"},
body: JSON.stringify(data)
})
.then(response => console.log(response.text())
)
this got me the result i was looking for
stringify() converted my object to a JSON string. i still cannot get it to read the incoming JSON, might have to use parse...but if i read as text i get the info i want and my API is showing a successful transaction.
I have a VBA file that has been working for years with a POST to API function to create products on Shopify. It has suddenly and for non identified reason stopped working around April 15th 2019. It gives the following error:
"error": "822: unexpected token at [my JSON string]
This is what the JSON string looks like (you can find a more complete one at the end of this post):
{
"product": {
"title": "Lunettes",
"body_html": "some long text",
"vendor": "Tom Ford",
"product_type": "lunettes enfant adolescents",
"published": false,
"tags": "some tags",
"variants": [
{
"option1": "default title",
"price": "199",
"sku": "1",
"weight_unit": "g"
}
],
"options": [
{
"name": "title",
"position": 1,
"values": [
"default title"
]
}
]
}
}
What I have already tried:
check the URL with correct API key and token/password
tried adding the latest released Shopify API version to the CURL : 2019-04
check the syntax of the JSON string (comas, {, etc)
Basically tried everything I knew. Please help if you have any clue.
the more complete Json_String is :
{"product":{"title":"Lunettes TF5501 ","body_html":"TEXT,<div style=\"text-align: center;\"><img alt=\"Dimensions Lunettes Varionet TF5501 Argent\" src=\"https://cdn.shopify.com/s/files/1/0855/6878/files/Lunettes.png?15354686291941720795\" style=\"float: none; display: block; margin-left: auto; margin-right: auto;\" /></div><div style=\"overflow-x: auto;\"> <table width=\"100%\"> <tbody><tr style=\"background-color: #98ffaf;\"><td style=\"text-align: center;\">140 mm</td><td style=\"text-align: center;\">54 mm</td><td style=\"text-align: center;\">38 mm</td><td style=\"text-align: center;\">18 mm</td><td style=\"text-align: center;\">145 mm</td></tr></tbody></table></div>","vendor":"Brand","product_type":"lunettes anti lumière bleue","published":false,"tags":"meta-filter-Marque-Varionet,meta-filter-Forme-Rectangle,meta-filter-Genre-Unisex,meta-filter-Genre-Homme,meta-filter-Genre-Femme,meta-filter-Couleur-Argent","variants":[{"option1":"default title","price":"199","sku":"tom ford tf5501016","position":1,"grams":"100","inventory_policy":"deny","compare_at_price":"339","fulfillment_service":"logisticien-mavu","inventory_management":"shopify","option_1":"default title","requires_shipping":true,"taxable":true,"inventory_quantity":1,"weight_unit":"g"}],"options":[{"name":"title","position":1,"values":["default title"] }]
}}
Thanks!
Youri
The first JSON you provided (please correct it to a code-block) is correct, but when parsing your more complete Json_string, you'll see that you have too much curly brackets at the end:
{
"product": {
"title": "Lunettes TF5501 ",
"body_html": "TEXT,https://cdn.shopify.com/s/files/1/0855/6878/files/Lunettes.png?15354686291941720795\" style=\"float: none; display: block; margin-left: auto; margin-right: auto;\" /> 140 mm54 mm38 mm18 mm145 mm",
"vendor": "Brand",
"product_type": "lunettes anti lumière bleue",
"published": false,
"tags": "meta-filter-Marque-Varionet,meta-filter-Forme-Rectangle,meta-filter-Genre-Unisex,meta-filter-Genre-Homme,meta-filter-Genre-Femme,meta-filter-Couleur-Argent",
"variants": [{
"option1": "default title",
"price": "199",
"sku": "tom ford tf5501016",
"position": 1,
"grams": "100",
"inventory_policy": "deny",
"compare_at_price": "339",
"fulfillment_service": "logisticien-mavu",
"inventory_management": "shopify",
"option_1": "default title",
"requires_shipping": true,
"taxable": true,
"inventory_quantity": 1,
"weight_unit": "g"
}],
"options": [{
"name": "title",
"position": 1,
"values": ["default title"]
}]
}
}
}
}
Try removing the last 2 curly brackets
Thanks for your replies
#David : I've seen the link https://community.shopify.com/c/Shopify-APIs-SDKs/error-gt-822-unexpected-token-at-price-rule/td-p/480430 , but i don't understand where and how i must use the 'X-Shopify-Access-Token' in VBA code, should it be added in the objHTTP.setRequestHeader? This is the API key, the Password or the "shared secret" ?
#QHarr : my posting parameters are :
Dim result As String
Dim objHTTP As Object
Url = "http://API-KEY:PASSWORD#SHOP-NAME.myshopify.com/admin/api/2019-04/products.json"
Set objHTTP = CreateObject("MSXML2.ServerXMLHTTP")
objHTTP.Open "POST", Url, False, "API-KEY", "PASSWORD"
objHTTP.setRequestHeader "Content-Type", "application/json"
objHTTP.send ("json_string")
result = objHTTP.responseText
tests["Valid schema"] = tv4.validate(jsonData, schema); is passed even if "error" and "responseType" is missing in the schema. How to make sure that response and schema both are matching for JSON schema.
when I hit post request on postman, the following is the Response Body in postman
{
"statusCode": 400,
"error": "Bad Request",
"message": "Email/Phone number not found",
"responseType": "EMAIL_NOT_FOUND",
"arabicMessage": "البريد الإلكتروني / رقم الهاتف غير موجود"
}
Tests in Postman
var jsonData=JSON.parse(responseBody)
var schema ={
"statusCode": {"type":"integer"},
"message": {"type":"string"},
"arabicMessage":{"type":"string"},
"data": {
"accessToken": {"type":"string"},
"userDetails": {
"_id": {"type":"string"},
"deviceType": {"type":"string"},
"countryCode": {"type":"string"},
"OTPCode": {"type":"integer"},
"invitationCode": {"type":"string"},
"availableCredits": {"type":"integer"},
"totalBookings": {"type":"integer"},
"promoCodes": {"type":"array"},
"updatedAt": {"type":"string"},
"createdAt": {"type":"string"},
"language": {"type":"string"},
"IsDeleted": {"type":"boolean"},
"IsVerified": {"type":"boolean"},
"IsBlock": {"type":"boolean"},
"customerAddresses": {"type":"array"},
"address":{"type":"string"},
"phoneVerified": {"type":"boolean"},
"currentLocation": {
"type": "Point",
"coordinates": [
{"type":"integer"},
{"type":"integer"}
]
},
"appVersion": {"type":"integer"},
"profilePicURL": {
"thumbnail": {"type":"string"},
"original": {"type":"string"}
},
"password": {"type":"string"},
"socialId": {"type":"string"},
"phoneNo": {"type":"integer"},
"email": {"type":"string"},
"LastName": {"type":"string"},
"firstName": {"type":"string"},
"__v": {"type":"integer"},
"referralCode": {"type":"string"},
"accessToken": {"type":"string"},
"deviceToken": {"type":"string"}
},
"updateAvailable": {"type":"boolean"},
"stateCallBookingIds": {"type":"array"},
"forceUpdate": {"type":"boolean"}
}
};
tests["Valid schema"] = tv4.validate(jsonData, schema);
//here the test is passing even with invalid jsonData which is the data
console.log("Validation failed: ", tv4.error);
There are lots of open issues on the Postman github account about the tv4 module.
There is a similar question on SO here, could your jsonData be different than your schema?
This is an example from a link on the tv4 github page.
"title": "Person",
"type": "object",
"properties": {
"firstName": {
"type": "string"
},
"lastName": {
"type": "string"
},
"age": {
"description": "Age in years",
"type": "integer",
"minimum": 0
}
},
"required": ["firstName", "lastName"]
}
You could try adding those fields as required?
Just leaving this here in case it helps anyone else. tv4.validate has two additional boolean parameters: checkRecursive and banUnkownProperties.
Especially the last one can help finding errors in JSON responses when they contain attributes that weren't defined in the schema.
Reference
I prefer to use jsonSchema this way:
var strSchema =
pm.collectionVariables.get("variable_that_contains_the_schema");
pm.test("Validate SCHEMA is OK", () => {
pm.response.to.have.jsonSchema(JSON.parse(strSchema));
});
And if you want to auto-generate the schema, you can use the generate-schema plugin https://www.npmjs.com/package/generate-schema
I use to store the content of this plugin in a collection variable, on the pre-request of my collection, like this:
Then in the test tab of your request, you can call the javascript eval() to load the generate-schema source-code in the postman's test environment:
// eval will evaluate the JavaScript generateSchema code and
// initialize the js on postman environment
eval(pm.collectionVariables.get("generate-schema"));
var strSchema =
pm.collectionVariables.get("variable_that_contains_the_schema");
if (strSchema === undefined){
console.log('>>>> variable for schema not defined!');
return;
}
if(strSchema == '' | strSchema === null) {
// call function generateSchema (external)
var schema = generateSchema.json("variable_that_contains_the_schema", jsonData);
delete schema.$schema; // remove the element '$schema' --> causes error in validator
var strSchema = JSON.stringify(schema);
//save the generated schema
pm.collectionVariables.set("variable_that_contains_the_schema", strSchema);
console.log(" >> schema was generated from the response, validation will proceed on the next request.");
}
else
{
console.log(" >> schema recovered from variable.");
// Schema test ------------------------------------------------
pm.test("Validate SCHEMA is OK", () => {
pm.response.to.have.jsonSchema(JSON.parse(strSchema));
});
}
I am working on an API for my Portal, to provide users the ability to update there data via API directly from there internal Systems.
Liferay 6.2 bundle Tomcat. (for api call testing I use soapUI)
The get Methods work fine, (I have getAll, and getByID). getByID returns a JSON Object like this:
{
"ID": "ORGANIZATIONID",
"type": "ORGANIZATIONTYPE",
"name": "ORGANIZATIONNAME",
"URI": "ORGANIZATIONNAMEURI"
"date of inclusion": "INCLUTIONDATE",
"last activities": "LASTMODIFIEDDATE",
"address": {
"name of host institution": "NAMEOFHOSTINSTITUTE",
"street1": "STREET1",
"street2" : "STREET2",
"zip": "ZIP",
"city": "CITY",
"country": "COUNTRY",
},
"url": [{"ORGANIZATIONURL"}],
"main contact": {
"first name": "FIRSTNAME",
"last name" : "LASTNAME",
"phone": "PHONE",
"email": "MAINCONTACTEMAIL"
},
"type of host institution" : "TYPEOFHOSTINSTITUTE",
"diseases": [
{
"name": "DISEASENAME1",
"number": "SAMPLECOUNT",
"gene": "GENE",
"orphacode": "ORPHA"
"icd10": "ICD",
"omim": "OMIM";
"synonym": "SYNONYM"
},
{
"name": "DISEASENAME2",
"number": "SAMPLECOUNT",
"gene": "GENE",
"orphacode": "ORPHA"
"icd10": "ICD",
"omim": "OMIM";
"synonym": "SYNONYM"
}
]
}
I would like to have an API for Updating the diseases information for an organization. I have created a URL service where everything is in the url as parameters, but I would like to have it that the in the url only the id parameter is send and the rest of the information in a JSON object. Like:
/api/jsonws/....-portlet...../updateregbb/organization-id/16016/
and the data:
{
"ID": "ORGANIZATIONID",
"diseases": [
{
"name": "DISEASENAME1",
"number": "SAMPLECOUNT",
"gene": "GENE",
"orphacode": "ORPHA"
"icd10": "ICD",
"omim": "OMIM";
"synonym": "SYNONYM"
},
{
"name": "DISEASENAME2",
"number": "SAMPLECOUNT",
"gene": "GENE",
"orphacode": "ORPHA"
"icd10": "ICD",
"omim": "OMIM";
"synonym": "SYNONYM"
}
]
}
But I could not find a solution how I can read the JSON data:
#JSONWebService(value = "updateregbb", method = "POST")
public void updateregbb2(long organizationId, Map jsondata) {
#JSONWebService(value = "updateregbb", method = "POST")
public void updateregbb(long organizationId, JSONObject json) {
How can I get the Data into my function?
Thanks for the help,
Best
Robert
{
"statusCode": "000",
"statusMessage": "Record Successfully Fetched",
"dsStatusCode": "000",
"dsStatusMessage": "Record Successfully Fetched",
"businessInput": null,
"businessOutput": {
"systemCircleId": "2",
"category": [
{
"categoryId": "abcs",
"sys": "5ID",
"displayName": "National Roaming Recharge",
"packsList": [
{
"amount": "79",
"benefits": "dsdsdsds",
"packId": "1344",
"processingFees": "70.3",
"serviceTax": "8.7",
"validity": "30 Days",
"volume": "0.0",
"isTop5": "no",
"fileName": "null"
},
{
"amount": "188",
"benefits": "Roaming Tariff - Incoming Free, Outgoing local # 80p/min, STD #1.15Rs/min with Talk Time 120 in main A/c",
"packId": "1263",
"fess": "47.3",
"serviceTax": "20.7",
"validity": "28 Days",
"volume": "0.0",
"isTop5": "no",
"fileName": "null"
},
{
"amount": "306",
"benefits": "FTT 306 with Roaming Tariff - Incoming Free, Outgoing local # 80p/min, STD #1.15Rs/min",
"packId": "1290",
"processingFees": "0",
"serviceTax": "33.7",
"validity": "28 Days",
"volume": "0.0",
"isTop5": "no",
"fileName": "null"
}
]
}
]
}
}
I want to parse this json to filter packlist for each category id using angularjs
assign a variable to the JSON you have. and use scope.$eval on the variable
Example
var jsonVar = { "statusCode": "000",
"statusMessage": "Record Successfully Fetched",
"dsStatusCode": "000",
"dsStatusMessage": "Record Successfully Fetched",
"businessInput": null
}
scope.$eval(jsonVar) // this gives the object on which you can do the ng-repeat
if you still have problems. Try using JSON.stringify(jsonVar) and then perform a scope.$eval on the this.
var jsonString = JSON.stringify(jsonVar);
scope.$eval(jsonString);// This returns a object too