How can I use the Woocommerce REST API with plain permalinks? - permalinks

I want to make requests to the Woocommerce REST API to check the status and update products. My Wordpress install uses plain permalinks, because the frontend is built in React, which renders on the static homepage. Therefore I need all queries to be passed to the homepage, so that my React router can handle the request (If I set permalinks to pretty, the wordpress router will guide any request that's not the homepage and it won't reach the React router).
I'm using ssl and I set up a consumer key and secret. I can make requests successfully if I set permalinks to pretty. However, I need to make queries like this:
https://example.com/?rest_route=/wc/v3/products
I tried passing the consumer secret and key as extra parameters:
https://example.com/?rest_route=/wc/v3/products&consumer_key=xxx&consumer_secret=xxx
but this doesn't work. I also tried to pass them as headers in my manual curl request in php. I also tried to make the request using curl from the command line. All of these methods work when I use the approach outlined in the documentation using pretty permalinks, but with permalinks to plain they all cause 401 responses stating I'm not authenticated.
Is there any way around this, or do I just need to make custom endpoints?

The documentation (woocommerce.github.io) says:
To use the latest version of the REST API you must be using:
...
Default permalinks will not work.
(emphasis theirs)
For the "Legacy API" the following works:
mywebsite.com/index.php?wc-api-version=1&wc-api-route=/products/1234
From:
add_rewrite_rule( '^wc-api/v([1-3]{1})(.*)?', 'index.php?wc-api-version=$matches[1]&wc-api-route=$matches[2]', 'top' );
in
class-wc-legacy-api.php:80
WC_Legacy_API::add_endpoint()
If you wanted, you could register your own rewrite rule and inside it do something like:
$rest_server = rest_get_server();
$request = new WP_REST_Request( 'GET', '/wc/v3/products' );
$response = rest_do_request( $request );
return...

Related

WooCommerce create API webhook (POST method)

I would like to connect API but, to be honest I'm not so experienced in api connections, the API instructions are clear, but I don't know how to begin in WordPress (WooCommerce), my goal is check the response of sent request and pass them into creating new shop order post type.
URL which specified the API provider should be on our side like this: https://www.example.com/api/1/order/send
I think it can be good when I use piece code like this:
add_action('init', function() {
add_rewrite_rule(
'/heureka-marketplace-api/1/order/send/([^/]+)/?$',
'index.php?pagename=&my_subscribers=1&my_subscriber=$matches[1]',
'top'
);
});
But I don't know if this can be used and what should I pass into add_rewrite_rule() parameters exactly to make it work, and how I can check if the api provider sents the request and how I can took data of their request?
The add_rewrite_rule() in init action was picked from some example of developer wordpress function reference.

How to send POST request to Wordpress website and do some actions

I am new to WordPress, what I want to do is to send POST request in JSON format to WordPress website and basis of that request I want to send an email.
what I want to know is...
endpoint to send request?
what functions or files will be use to handle post request
thanks.
One way is to do the following:
Create a blank page and remember slug (here test-mypost)
Create and add code to custom .php (page-test-mypost.php)
Have to be inside current theme (on same level as style.css ... root)
2.1. Add logic to page (test-mypost.php)
(eg: if request type is post and param1 is something then send mails)
Test page(yoursite/test-mypost)
Note: For how to write proper post request and send mail there are lot's of online docs very easy to find via a trivial search

Symfony - Target path is null on cURL like user request

I have an application with restricted access to the whole site, except for login and password recovery.
I'm trying to add to the login view open graph meta tags with data based on the referer address. To do that, I use the \Symfony\Component\Security\Http\Util\TargetPathTrait in the login action like this:
<?php
$referer = $this->getTargetPath($request->getSession(), 'main');
Locally, I use Open Graph Preview chrome add-on, and it works perfectly. As an anonymous user, I try to acces to a page, and then redirected to the login page. Here $referer is not null and I can retieve data I need to generate meta tags.
Now on test environment on my production server, with open graph chrome add-on, it still working. Share a link through Telegram, the preview is displayed as expected. But when I share the same link through Facebook messenger, I don't get what I want.
Edit: doesn't work with Discord and WhatsApp either.
I've made some test with the Facebook debugger, it appears that $referer is null and I don't understand why. It looks like Symfony access control have a particular behavior when a Facebook service try to see a page, as no session data seems to be manage by the symfony security components.
The login feature of the application is quite simple as it follows the basics step described in the Symfony documentation.
Is anyone has a clue on what can I do to fix that? Meanwhile, I'm trying to find a workaround with Symfony events.
EDIT 1: I reproduced the issue localy, with a cURL request. In that case it appears no session is handled. \Symfony\Component\Security\Http\Util\TargetPathTrait::getTargetPath method is useless as Symfony store the target path in session.
So now, when an anonymous user try to request a restricted URL, I add the referer as a GET parameter to the redirect login URL.
Cool thing, now the preview works perfectly on Discord, WhatsApp and still works on Telgram.
Sadly, it still doesn't work on Facebook's app (Messenger and Facebook posts).
So, I took a look on the facebook debugger tool. And here come the strange thing, the redirect url request by FB service is different than the one my application normally give.
Expected URL : https://domain.ext/login?referer=https://domain.ext/referer/path
URL requested by FB : https://domain.ext/login?randomCoherentParamName=intValue
The odd thing is that 'randomCoherentParamName' correspond to a route parameter from the referer URL.
Here how I generate the redirect URL:
<?php
// From a class that extends
// Symfony\Component\Security\Guard\Authenticator\AbstractFormLoginAuthenticator
/**
* Override to control what happens when the user hits a secure page
* but isn't logged in yet.
*
* #return RedirectResponse
*/
public function start(Request $request, AuthenticationException $authException = null)
{
$url = $this->urlGenerator->generate('loginRoute', ['referer' => $request->getUri()]);
return new RedirectResponse($url);
}
If anyone has a clue of what's going on, I will appreciate any advice :).
EDIT 2: It seems FB service use a canonical URL to access the login page when redirected. Problem is I never set the canonical address meta tag in any page on my website. So, I'm wondering how is it possible...
Anyway, I think I've got a solution to bypass this problem, I'll share if it works, but I really want to understand how FB service works and identify how it is able to get a canonical URL I've never set... Apach fault? Symfony fault? My Fault? Or is it related to the Facebook crawler ?
Any comment will be appreciate :)
Problem solved !
The Facebook issue was totally my fault, actually, and a bit because of FB service. Let me explain.
When FB service request a shared URL, it parses the response to find open graph meta tags. During response parsing, if the service detect an url open graph meta tag, it request that url and use the parsed data from that response to generate the preview. This behavior seems to be specific to Facebook, as I didn't have any issue with Discord, WhatsApp and Telegram (and Telegram handle session when it retrieve data from an URL).
Now, what did I do wrong ? Actually, my login page has an url open graph meta tag, and, well... I didn't generate the good URL as its value...
Thanks for your attention :)

Woocommerce REST API 401

similar question has been asked before however I am not sure if the proposed solutions can be applied in my case. I have generated consumerKey and consumerSecret as per the woocommerce api documentation. I have confirmed that I can get the results using these keys by calling the below url in the webbrowser:
https://mywebsite.com/wp-json/wc/v2/products?consumer_key=ck_blahblah&consumer_secret=cs_blahblah
However, when I execute the same api call in the postman, using GET and correctly replacing user-> consumerKey and pass -> consumerSecret I always get 401 : woocommerce_rest_cannot_view. I have tried both http and https with the same error. Any ideas?
Use this plugin https://github.com/WP-API/Basic-Auth and when you call the API use the Basic Authentication using the username and password.
Woo Commerce uses a diferent authentication method for HTTP and HTTPS.
So, if "HTTPS" = 1 is not being passed by Apache/Nginx to you code it will enforce the HTTP method.
Do a double check if this "HTTPS" is passed to your PHP:
Open the file: ./wp-includes/load.php
Search for "is_ssl"
Insert a "echo 'test_beg'; echo $_SERVER['HTTPS']; echo
'test_end';
Do a request on the API
If it return test_beg and test_end without "on" or "1" in the
middle, the HTTPS is not being passedList item
It can happen when using a reverse proxy, so, you could need to insert "SetEnvIf HTTPS on HTTPS=on" on your httpd.conf (if using Apache).
I hope it helps :)
(remember to delete these 'echo' on load.php)

Allocate a custom url for generated json data through wordpress plugin

I am writing a custom JSON API plugin (JSONAPI plugin is not working according to my requirements). I will generate JSON from queries but my question is how to access that JSON from url.
In other words.
* I am generating JSON by writing a wordpress plugin.
* I want to specify a URL for that generated JSON.
Ex:
Json : [jsondata] (generating from custom wordpress plugin).
when "www.yourwordpressblog.com/api/get_posts" is called my jsondata should come.
You can do this by hooking a function callback to the wp_ajax_* and wp_ajax_nopriv_ actions. When a request is made to the ajaxurl with the action parameter, the hooks will be called with the action appended. The rest of the data is accessible using $_POST and you are free to echo whatever you want back to the browser, including JSON. Make sure to set the Content-Type header if you aren't sending back HTML.
For a guide on how to do this please see Creating AJAX Functions in WordPress.

Resources