I am attempting to do an API call to the following: https://learn.microsoft.com/en-us/partner-center/develop/get-a-price-sheet To get a price sheet for a given market and view. But i can not make it work.
I got a token using https://login.microsoftonline.com/x/oauth2/token
But when I try to call the following API: https://api.partner.microsoft.com/v1.0/sales/pricesheets(Market='be',PricesheetView='updatedlicensebased')/$value
I get a
401, "Unauthorized: Invalid Authorization header"
Can someone give me some advice to what could be the problem? Thanks.
in your POST request to https://login.microsoftonline.com/x/oauth2/token you should use a 'resource' => 'https://api.partner.microsoft.com'.
This PHP code works for me:
public static function getTokenFromCode($code){
$data = array(
'resource' => 'https://api.partner.microsoft.com',
'client_id' => $appId,
'code' => $code,
'redirect_uri' => $redirectURL,
'grant_type' => 'authorization_code',
'client_secret' => $appKey
);
$header = array(
'Accept: application/json',
'return-client-request-id: true',
'Expect: 100-continue'
);
$token = self::callApi("POST", 'https://login.microsoftonline.com/'.$accountId."/oauth2/token", $header, $data);
return $token;
}
public static function getNcePriceList($timeline = "current"){
$header = array(
'Authorization: Bearer '.$token['access_token'],
'Host: api.partner.microsoft.com',
);
return self::callApi("GET", "https://api.partner.microsoft.com/v1.0/sales/pricesheets(Market='DE',PricesheetView='updatedlicensebased')/\$value?timeline=".$timeline, $header);
}
Related
We are getting the following error when executing this:
[description] => Authentication values are missing [code] => 1001
Can anyone see what I am doing wrong.
I tried removing the base64_encode function but this didn't have any impact.
I got the integration key and password from opayo (sagepay) - the test environment.
My php code follows:
$key = base64_encode("My Integration Key");
$password = "My Integration Password";
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_URL => "https://pi-test.sagepay.com/api/v1/merchant-session-keys",
CURLOPT_RETURNTRANSFER => true,
CURLOPT_SSL_VERIFYPEER => false,
CURLOPT_SSL_VERIFYHOST => false,
CURLOPT_CUSTOMREQUEST => "POST",
CURLOPT_POSTFIELDS => '{ "vendorName": "MY VENDOR" }',
CURLOPT_HTTPHEADER => array(
"Authorization: Basic $key:$password",
"Cache-Control: no-cache",
"Content-Type: application/json"
)
));
$response = curl_exec($curl);
$response = json_decode($response, true);
$err = curl_error($curl);
curl_close($curl);
Tia for any help
Both the key and password had to be base 64 encoded.
ie $key = base64_encode("My Integration Key:My Integration Password");
and then fed in to the curl http header as
"Authorization: Basic $key",
I had the same issue, so created a NuGet package for this API-client code: https://github.com/joeratzer/opayo-admin-and-reporting-api-client.
You can find the NuGet package here:
https://www.nuget.org/packages/Joe.Opayo.Admin.Api.Client/1.1.0
The client app allows code like this:
var client = new OpayoAdminApiClient();
var isTest = true;
var request = new OpayoApiRequest(ApiCommandType.GetTransactionDetail, "password", isTest, "user-name", "vendor-name");
var commandSpecificXml = "<vendortxcode>01Jan2010Transaction12345</vendortxcode>";
return await client.ProcessApiCommandAsync<TransactionDetail>(request, commandSpecificXml);
I'm getting data from an external API source.
Im using this to retrieve my orders
$data = Http::get(
$this->URL .'orders?language=nl_NL&limit=100&format=json&status_changed_start_date='
. $last_poll
. '&ordering=asc&partner_token='.$this->PARTNERKEY.'&token='.$this->MERCHANTTOKEN.''
)->json();
following the guide on the partner site I should use this format to update a specific record.
curl -X PATCH $this->URL ."orders/2?language=nl_NL&format=json&override_minimum=false&override_stock=false&mutate_stock=true&partner_token='.$this->PARTNERKEY.'&token='.$this->MERCHANTTOKEN.'" \
-H "accept: application/json" \
-H "Content-Type: application/json" \
-d "{\"status\":2,\"archived\":true,\"comments\":{\"internal\":\"Owner's commentary\"}}"
How would I implement this within a Laravel controller ?
Use the HTTP Client provide by Laravel:
use Illuminate\Support\Facades\Http;
use Illuminate\Http\Request;
class MyController
{
public function update (Request $request)
{
// Maybe use from $request?
$id = 2;
Http::patch($this->url . "/orders/" . $id, [
'version' => 1,
'order_number' => 2,
'language' => 'nl_NL',
'format' => 'json',
'override_minimum' => false,
// .. put here the other parameters
]);
}
}
Hi Here is my final code.
this seems to be working as I needed
$client = new Client([
// Base URI is used with relative requests
'base_uri' => $this->URL,
]);
$response = $client->request('PATCH', 'orders/' . $item['number'] .'?language=nl_NL&format=json&override_minimum=false&override_stock=false&mutate_stock=true&partner_token='.$this->PARTNERKEY.'&token='.$this->MERCHANTTOKEN, [
'json' => [
'status' => 2,
'archived' => true,
'comments' => ['internal' => $comment]],
]);
I have a POST request with Guzzle like this:
// Return a collection
$cart = $this->getCart('2019-10-08 07:08:39');
//Return first entry of the collection with first()
$template = $this->getTemplate($config->key);
$isDetail = null;
foreach ($cart as $item) {
try {
$client = $this->getClient();
$headers = ['Content-Type' => 'application/json'];
$body = [
'user_id' => $item->mystore_user_id,
'title' => $template->title,
'message' => $template->message,
'avatar' => $template->avatar,
'detail_id' => $isDetail,
'schedule' => null
];
print_r($body);
$response = $client->post('push-noti/unicast', $headers, $body);
print_r(response()->json(json_decode($response->getBody(), true)));
} catch (QueryException | \Exception $ex) {
echo "Error!";
}
}
My body variable value is exist in each loop when it printed. But when I use it in $client->post, my request return error with user_id, title, message is required. I really don't know why is it?
Can you tell me what's wrong in my code?
Thank you!
Try
$response = $client->post('push-noti/unicast', ['body' => $body , 'headers' => $headers]);
If you are calling a third party API, replace push-noti/unicast with complete URL.
I have a controller through which I send data to my local environment of the api platform (which is running fine)
/**
* Creates a new Location entity.
*
*/
public function createAction(Request $request)
{
$this->get("suvya_breadcrumbs.factory")->update('New Hub');
$form = $this->createForm(HubType::class);
$form->handleRequest($request);
$new_url = $this->generateUrl('new_hub');
$redirect_url = $this->generateUrl('home');
if ($form->isSubmitted() && $form->isValid()) {
$client = new Client([
'base_uri' => 'http://127.0.0.1:8000',
]);
$response = $client->request('POST', '/hubs', [
'form_params'=> $form->getData(),
'headers' => [
'Accept' => 'application/ld+json',
'Content-Type'=> 'application/json',
'Authorization'=> 'eyJhbGciOiJSUzI1NiJ9.eyJyb2xlcyI6WyJST0xFX1VTRVIiXSwidXNlcm5hbWUiOiJhZG1pbiIsImlhdCI6MTUxNzg3NjE1NCwiZXhwIjoxNTE3ODc5NzU0fQ.gIG9lueJJZxzkOl8qblhHWwiJvW97m4gz1-1mYeM9SgMzMW35Wh6XamOOYiISDN99yJ6Ovo-wKk6whpE5UGMDVw_wGek003Dd6r-Y7Ql3kVLHksn2JFzhAN3GwlXFcOI4MIjmq5qBhkzv21pHymO0yn1SlzWBwb0O7WygywefMu5p09zGuvAiP9I2ShyQLZhjj8bB_odf3dI-Ql0ZbRmn_JDkDoPcm5U11i-3S1oMikBmFq0WtTcWo7vezt3QdA3bY4_bgaISINAiYRR-_cvjpBSqFSE6n1ZYtHvKFn-98wXXsBGxEAoZw6iQL4iRgOI8F_uaiCo0eRHC7q0_xQ_V_W0-5XDIQXWDwoiVaUXnjO6xo2Fldp7PLO1ueJz1e4wiOy2-TunZdc8UCtw2BdFIQtWatPLi_v_rsNvF2H-6hwa9UOKEi9Z4tH4KkuATbXAxxfkCbSOyY1SAWP0riooPQi_AI2J7L2Ly86eAuKo1Hix3EuEogo19GSyBz_cCWczyERQWM9gikuUs8E22SIAdxTl8ZLFaXgiZIibDvb8pqcN8izFjywWbF2CkyWC58WxrVd6Bfmfnm7k9T6oZqwIZ-TQR-SbRnUHN1hpWUjFCk-tHhgvh7osHXmxe3grzA8M3LPBpQGQiTeqBZFMjF4Tx8zW2tuiEn6TwhV14Lj24Vc'
]
]);
die();
}
return $this->render('SuvyaFabricsCloudBundle:Common:basic.html.twig', array(
'form' => $form->createView(),
'page_title'=> 'Hub aanmaken',
'action_path' => $new_url,
'cancel_path'=> $redirect_url,
'submit_button_title' => 'Opslaan',
));
}
But unfortunately i'm getting an error in my dev.log of the api environment:
[2018-02-06 02:32:37] request.INFO: Matched route "api_hubs_post_collection". {"route":"api_hubs_post_collection","route_parameters":{"_controller":"api_platform.action.post_collection","_format":null,"_api_resource_class":"AppBundle\\Entity\\Hub","_api_collection_operation_name":"post","_route":"api_hubs_post_collection"},"request_uri":"http://127.0.0.1:8000/hubs","method":"POST"} []
[2018-02-06 02:32:37] request.CRITICAL: Uncaught PHP Exception Symfony\Component\Serializer\Exception\UnexpectedValueException: "Syntax error" at /Users/myname/Sites/suvyalogistics-api/vendor/symfony/symfony/src/Symfony/Component/Serializer/Encoder/JsonDecode.php line 78 {"exception":"[object] (Symfony\\Component\\Serializer\\Exception\\UnexpectedValueException(code: 0): Syntax error at /Users/myname/Sites/suvyalogistics-api/vendor/symfony/symfony/src/Symfony/Component/Serializer/Encoder/JsonDecode.php:78)"} []
The output of form->getData():
array (size=4)
'postalCode' => string 'sdfdsf' (length=6)
'streetName' => string 'sdfsdf' (length=6)
'doorNumber' => string 'sdfsfd' (length=6)
'city' => string 'sdfsfd' (length=6)
Running the endpoint at the api platform with the same values goes fine as well.
Does anyone of you has an idea why this goes wrong?
You're sending a payload encoded in application/x-www-form-urlencoded (HTML form like) to the API Platform API, while, according to the headers you've set, it excepts data encoded in JSON.
To encode the data of the form in JSON, you can use the following Guzzle snippet:
$client = new Client([
'base_uri' => 'http://127.0.0.1:8000',
]);
$response = $client->request('POST', '/hubs', [
'json' => $form->getData(),
'headers' => [
'Accept' => 'application/ld+json',
'Authorization'=> '...'
]
]);
Alternatively, you can configure API Platform to accept form data, but I would not recommend going this way (it's better to only deal with JSON API-side).
I have been trying to update a field on a customer information via the REST API using this link format:
http://<magentohost>/api/rest/customers
But to I am getting a customer email already exist
How can I update information via REST API..
Sample Code:
$productData = json_encode(array(
'id' => 1,
'firstname' => 'Ted',
'lastname' => 'Mosbius',
'website_id'=> 1,
'group_id' => 1,
'email' => 'ted#mosbis.com'
));
$headers = array('Content-Type' => 'application/json');
$oauthClient->fetch($resourceUrl, $productData, OAUTH_HTTP_METHOD_POST, $headers);
// $oauthClient->fetch($resourceUrl);
$productsList = json_decode($oauthClient->getLastResponse());
print_r($productsList);
In this code, email exist, id exist , website_id exist and group_id exist... I just wanted to update the firstName and lastName
Thanks in advance
Just found the problem, I need to use PUT instead of POST when updating based from this link (http://ajaxpatterns.org/RESTful_Service)...
$productData = json_encode(array(
'id' => 1,
'firstname' => 'Ted',
'lastname' => 'Mosbius',
));
$headers = array('Content-Type' => 'application/json');
$oauthClient->fetch($resourceUrl, $productData, OAUTH_HTTP_METHOD_PUT, $headers);
$productsList = json_decode($oauthClient->getLastResponse());
print_r($productsList);
Hopefully this will help someone in the future... :)
Errors do come up less the header is formed like this:
$headers = array('Content-Type' => 'application/json', 'Accept' => '*/*');