I am trying to create a Sales Invoice through Sage Accounting API calls (its documentation can be found here: https://developer.sage.com/api/accounting/api/)
To make my code clearer I have created a class that helps me make those calls accordingly.
Here is the method I use to make those calls:
public function postRequest()
{
$url = $this->baseEndpoint . $this->request;
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
if (isset($this->params)) {
curl_setopt($ch, CURLOPT_POSTFIELDS, $this->params);
}
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
"Authorization: Bearer $this->token",
"Host: api.accounting.sage.com",
"Content-Type: application/json"
));
$response = json_decode(curl_exec($ch), true);
curl_close($ch);
return $response;
}
How I call this method:
$params = array(
"sales_invoice" => array(
"contact_id" => "485fdfe0be154f9c9af44351de16e5be",
"date" => "2019-06-13",
"invoice_lines" => array(
array(
"description" => "description",
"ledger_account_id" => "f04157c90ff0496ab3a22f2558e46010",
"unit_price" => 10 ,
"quantity" => 1,
"tax_rate_id" => "ES_RE_STANDARD",
"tax_rate" => 0.1
)
)
)
);
$params = json_encode($params);
$request = "v3.1/sales_invoices";
$sageRequest = new SageRequest($token, $request, $params);
$sageRequest->postRequest();
According to the API documentation, that should work, but still I get this error:
[$severity] => error
[$dataCode] => UnexpectedError
[$message] => An unexpected error occurred.
[$source] =>
If there is anyone who has some experience with the Sage Accounting API, I would be more than grateful to know what I have done wrong.
This example works for me on a Spanish business:
{
"sales_invoice": {
"contact_id": "22b609fba11642238f2ecd0f5fe3e0b5",
"date": "2019-06-12",
"invoice_lines": [
{
"description": "Description",
"ledger_account_id": "829739738de811e996c90122ae3d08ca",
"quantity": 1,
"unit_price": 100,
"tax_rate_id": "ES_STANDARD"
}
],
"main_address": {
"city": "Madrid"
}
}
}
Make sure your contact is listed in the contact endpoint. Use GET https://api.accounting.sage.com/v3.1/ledger_accounts?visible_in=sales to get a list of all valid ledger accounts for sales objects.
I see your question uses ES_RE_STANDARD as tax rate. I will update this answer soon with an example for the "recargo de equivalencia" tax rate.
Related
I need to create a SKU via stripe API.
The problem is in inventory field.
Stripe api response is:
'error' => [
'message' => 'Invalid hash',
'param' => 'inventory',
'type' => 'invalid_request_error'
]
My php code is:
$endPoint = 'https://api.stripe.com/v1/skus';
$APIKEY_TEST = 'my_api_key';
$headers = array('Authorization: Bearer '.$APIKEY_TEST);
$sku = [
'active' => 'true',
'inventory' => ['quantity' => 10000000 ,'type' => 'infinite', 'value' => null],
"currency" => "eur",
"price" => $price,
"product" => $stripe_product_id
];
$array_string ='';
foreach($sku as $key => $value) {
$array_string .= $key.'='.$value.'&';
}
rtrim($array_string, '&');
$ch = curl_init();
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_URL, $endPoint);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $array_string);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
$output = curl_exec($ch);
curl_close($ch);
In stripe api docs inventory is hash type field.
I have tried json_encode() without luck.
Maybe the problem is in sending an array instead of a hash.
In $sku array, inventory field is also an nested associative array.
Maybe the problem resides there as well.
Is there a way to send CURLOPT_POSTFIELDS containing inventory so that stripe accepts it?
EDIT:
In Stripe dashboard i can see my request:
{
"active": "true",
"inventory": "Array",
"currency": "eur",
"price": "3",
"product": "prod_F6ipvfYFvOxxQq"
}
Inventory field has no data, but instead "Array".
After trying a lot of possible solutions, i found the answer:
$post_array = http_build_query($sku);
And know stripe accepts the $sku array with nested inventory array.
It worth notice that stripe does not accept JSON in requests.
The request has to be url encoded.
I am trying to get more than 20 images with the searches endpoint:
$data = '{
"query": {
"ands": [
{
"output": {
"input": {
"data": {
"image": {
"url": "' . $url . '"
}
}
}
}
}
]
}
}';
$ch = curl_init('https://api.clarifai.com/v2/searches?
page=1&per_page=30');
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
"Authorization: Key " . self::$clarify_user_apikey,
"Content-Type: application/json")
);
$output = curl_exec($ch);
curl_close($ch);
The images are initialized above in the $data variable.
Does the image search not have pagination and per_page attributes, or what am I doing wrong?
However I change the two attributes, I always get a max of 20 images back. The App / Project in question has more than 70k images, and the explorer app shows more images as well.
Thanks!
I found the answer.
For easier understanding I formatted the JSON part into an array.
$data = array(
"query" => array(
"ands" => array(
array(
"output" => array(
"input" => array(
"data" => array(
"image" => array(
"url" => $url
)
)
)
)
)
)
),
"pagination" => array(
"page" => 1,
"per_page" => 100
),
);
This code gives 100 images back. I haven't seen an upper limit yet, but it seems to work fine with 500 images as well. The request call gets slow then, though.
I'm using the Magento ver. 2.1.2 Rest Api to create users, following this :
http://devdocs.magento.com/guides/m1x/api/rest/Resources/resource_customers.html#RESTAPI-Resource-Customers-HTTPMethod-POST-customers
$data = [
"customer" => [
"firstname" => 'Earl',
"lastname" => 'Hickey',
"email" => 'earl-2#example.com',
"password" => 'password',
"website_id" => 1,
'store_id' => 1,
"group_id" => 1
]
];
$token = $this->get('lp_api')->getToken();
$ch = curl_init( $this->endpoint . 'customers');
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
curl_setopt($ch, CURLOPT_VERBOSE, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
"Content-Type: application/json", "Authorization: Bearer " . json_decode( $token ),
)
);
// var_dump(curl_getinfo($c));
$result = curl_exec($ch);
If i send a password (as in the example above), i've got the following error :
Next Exception: Report ID: webapi-583357a3bf02f; Message: Property "Password" does not have corresponding setter in class "Magento\Customer\Api\Data\CustomerInterface". in /var/www/html/www.magento.dev/vendor/magento/framework/Webapi/ErrorProcessor.php:195
I noticed that if i remove the "password" => 'password' from the $data array, a user is created without password (seems odd to me).
I can't find any help on this error.
Any idea anyone ?
Refer below link for Magento 2.x version.
http://devdocs.magento.com/swagger/index_20.html#/
I have used below body for creating customers through Rest Api and it worked properly.
{
"customer": {
"email": "xyz#abc.com",
"firstname": "x",
"lastname": "y",
"website_id":1,
"group_id":1,
"custom_attributes": [
{
"attribute_code": "mobile_no",
"value": "1234567890"
}
]
},
"password": "123456"
}
Hi im trying to translate this python script to php. I don't have much knowledge of Python and limited for PHP.
The python script is:
import urllib2
import json
data = {
"Inputs": {
"input1": {
"ColumnNames": ["Client_ID"],
"Values": [ [ "0" ], [ "0" ], ]
},
},
"GlobalParameters": {}
}
body = str.encode(json.dumps(data))
url = 'https://ussouthcentral.services.azureml.net/workspaces/3e1515433b9d477f8bd02b659428cddc/services/cb1b14b17422435984943d51b5957ec7/execute?api-version=2.0&details=true'
api_key = 'abc123'
headers = {'Content-Type':'application/json', 'Authorization':('Bearer '+ api_key)}
req = urllib2.Request(url, body, headers)
try:
response = urllib2.urlopen(req)
result = response.read()
print(result)
except urllib2.HTTPError, error:
print("The request failed with status code: " + str(error.code))
print(error.info())
print(json.loads(error.read()))
In a bid to try and convert it myself, here is what I have done so far:
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
$data = array(
'Inputs'=> array(
'input1'=> array(
'ColumnNames' => ["Client_ID"],
'Values' => [ [ "0" ], [ "0" ], ]
),
),
'GlobalParameters'=> array()
);
$body = json_encode($data);
$url = 'https://ussouthcentral.services.azureml.net/workspaces/3e1515433b9d477f8bd02b659428cddc/services/cb1b14d17425435984943d41a5957ec7/execute?api-version=2.0&details=true';
$api_key = 'abc123';
$headers = array('Content-Type'=>'application/json', 'Authorization'=>('Bearer '+ $api_key));
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL,$url);
curl_setopt($curl, CURLOPT_POST, 1);
curl_setopt($curl, CURLOPT_POSTFIELDS, $body);
curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
$result = curl_exec($curl);
var_dump($result);
im sure I have got lots wrong but would appreciate the help.
thanks
I just had to do this myself and though I'd provide an answer for you. If you're going to talk to Azure's ML platform using php, you need to build your CURL call like this:
$data = array(
'Inputs'=> array(
'input1'=> array(
'ColumnNames' => array("header1", "header2", "header3"),
'Values' => array( array("value1" , "value2" , "value3"))
),
),
'GlobalParameters'=> null
);
$body = json_encode($data);
$url = 'your-endpoint-url';
$api_key = 'your-api-key';
$headers = array('Content-Type: application/json', 'Authorization:Bearer ' . $api_key, 'Content-Length: ' . strlen($body));
$this->responseArray['body'] = $body;
$curl = curl_init($url);
curl_setopt($curl, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($curl, CURLOPT_POSTFIELDS, $body);
curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
$result = curl_exec($curl);
Of all the places to get hung up, it was on the GlobalParameters for me, and is for you, too. You need this instead:
GlobalParameters => null
This generates the following JSON
GlobalParameters: {}
whereas
GlobalParameters => array()
gives
GlobalParameters: []
it's a subtle distinction, but enough to make Azure throw a hissy fit.
I didn't test using your curl_setopt functions and instead used what I've included in my example. I'm assuming it will work using the curl_setopts you have, but I don't know for sure.
I had some trouble adapting this perfectly, and I wanted to be able to easily work with JSON & Guzzle. Below is the solution that I built.
First is the function for making the actual call to Azure. Note that Guzzle wants your URL to be split into the domain and URI pieces.
This should all be in your .env file (if you're using Laravel at least).
AZURE_BASE=https://ussouthcentral.services.azureml.net
AZURE_URL=/workspaces/[[YOUR_STUFF_HERE]]/services/[[YOUR_STUFF_HERE]]/execute?api-version=2.0&format=swagger
AZURE_PRIMARY_KEY=[[YOUR_KEY]]
use GuzzleHttp\Client;
public function learn () {
$client = new Client([
'base_uri' => env('AZURE_BASE'),
'timeout' => 2.0,
]);
$headers = [
'Authorization' => 'Bearer ' .env('AZURE_PRIMARY_KEY'),
'Accept' => 'application/json',
'Content-Type' => 'application/json'
];
$data = $this->test_data();
$body = json_encode($data);
$response = $client->request('POST', env('AZURE_URL'), [
'headers' => $headers,
'body' => $body
]);
return $response;
}
As other answers have noted, the data setup is very touchy. new \stdClass is the key here, as we need to end up with a JSON Object ({}) not an array ([]). stdClass creates that empty object for us.
function test_data () {
return array(
'Inputs'=> array(
'input1'=> array(
[
'DESC' => "",
'2-week-total'=> "1",
'last-week'=> "1",
'this-week'=> "1",
'delta'=> "1",
'normalized delta'=> "1",
'delta-percent'=> "1",
'high-total-delta'=> "1",
'high-total-amt'=> "1",
'role'=> ""
]
),
),
'GlobalParameters'=> new \stdClass,
);
}
Now when you call ->learn(), you'll get back some nice JSON to do what you need.
I'm trying to perform a cURL request to google calendar api using their guide, that says:
POST https://www.googleapis.com/calendar/v3/calendars/{name_of_my_calendar}/events?sendNotifications=true&pp=1&key={YOUR_API_KEY}
Content-Type: application/json
Authorization: OAuth 1/SuypHO0rNsURWvMXQ559Mfm9Vbd4zWvVQ8UIR76nlJ0
X-JavaScript-User-Agent: Google APIs Explorer
{
"start": {
"dateTime": "2012-06-03T10:00:00.000-07:00"
},
"end": {
"dateTime": "2012-06-03T10:20:00.000-07:00"
},
"summary": "my_summary",
"description": "my_description"
}
How am I supposed to do that in php? I wonder what parameters I should send and what constants I should use. I'm currently doing:
$url = "https://www.googleapis.com/calendar/v3/calendars/".urlencode('{name_of_my_calendar}')."/events?sendNotifications=true&pp=1&key={my_api_key}";
$post_data = array(
"start" => array("dateTime" => "2012-06-01T10:00:00.000-07:00"),
"end" => array("dateTime" => "2012-06-01T10:40:00.000-07:00"),
"summary" => "my_summary",
"description" => "my_description"
);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, 1);
// adding the post variables to the request
curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);
$output = curl_exec($ch);
curl_close($ch);
but the response is:
{
error: {
errors: [
{
domain: "global",
reason: "required",
message: "Login Required",
locationType: "header",
location: "Authorization"
}
],
code: 401,
message: "Login Required"
}
}
How should I format my parameters?
I noticed this question is asked quite some time ago, however after figuring out the post-parameter problem after some time I thought it might be useful to others to answer it. First within '$post_data', I switched the 'start' and 'end':
$post_data = array(
"end" => array("dateTime" => "2012-06-01T10:40:00.000-07:00"),
"start" => array("dateTime" => "2012-06-01T10:00:00.000-07:00"),
"summary" => "my_summary",
"description" => "my_description"
);
Secondly, I figured Google Calendar API expected the data to be json, so in curl_setopt:
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($post_data));
This worked perfectly for me, hope it's useful to someone else as well!