woocommerce subscription API - wordpress

I am using Woocomemrce REST API to connect with my site. Everything works fine when it comes to orders but it is not working with subscriptions. I have tried following code to get subscriptions but it is giving "Error: No route was found matching the URL and request method [rest_no_route]"
$woocommerce = new Client(
'https://www.example.com',
'ck_OUR_CONSUMER_KEY',
'cs_OUR_CONSUMER_SECRET',
[
'wp_api' => true,
'version' => 'wc/v2',
]
);
try {
print_r($woocommerce->get('orders')); //this works and fetch orders
print_r($woocommerce->get('subscriptions')); //but this does not work
} catch (HttpClientException $e) {
echo $e->getMessage(); // Error message.
echo $e->getRequest(); // Last request data.
echo $e->getResponse(); // Last response data.
}
Can anyone help me sort out this issue. Thank You.

I changed it to the following it worked for me.
$woocommerce = new Client(
'https://www.example.com',
'ck_OUR_CONSUMER_KEY',
'cs_OUR_CONSUMER_SECRET',
[
'wp_api' => true,
'version' => 'wc/v1',
]
);

Related

Ninja Forms server-side validation not working

I have spent two days trying to figure this out. I have wordpress page with a four field Ninja Form. One of the fields is an Email. I created an API (in our .NET Core project) that checks and then throws a 400 error if a already with that email address exists in our DB. I am using the Ninja Forms Webhook feature to submit the form to my API. I just want to display my 400 error message to the user.
I am using the documentation below from Ninja Forms but it is not working:
https://developer.ninjaforms.com/codex/custom-server-side-validation/
More specifically, I am getting a 500 with the the following error in the console:
Uncaught Error: Call to undefined function my_nf_validation() in \/home\/site\/wwwroot\/wp-content\/themes\/hello-elementor\/functions.php:245\nStack trace:\n#0 \/home\/site\/wwwroot\/wp-includes\/class-wp-hook.php(287): {closure}(Array)\n#1 \/home\/site\/wwwroot\/wp-includes\/plugin.php(206): WP_Hook->apply_filters(Array, Array)\n#2 \/home\/site\/wwwroot\/wp-content\/plugins\/ninja-forms\/includes\/AJAX\/Controllers\/Submission.php(132): apply_filters('ninja_forms_sub...', Array)\n#3 \/home\/site\/wwwroot\/wp-includes\/class-wp-hook.php(287): NF_AJAX_Controllers_Submission->submit('')\n#4 \/home\/site\/wwwroot\/wp-includes\/class-wp-hook.php(311): WP_Hook->apply_filters('', Array)\n#5 \/home\/site\/wwwroot\/wp-includes\/plugin.php(478): WP_Hook->do_action(Array)\n#6 \/home\/site\/wwwroot\/wp-admin\/admin-ajax.php(175): do_action('wp_ajax_nf_ajax...')\n#7 {main}\n thrown<\/pre>"},"last":{"type":1,"message":"Uncaught Error: Call to undefined function my_nf_validation() in \/home\/site\/wwwroot\/wp-content\/themes\/hello-elementor\/functions.php:245\nStack trace:\n#0 \/home\/site\/wwwroot\/wp-includes\/class-wp-hook.php(287): {closure}(Array)\n#1 \/home\/site\/wwwroot\/wp-includes\/plugin.php(206): WP_Hook->apply_filters(Array, Array)\n#2 \/home\/site\/wwwroot\/wp-content\/plugins\/ninja-forms\/includes\/AJAX\/Controllers\/Submission.php(132): apply_filters('ninja_forms_sub...', Array)\n#3 \/home\/site\/wwwroot\/wp-includes\/class-wp-hook.php(287): NF_AJAX_Controllers_Submission->submit('')\n#4 \/home\/site\/wwwroot\/wp-includes\/class-wp-hook.php(311): WP_Hook->apply_filters('', Array)\n#5 \/home\/site\/wwwroot\/wp-includes\/plugin.php(478): WP_Hook->do_action(Array)\n#6 \/home\/site\/wwwroot\/wp-admin\/admin-ajax.php(175): do_action('wp_ajax_nf_ajax...')\n#7 {main}\n thrown","file":"\/home\/site\/wwwroot\/wp-content\/themes\/hello-elementor\/functions.php","line":245}},"debug":[]}
I placed the code in the function.php file in Themes Editor. This is my first time working with wordpress so I hope I am doing this right. This is my code and is taken directly from the above documentation:
add_filter( 'ninja_forms_submit_data', function( $form_data ){
if( ! my_nf_validation( $form_data ) ) { // Add check here.
$errors = [
__( 'An unexpected error occurred.', 'my-plugin' )
];
$response = [
'errors' => $errors,
];
echo wp_json_encode( $response );
wp_die(); // this is required to terminate immediately and return a proper response
}
// If no errors, be sure to return the $form_data.
return $form_data;
});
I would really appreciate anyone's help with this.
Try the following Code, It will work.
function validateCode($field){
if( checkCondition ){
// let it go
return true;
}
else{
return false;
}
}
add_filter( 'ninja_forms_submit_data', 'my_ninja_forms_submit_data' );
function my_ninja_forms_submit_data( $form_data ) {
$form_settings = $form_data[ 'settings' ]; // Form settings.
if($form_data['id'] == '2'){
foreach( $form_data[ 'fields' ] as $field ) { // Field settigns, including the field key and value.
if( 'unique_code' == $field[ 'key' ] ){
if(!validateCode($field)){
$form_data['errors']['fields'][$field['id']] = "INVALID CODE";
}
}
}
}
return $form_data;
}
The documentation references a custom WordPress filter, as defined by the Ninja Forms plugin. Filters are a feature of WordPress Hooks, which allow a theme or plugin to modify the functionality of another theme or plugin. See https://developer.wordpress.org/plugins/hooks/filters/
To your question, the Webhooks add-on plugin (an official extension of Ninja Forms) is not required to use the filter that you reference from the documentation.
Instead, you'll need to replace "my_nf_validation()" with your own defined function, as the documentation shows an example.
Your function needs to handle the API request and response handling. In the documentation example, the custom function returns a Boolean value.

401(woocommerce_api_user_cannot_read_product) response--Woocommerce REST API

the API works when ck_ and cs_ keys are for Admin and returns the std class object but when keys are for a different user returns You do not have permission to read this product 401(woocommerce_api_user_cannot_read_product) Error response: even when user has read/write privileges. but goes ahead to create the product in the database. Any help on this issue is highly appreciated
require_once( 'lib/woocommerce-api.php' );
$options = array(
'debug' => true,
'return_as_array' => false,
'validate_url' => false,
'timeout' => 30,
'ssl_verify' => false,
);
try {
$client = new WC_API_Client( $the_url, 'ck_xxxx', 'cs_xxxx', $options);
Try adding into your $options array:
$options['query_string_auth'] = true;
As noted in the documentation this will "Force Basic Authentication as query string true" in other words it will append your consumer key and consumer secret to your request URL as a query string. This is only supported on HTTPS.

Facebook post wirth php error: (#200) The user hasn't authorized the application to perform this action

i want to post from my website to my facebook site. i have created a app for my site. I use this code (i replace data from my app with '[]'):
require_once 'lib/php-graph-sdk-5.4/src/Facebook/autoload.php';
// initialize Facebook class using your own Facebook App credentials
// see: https://developers.facebook.com/docs/php/gettingstarted/#install
$access_token = '[aaccesstoken]';
$config = array();
$config['app_id'] = '[appid]';
$config['app_secret'] = '[appsecret]';
$config['fileUpload'] = false; // optional
$fb = new \Facebook\Facebook($config);
// define your POST parameters (replace with your own values)
$params = array(
"access_token" => $access_token, // see: https://developers.facebook.com/docs/facebook-login/access-tokens/
"message" => "Test Message",
"link" => "http://www.frauen-styles.de",
"picture" => "http://www.frauen-styles.de/site/assets/files/3545/20.jpg",
"name" => "Test Name",
"caption" => "Caption",
"description" => "Beschreibung"
);
// post to Facebook
// see: https://developers.facebook.com/docs/reference/php/facebook-api/
try {
$ret = $fb->post('/me/feed', $params);
echo 'Successfully posted to Facebook';
} catch(Exception $e) {
echo $e->getMessage();
}
what i'm doing wrong? im administrator of the page. support tells me that no publish_pages is requiered for the app for admins. I only want to send a post from my website to my facebook-page.
support tells me that no publish_pages is requiered
As you can read in the API reference in the official docs, you do need publish_pages and manage_pages to post to a Page (as Page).
Docs: https://developers.facebook.com/docs/graph-api/reference/page/feed#publish

External request to Wordpress WP-API - Basic Authentication

I'm trying to hit my Wordpress API using Basic Auth with Guzzle (http tool) from my middleware (Laravel).
$username = 'myAdminUserName';
$password = 'myAdminPassword';
$uri = 'https://example.com/wp-json/mysite-api/cleared-action';
$response = $this->guzzle->put(
$uri,
[
'headers' => [
'Authorization' => 'Basic ' . base64_encode( $username . ':' . $password )
],
'body' => [
'user_id' => $wordpressId //passed into this function
]
]
);
It then hits the route set up in my Wordpress API
$routes['/mysite-api/cleared-action'] = array(
array(array($this, 'automatedClearing'), WP_JSON_Server::ACCEPT_JSON
| WP_JSON_Server::CREATABLE
| WP_JSON_Server::EDITABLE)
);
However that is as far as it gets. It does not hit my automatedClearing endpoint which looks like this
public function automatedClearing() {
global $container;
\Groups_User_Group::create( array('user_id' => 2903, 'group_id' => 13));
$mySiteServices = $container['services'];
$this->$mySiteServices->sendClearedEmail(2903); //2903 = user_id
}
I've used hardcoded values for the users ID.
I keep getting a 200 response from my call, so it definitely hits the route, but does not execute the endpoint. The response is basically just an empty one.
My Wordpress access.log shows the route being hit, but my error.log doesn't show anything. By the way, this is a laravel Homestead (vagrant) box hitting a Wordpress vagrant box.
I'm wondering if this is because the WP-API requires a nonce? But I thought nonce was only needed within Wordpress, whereas this is an external app hitting Wordpress.
I'm pretty stuck on this. Any guidance is greatly appreciated
Try to test it using postman ... if this works via postman then you have the problem with laravel or guzzle

Edit include/mail.inc, add my own SMTP setting there

The following function is contained in include/mail.inc of Drupal6, it uses the default SMTP settings buried in a file named "php.ini" to send mail.
function drupal_mail_send($message) {
// Allow for a custom mail backend.
if (variable_get('smtp_library', '') && file_exists(variable_get('smtp_library', ''))) {
include_once './'. variable_get('smtp_library', '');
return drupal_mail_wrapper($message);
}
else {
$mimeheaders = array();
foreach ($message['headers'] as $name => $value) {
$mimeheaders[] = $name .': '. mime_header_encode($value);
}
return mail(
$message['to'],
mime_header_encode($message['subject']),
// Note: e-mail uses CRLF for line-endings, but PHP's API requires LF.
// They will appear correctly in the actual e-mail that is sent.
str_replace("\r", '', $message['body']),
// For headers, PHP's API suggests that we use CRLF normally,
// but some MTAs incorrecly replace LF with CRLF. See #234403.
join("\n", $mimeheaders)
);
}
}
but I use shared host, therefore i can't edit php.ini, i want to edit the above function "drupal_mail_send", add the codes below into that function so that it can bypass the PHP mail() function and send email directly to my favorite SMTP server.
include('Mail.php');
$recipients = array( 'someone#example.com' ); # Can be one or more emails
$headers = array (
'From' => 'someone#example.com',
'To' => join(', ', $recipients),
'Subject' => 'Testing email from project web',
);
$body = "This was sent via php from project web!\n";
$mail_object =& Mail::factory('smtp',
array(
'host' => 'prwebmail',
'auth' => true,
'username' => 'YOUR_PROJECT_NAME',
'password' => 'PASSWORD', # As set on your project's config page
#'debug' => true, # uncomment to enable debugging
));
$mail_object->send($recipients, $headers, $body);
Could you write down the modified code for my reference?
The code in drupal_mail_send is part o the Drupal core functionality and should not be changed directly as your changes may be overwritten when you update Drupal.
Modifications of Drupal core files is often referred to by the Drupal community as "hacking core" and is largely discouraged.
Drupal already has a number of modules available which may help you. See:
http://drupal.org/project/phpmailer module:
Adds SMTP support for sending e-mails using the PHPMailer library.
Comes with detailed configuration instructions for how to use Google
Mail as mail server.
http://drupal.org/project/smtp module:
This module allows Drupal to bypass the PHP mail() function and send
email directly to an SMTP server.

Resources