How to Set Xero Authorization Header Using wp_remote_post() - php

I am trying to use the Xero API to send an Invoice Email on my WordPress site. But I am unsure how to set the authorization header I have attempted the following:
$args = array(
'headers' => array(
'Content-Type: application/x-www-form-urlencoded',
'Authorization' => 'Basic ' . base64_encode('myClientID' . ':' . 'myClientSecret')
),
);
$response = wp_remote_post('https://api.xero.com/api.xro/2.0/Invoices/2dfa4120-1fd2-4e67-927e-c16ac821226c/Email', $args);
print_r($response);
This gives me a response of 404 unauthorized. Is there something I'm missing or doing wrong?

the Authorization header actually requires a valid access_token be set, not the id / secret combo. You can read more about the code flow required to get a token here: https://developer.xero.com/documentation/oauth2/auth-flow
If you familiar with PHP you can look through code in the PHP SDK sample app here: https://github.com/XeroAPI/xero-php-oauth2-app
Is your goal to send that invoice email to a dynamic organisation, or simply send an invoice from your own personal org?
Fortunately (or unfortunately) early next year we will have the option for this embedded access_token - but if you wanted to set this up in the interim you will need to generate an access token from a user flow, and then setup the backend mechanism to have it be refreshed prior to usage which I explain in this youtube vid: https://www.youtube.com/watch?v=Zcf_64yreVI
More about "machine 2 Machine" integrations aka the client_credentials OAuth2.0 grant
https://developer.xero.com/announcements/custom-integrations-are-coming/

Related

Walmart MX Marketplace Acknowledge Order API Issue

I am working on Walmart integration to my own web application using PHP. When I tried to acknowledge my Mexico orders, I got an empty response. The data type of response is string with 0 length, error code 400. It looks like my credentials are good. Is "https://marketplace.walmartapis.com/v3/orders/{PurchaseOrderId}/acknowledge" a valid API url?
$url="https://marketplace.walmartapis.com/v3/orders/P108915403/acknowledge";
$ch = curl_init();
$qos = uniqid();
$options = array(
CURLOPT_URL => $url,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_TIMEOUT => 60,
CURLOPT_HEADER => false,
CURLOPT_POST =>1,
CURLOPT_HTTPHEADER => array(
"WM_SVC.NAME: Walmart Marketplace",
"WM_QOS.CORRELATION_ID: $qos",
"Authorization: Basic $authorization",
"WM_SEC.ACCESS_TOKEN:$token",
"Accept: application/json",
"Content-Type: application/json",
"WM_MARKET: mx",
),
);
curl_setopt_array($ch, $options);
$response = curl_exec($ch);
var_dump($response);
Code Snippet
After putting it aside for a few months, today I picked it up and finally got it resolved luckily and got a 202 Accepted Response with empty content(Walmart's documentation says the response to a successful call contains the acknowledged order, but it actually contains nothing except for 202 Accepted code).
When I tried to acknowledge my Mexico orders, the response is actually not empty. The header contains error message: http code 400 Bad Request. I confirmed that it is due to wrong payload structure after testing.
So "https://marketplace.walmartapis.com/v3/orders/{PurchaseOrderId}/acknowledge" is a valid API URL and is the same as US API. The difference between them is that MX site needs a well-structured payload through POST while US site does not(US API only needs an empty payload through POST).
The key point to a successful call is the structure of the payload. The structure should be like the samples in the documentation.
Pay attention to the details of the structure. Refer to the picture for the structure of payload here.
The "orderLine" and "orderLineStatus" should be declared as ARRAY instead of single element. And this is the reason why I failed to call the acknowledge API before.
Looks like you are using an old API, which has been discontinued, the same has been communicated late December 2020.
We have improved our onboarding experience with following steps:
 
Create an account on Walmart IO platform - https://walmart.io by clicking on the user icon just before the search box.        
Login to the account and accept "Terms of Use"
Click on "Create Your Application" to create a new application and fill in appropriate details.        
Use this tutorial to generate two sets of public/private keys - https://walmart.io/key-tutorial       
* One set will be used for production.        
* Other set will be used for stage.
Upload both public keys using - https://walmart.io/key-upload?app_name=<your app name>      
Consumer ID will be generated for both sets for prod and stage which can be seen on the dashboard - https://walmart.io/userdashboard 
Click on "Request Access" for Checkout APIs at https://walmart.io/reference  and fill out the form. 
Once the access is approved, documentation will be available for integrating with Commerce API through Walmart I/O.
We will send out client secrets for stage and prod as soon as they’re ready.
 
Thanks,
Firdos
IOSupport

go through browser auth with rest requests - Gmail API

I would like to send email messages with our corporate emails provided by Gmail. In order to do that, I would like to use Gmail API with rest commands (basically launched with a php procedural code, for legacy purpose).
I have that code :
I go to this url :
// https://accounts.google.com/o/oauth2/auth?client_id=my_client_id&redirect_uri=urn:ietf:wg:oauth:2.0:oob&scope=https://www.googleapis.com/auth/gmail.send&response_type=code
// and obtain a token like that : 4/1AX4XfWgmW0ZdxXpJn8YzkVeDs3oXZUHyJcR7abE2TuqQrcmo4c1W02ALD4I
/*
echo GoogleAuthCurl("GET", '', array(
'client_id' => $GOOGLE_CLIENT_ID,
'redirect_uri'=>'urn:ietf:wg:oauth:2.0:oob',
'scope' => 'https://www.googleapis.com/auth/gmail.send',
'response_type' => 'code'
), array());
then I can use requests in curl for getting my access token :
curl \
--request POST \
--data "code=[Authentcation code from authorization link]&client_id=[Application Client Id]&client_secret=[Application Client Secret]&redirect_uri=urn:ietf:wg:oauth:2.0:oob&grant_type=authorization_code" \
https://accounts.google.com/o/oauth2/token */
$tokenJson = json_decode( GoogleTokenCurl("POST", '', array(), array(
'code' => '4/1AX4XfWiEWngRngF7qryjtkcOG1otVtisYpjHnej1E54Pujcrchef8REvdt0',
'client_id' => $GOOGLE_CLIENT_ID,
'client_secret' => $GOOGLE_CLIENT_SECRET,
'redirect_uri'=>'urn:ietf:wg:oauth:2.0:oob',
'grant_type' => 'authorization_code'
)
));
print_r($tokenJson);
This far, I've got food for my authorization header. My issue is in the first step (with the consent asked to user). I wish i can do this step without putting my url in the browser, validate two screens to grant access before getting the authorization code.
I'm also interested in advices to create gmail messages with rest requests driven by curl. I found postman collection about all actions gmail api can do, but one or two call examples wouldn't do harm ;)
thanks !
In the current state, by the method you are using, &response_type=code, you need two calls to the OAuth client to get the access token. You can find an example of how to handle it just using HTTP/REST requests here.
In any case, you could use Google API Client Library for PHP. Allows you to handle the OAuth authentication flow, only needing one interaction to get the token.
You can find a full example on how this works here, notice that this example uses the Drive API, if you want to use it within the Gmail API, you can check Gmail API PHP library.
Documentation:
PHP Gmail API
OAuth 2.0 to Access Google APIs

ebay sdk - retrieving orders and sync with external DB

I am struggling, literally, trying to figure out how to use th Ebay API in order to retrieve the orders received on a specific merchant account and then store some datas in an external DB.
I have registered to developer.ebay.it, I have built a key pair, both for production and sandbox, then I have tried the api (Browse/getItem)...and then...LOST.
I cannot use the Fullfillment, because I always get a response of Insufficient authorization, even if I create a token, even if I put a real order number... I don't get how to question the API.
Lastly, I am using PHP and I have downloaded the davidtsadler SDK from github. How do I configure an example of getOrder with that SDK? Do you have any link, suggestions, anything?
What I find on internet is not enough clear for my level of knowledge and almost nobody deals with the getOrder call.
Thank you for your help.
The ebay API documentation is fairly clear on how to perform a query:
If you wanted to get a specific Fullfillment policy, then you would need to perform a GET request to ebays Fullfillment API using the /order/{orderId} path - where {orderId} is a real order ID.
In PHP, that might go a little something like this:
/* Returns a JSON object containing an ebay order */
function getOrder($order_id, $auth_key){
$options = array(
'http' => array(
'method' => "GET",
'header' => "Authorization: Bearer ".$auth_key."\r\n" .
"Content-Type: application/json"
)
);
$context = stream_context_create($options);
$result = file_get_contents("https://api.ebay.com/sell/fulfillment/v1/order/".$order_id, false, $context);
return json_decode($result);
}
Then you could call the method above and retrieve an order using:
$order = getOrder("A REAL ORDER ID", "YOUR AUTH KEY");
The $order variable now holds a JSON object. You can print info from the object using: (This example prints the username associated with the order)
echo $order->buyer->username;
Finally, please note the direct quote from ebays documentation:
"eBay creates and displays an Application token. This token is valid for a limited time span. If you get an invalid token error when you make a call using this token, simply create a new token and use the new token in your call."

WordPress rest API OAuth curl commands

I have the WordPress rest API
and WordPress OAuth server setup plugins setup and am trying to authenticate using http://sevengoslings.net/~fangel/oauth-explorer/
every time the call content is not giving me the OAuth token or OAuth secret that I need.
I tried these steps
https://wordpress.org/support/topic/json-rest-api-from-mobile-app-with-authentication
1. Enter base url (http(s)://your.domain.com/oauth1
2. Access token = request
3. Authorize = authorize
4. Access_Token = access
5. Enter your consumer key and secret (leave method as HMAC-SHA1)
Click Get Request Token and you get Call content
I should get this in Call Content
Call content now =
oauth_token=xxxxxxxxxxxxxxx&oauth_token_secret=xxxxxxxxxxxxxxxxxxxxx&oauth_call_back_confirmed=true
But I only get this
page not found
Here they were not able to get 3-legged OAuth1 .0a to work so they used basic OAuth which requires another plugin and is not recommended for production.
Should I be using a different signature method?
I'm looking for two curl commands to get an OAuth grant from the server and another one to trade this grant for an access token+ refresh token.
I have got this to work and I'll outline how I have done this.
I'm using the Postman application to test and perfect the API calls. I highly advise using this. Once you have got the call working you can export to PHP Curl (or whatever you need).
If you use Postman you can view my API calls using this shared link.
For the First call you are having trouble with I have the following settings
First, I made sure my endpoint URL was:
{{url}}/oauth1/request
I set my API Call to PUSH and my AuthType to OAuth 1.0
I added my consumer_key and consumer_secret that I created in the WP Backend > Users > Applications (this is added with the OAuth plugin).
Signature Method - HSAC-SHA1
Then Postman will update this and dynamically create your Nonce, Timestamp and Version.
I set my Realm as 'Example'
I then made sure that I enabled the options:
- Add Params to header
- Add empty params to signature
Here is what I get for my params:
realm="Example",oauth_consumer_key="AdPuqyWrAQQc",oauth_signature_method="HMAC-SHA1",oauth_timestamp="1470248765",oauth_nonce="dnOTvG",oauth_version="1.0",oauth_signature="gUahTX2hfV1lqZCfMUvHtLLoauI%3D"
This provides me with the following output:
oauth_token=xbTb4E93K6pP2tcg4qGJIYgl&oauth_token_secret=qWo01WL2ish205yvjiU8qyCkKVPMNUvSbKpFBB1T1oOuOtBc&oauth_callback_confirmed=true
I can use Postman to export this API call to a cURL function and if so I get the following:
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_URL => "http://mydomain.dev/oauth1/request",
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => "",
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 30,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => "POST",
CURLOPT_POSTFIELDS => "-----011000010111000001101001\r\nContent-Disposition: form-data; name=\"oauth_consumer_key\"\r\n\r\nAdPuqyWrAQQc\r\n-----011000010111000001101001\r\nContent-Disposition: form-data; name=\"oauth_token\"\r\n\r\n\r\n-----011000010111000001101001\r\nContent-Disposition: form-data; name=\"oauth_signature_method\"\r\n\r\nHMAC-SHA1\r\n-----011000010111000001101001\r\nContent-Disposition: form-data; name=\"oauth_timestamp\"\r\n\r\n1470241356\r\n-----011000010111000001101001\r\nContent-Disposition: form-data; name=\"oauth_nonce\"\r\n\r\n7VKp4N\r\n-----011000010111000001101001\r\nContent-Disposition: form-data; name=\"oauth_version\"\r\n\r\n1.0\r\n-----011000010111000001101001\r\nContent-Disposition: form-data; name=\"oauth_signature\"\r\n\r\n9qRrIkDxt56S9Ikf061eFOVLAdA%3D\r\n-----011000010111000001101001--",
CURLOPT_HTTPHEADER => array(
"authorization: OAuth realm=\"Example\",oauth_consumer_key=\"AdPuqyWrAQQc\",oauth_signature_method=\"HMAC-SHA1\",oauth_timestamp=\"1470248765\",oauth_nonce=\"dnOTvG\",oauth_version=\"1.0\",oauth_signature=\"gUahTX2hfV1lqZCfMUvHtLLoauI%3D\"",
"cache-control: no-cache",
"content-type: multipart/form-data; boundary=---011000010111000001101001",
"postman-token: dd85258e-a72a-b731-82d1-00109e30962f"
),
));
$response = curl_exec($curl);
$err = curl_error($curl);
curl_close($curl);
if ($err) {
echo "cURL Error #:" . $err;
} else {
echo 'response ' . $response;
$a = parse_str($response);
echo 'token ' . $oauth_token;
echo '<br>';
echo 'secret '. $oauth_token_secret;
}
This is step 1 of a 3 step process for OAuth Authentication. I'm just starting out on my journey to connect them all. There is not much documentation out there and not many examples.
Step 2 looks like a call to /oauth1/authorize with the provided token and secret. This looks like it then requires a user login and a new (and permenant) token and secret is created.
Step 3 looks like a call to /oauth1/access
I haven't succesfully got Step 2 and Step 3 to link together correctly, but I thought I should post to help with the original query about the first step not returning the correct tokens
This article is one of the better ones out there explaining how to use WP-API and OAuth.

How to use facebook access_token

I´m building a facebook app with php,
everything works perfect, I do successful dialog auth
I have the short_live token
I generate the long_live_token and save it to some directory
what I want to do is that in canvas app the user selects some stuff and activates a mechanism that regularly posts stuff, this is why I save the token.
but what can I do with it?!
I find a lot about generating the access_token but nothing about how to use it!?
Where can I add it as parameter? What is the key?
example:
I´m using facebook sdk for php for post sth. to a wall like
$msg_body = array(
'message' => "wassup yo"
);
$facebook->api($uri, 'post', $msg_body );
but this only works if
$facebook->getUser();
is returning a user
how can I use my stored access_token to do the same?
I believe there is a function called "setAccessToken" in the Facebook PHP SDK. You would just need to set it with that function and it gets added to every call automatically.
Manual way:
$params = array(
'message' => 'wassup yo',
'access_token' => '[your-token]'
);
$facebook->api($uri, 'post', $params);
You could also do this with CURL, this would be an example URL;
$url = 'https://graph.facebook.com/' . $userId .
'/feed' .
'&access_token=' . $accessToken .
'&message=' . $userMessage;
Basically you just add the Access Token as a parameter like the message.
Just make sure you are using secure calls, see this article for an example of using CURL with the Facebook API and usage of "appsecrect_proof": http://www.devils-heaven.com/extended-page-access-tokens-curl/
IMPORTANT: Be sure that the message parameter is always 100% user generated without any prefilling (see Platform Policy) and keep in mind that you need to go through a review process with pulish_actions to make it available for other Users: https://developers.facebook.com/docs/apps/changelog

Categories