I have an online shop that uses woocommerce, wordpress.
We use a shared warehouse facilities of a firm that handles our products. They dont have a dedicated plugin for wordpress, but they sent me some API code that i have to inject in my site, in order to send them the order details to know what to goods to prepare.
They have sent me JS code
var myHeaders = new Headers();
myHeaders.append("SOAPAction", "http://tempuri.org/ImportOrders");
myHeaders.append("Content-Type", "text/xml; charset=utf-8");
var payload = "<SOAP-ENV:Envelope xmlns:SOAP-ENV=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:ns1=\"http://tempuri.org/\"><SOAP-ENV:Body> <ns1:ImportOrders> <ns1:livrare> <CrosspointInboundMessage> <Order> ... </Order> </CrosspointInboundMessage></ns1:livrare></ns1:ImportOrders></SOAP-ENV:Body></SOAP-ENV:Envelope>";
var requestOptions = {
method: 'POST',
headers: myHeaders,
body: payload
};
fetch("http://ws.qeops.ro/crosspointimportstandard.asmx?WSDL", requestOptions)
.then(response => response.text())
.then(result => console.log(result))
.catch(error => console.log('error', error));`
fetch("http://ws.qeops.ro/health", requestOptions)
.then(response => response.text())
.then(result => console.log(result))
.catch(error => console.log('error', error));
I need to use XML not json
Please see a sample remote get request when an order is placed successfully.
add_action( 'woocommerce_payment_complete', 'do_api_call' );
function do_api_call( $order_id ) {
$order = new WC_Order( $order_id );
$items = $order->get_items();
foreach ( $items as $item ) {
$product_id = $item[ 'product_id' ];
$product = new WC_Product( $product_id );
$name = $order->billing_first_name;
$surname = $order->billing_last_name;
$email = $order->billing_email;
$sku = $product->get_sku();
// API Callout to URL
$url = 'http://ws.qeops.ro/health';
$response = wp_remote_get( $url, array(
'headers' => array( 'Content-Type' => 'application/json; charset=utf-8' ),
'method' => 'GET',
'redirect' => 'follow',
'timeout' => 75,
'sku' => $sku,
"name" => $name,
"surname" => $surname,
"email" => $email,
)
);
}
}
Related
I am having big issues doing a POST request from wordpress backend.
This is the request I try to make. The AppsSCript is a doPost() endpoint echo-ing the request. It gives me a 400 error.
$body = array(
'firstName' => 'WhyWontYouWork'
);
$args = array(
'method' => 'POST',
'timeout' => 45,
'redirection' => 5,
//'httpversion' => '1.0',
'blocking' => true,
'headers' => array(
'Content-Type' => 'application/json'
),
'body' => $body
);
$request = wp_remote_post ($url, $args);
$response = wp_remote_retrieve_body( $request );
I found out with insomnia, that having a content-length header in the POST request is making Apps Script go crazy. If I remove it, all works.
Hope this helps,
$url = 'https://example.com/api/endpoint';
$args = array(
'method' => 'POST',
'timeout' => 30,
'headers' => array(
'Content-Type' => 'application/json',
),
'body' => json_encode( array( 'data' => 'value' ) ),
);
// Remove the Content-Length header
unset( $args['headers']['Content-Length'] );
// Or Change it
$args['headers']['Content-Length'] = 20166 // in decimal bytes
// Make the remote post request
$response = wp_remote_post( $url, $args );
// Check for errors
if ( is_wp_error( $response ) ) {
// Handle error
} else {
// Handle success
}
This is an extension for elementor pro forms that sends the form data to an API.
This first API will return a success or failure message.
If successful, the response will also contain an ID number.
That ID number should then be used in a second API request where the number is appended to the URL. This second API will return a login URL.
The plugin should then redirect the user to the returned URL.
Currently I am receiving a response from the first API. the response I've received is as follows:
{"code":201,"data":{"id":133714},"message":"Success"}
The second API Response I get is the following:
{"code": 200,"request_method":"GET","autologin":"https://www.exampleurl.com/login" }
But it is not redirecting the user. Can you help me discover why?
`
<?php
/*
Plugin Name: Elementor Custom form
Plugin URI:
Description:
Version:
Author:
Author URI:
License:
License URI:
*/
/*
This plugin adds a custom form action to Elementor Pro forms.
The new action sends an API Request to a custom endpoint.
After receiving a valid response, the form will send another API Request to a different endpoint.
The response from the second API Request is used to redirect the user to a different page.
*/
if ( ! defined( 'ABSPATH' ) ) {
exit; // Exit if accessed directly
}
class Bpd_Custom_Form_Action extends \ElementorPro\Modules\Forms\Classes\Action_Base {
public function get_name() {
return 'custom_form_action';
}
public function get_label() {
return __( 'Custom Form Action', 'elementor-pro' );
}
public function register_settings_section( $widget ) {
$widget->start_controls_section(
'section_custom_form_action',
[
'label' => $this->get_label(),
'condition' => [
'submit_actions' => $this->get_name(),
],
]
);
//////////////////////////////////////////////
//
// FIRST API - SETTINGS & AUTHORIZATION
//
//////////////////////////////////////////////
$widget->add_control(
'custom_form_action_api_url',
[
'label' => __( 'URL', 'elementor-pro' ),
'type' => \Elementor\Controls_Manager::TEXT,
'placeholder' => 'https://example.com/api/',
'description' => __( 'Enter the URL of the API endpoint you want to send the form data to.', 'elementor-pro' ),
'label_block' => true,
'separator' => 'before',
]
);
$widget->add_control(
'custom_form_action_application_token',
[
'label' => __( 'Application Token', 'elementor-pro' ),
'type' => \Elementor\Controls_Manager::TEXT,
'placeholder' => 'https://example.com/api/',
'label_block' => true,
'description' => __( 'Enter the application token for your API request.', 'elementor-pro' ),
'separator' => 'before',
]
);
//////////////////////////////////////////////
//
// FIRST API - Body & Response Options
//
//////////////////////////////////////////////
$widget->add_control(
'custom_form_action_api_body',
[
'label' => __( 'Body', 'elementor-pro' ),
'type' => \Elementor\Controls_Manager::TEXTAREA,
'placeholder' => '{ "name": "{{{ name }}}", "email": "{{{ email }}}" "ip": "{{{ USERIP }}}" }',
'description' => __( 'Enter the body of the API request. You can use the form fields as placeholders. For example: { "name": "{{{ name }}}", "email": "{{{ email }}}" }', 'elementor-pro' ),
'label_block' => true,
'separator' => 'before',
]
);
//////////////////////////////////////////////
//
// Second API - SETTINGS & AUTHORIZATION
//
//////////////////////////////////////////////
$widget->add_control(
'custom_form_action_second_api_url',
[
'label' => __( 'Second API URL', 'elementor-pro' ),
'type' => \Elementor\Controls_Manager::TEXT,
'placeholder' => 'https://example.com/thank-you/',
'description' => __( 'Enter the URL of the page you want to redirect the user to after the form is submitted.', 'elementor-pro' ),
'label_block' => true,
'separator' => 'before',
]
);
$widget->add_control(
'custom_form_action_second_application_token',
[
'label' => __( 'Second Application Token', 'elementor-pro' ),
'type' => \Elementor\Controls_Manager::TEXT,
'placeholder' => 'https://example.com/api/',
'label_block' => true,
'description' => __( 'Enter the application token for your API request.', 'elementor-pro' ),
'separator' => 'before',
]
);
$widget->end_controls_section();
}
public function register_form_action( $widget ) {
$widget->add_form_action(
'custom_form_action',
[
'label' => __( 'Custom Form Action', 'elementor-pro' ),
'event' => \ElementorPro\Modules\Forms\Classes\Form_Record::get_form_settings( 'custom_form_action_event' ),
'callback' => [ $this, 'custom_form_action' ],
]
);
}
public function run( $record, $ajax_handler ) {
$debugLog = '';
$settings = $record->get( 'form_settings' );
// create the first api request
$first_api_url = $settings['custom_form_action_api_url'];
$first_api_body = $settings['custom_form_action_api_body'];
// set up the first header request
$first_api_header_authorization = 'Bearer ' . $settings['custom_form_action_application_token'];
// get the form fields
$fields = $record->get( 'fields' );
// replace the placeholders with the form field values
$first_api_body = $this->replace_placeholders( $first_api_body, $fields );
//////////////////////////////////////////
//
// Make the first API request
//
//////////////////////////////////////////
//if the method is post
// send the post request
$first_api_response = wp_remote_post( $first_api_url, [
'method' => 'POST',
'headers' => array(
'Authorization' => 'Bearer ' . $settings['custom_form_action_application_token'],
'content-type' => 'application/json',
),
'body' => $first_api_body,
'timeout' => 20,
'redirection' => 5,
'httpversion' => '1.0',
//SET BLOCKING TO TRUE TO WAIT FOR A RESPONSE - 5 hours wasted for this.
'blocking' => true,
'data_format' => 'body',
] );
if ( ! is_wp_error( $first_api_response ) ) {
$response_data = json_decode( $first_api_response['body'], true );
if ( isset( $response_data['data']['id'] ) ) {
$new_lead_id = $response_data['data']['id'];
}
else{
$new_lead_id = '';
}
}
//////////////////////////////////////////
//
// Make the second API request
//
//////////////////////////////////////////
// create the second api request
$second_api_url = $settings['custom_form_action_second_api_url'];
// set up the second header request
$second_api_header_authorization = 'Bearer ' . $settings['custom_form_action_second_application_token'];
if (!empty($first_api_response_body)){
$new_lead_id = $first_api_response_body->data->id;
}
$new_api_url = $second_api_url . $new_lead_id;
$new_api_body = '{ "lead_id": ' . $new_lead_id . '}';
// send the second api request
$second_api_response = wp_remote_post( $new_api_url, [
'method' => 'POST',
'headers' => array(
'Authorization' => 'Bearer ' . $second_api_header_authorization,
'content-type' => 'application/json',
),
'body' => $new_api_body,
'timeout' => 20,
'redirection' => 5,
'httpversion' => '1.0',
'blocking' => true,
'data_format' => 'body',
] );
//Check for errors in the Second api response.
if ( ! is_wp_error( $second_api_response ) ) {
$response_data = json_decode( $second_api_response['body'], true );
if ( isset( $response_data['autologin'] ) ) {
$autologin = $response_data['autologin'];
}
else{
$autologin = 'https://google.com';
}
}
//redirect the user
if ( ! empty( $autologin ) ) {
wp_redirect( $autologin );
exit;
}
else{
wp_redirect( 'https://www.google.com' );
exit;
}
if ( is_wp_error( $first_api_response ) ) {
wp_remote_retrieve_response_code( $second_api_response );
if ( wp_remote_retrieve_response_code( $second_api_response ) == 201 ) {
//add success message
$ajax_handler->add_success_message( __( 'First API Response: ' . $second_api_response['body'], 'elementor-pro' ) );
}
elseif ( wp_remote_retrieve_response_code( $second_api_response ) == 202 ) {
//add error message
$ajax_handler->add_error_message( __( 'First API Response: ' . $second_api_response['body'], 'elementor-pro' ) );
}
}
if ( is_wp_error( $second_api_response ) ) {
$ajax_handler->add_error_message( __( '<br><br>Data ID From First Response: '. $first_api_response_body->data->id
. '<br>Second API Body: ' . json_encode($second_api_body)
. '<br> First API Response Selector: ' . $first_api_body_response_selector
. '<br>Second API Response: ' . $second_api_response['body']
. '<br>Redirect URL: ' . $redirect_response_url
. '<br><br>',
'elementor-pro'
)
);
return;
}
if ( ! empty( $redirect_response_url ) && filter_var( $redirect_response_url, FILTER_VALIDATE_URL ) ) {
$ajax_handler->add_response_data( 'redirect_url', $redirect_response_url );
}
}//end run function
public function on_export( $element ) {
unset( $element['custom_form_action_message_redirect_url'] );
return $element;
}
public function replace_placeholders( $string, $fields ) {
$ip_of_current_user = $this->bpd_get_user_ip();
foreach ( $fields as $id => $field ) {
$string = str_replace( '{{{ USERIP }}}', $ip_of_current_user, $string );
$string = str_replace( '{{{ ' . $id . ' }}}', $field['value'], $string );
}
return $string;
}
public function bpd_get_user_ip() {
/*
if ( ! empty( $_SERVER['HTTP_CLIENT_IP'] ) ) {
$ip = $_SERVER['HTTP_CLIENT_IP'];
return $ip;
} elseif ( ! empty( $_SERVER['HTTP_X_FORWARDED_FOR'] ) ) {
$ip = $_SERVER['HTTP_X_FORWARDED_FOR'];
return $ip;
} else {
$ip = $_SERVER['REMOTE_ADDR'];
return $ip;
}
*/
$ip = $_SERVER['REMOTE_ADDR'];
return $ip;
}
}
`
Trying to get only the needed data on a custom endpoint in Wordpress. To do so, I am using get_posts() function.
add_action('rest_api_init', function() {
register_rest_route('wl/v1', 'pages', [
'methods' => 'GET',
'callback' => 'wl_page',
]);
});
function wl_page() {
$args = [
'numberposts' => 99999,
'post_type' => 'page',
'post_parent' => 0,
];
$posts = get_posts($args);
$data = [];
$data['ID'] = $posts[0]->ID;
$data['title'] = $posts[0]->post_title;
$data['content'] = $posts[0]->post_content;
$data['featured_image'] = $posts[0]->featured_media;
return $data;
}
It should return the ID of the featured image, but get_posts() doesn't even return that field.
get_posts returns array of Post Objects which don't have featured_media property available. Use get_post_thumbnail_id() instead.
See updated code below:
add_action('rest_api_init', function() {
register_rest_route('wl/v1', 'pages', [
'methods' => 'GET',
'callback' => 'wl_page',
]);
});
function wl_page() {
$args = [
'numberposts' => 99999,
'post_type' => 'page',
'post_parent' => 0,
];
$posts = get_posts($args);
$data = [];
$data['ID'] = $posts[0]->ID;
$data['title'] = $posts[0]->post_title;
$data['content'] = $posts[0]->post_content;
$data['featured_image'] = get_post_thumbnail_id( $posts[0]->ID );
return $data;
}
I am challenging Ajax implementation when replying by "BBPress".
However, reply posted in this manner is displayed in the dashboard, but it is not displayed in the loop of the replies list.
This will be displayed in the loop of the replies list only when you click "Update" on the dashboard.
I want to know the code that displays correctly in the loop.
This is my code:
my-reply.js
"use strict";
(function($){
$(document).on("click","#bbp_reply_submit", function() {
// get
var inputForum = '56'; //There is only one forum.
var inputTopic = $('#bbp_topic_id').val();
var inputTitle = $('#bbp-reply-form-info').text();
var inputContent = $('#bbp_reply_input').val();
var inputParent = $('#bbp_reply_to').val();
var inputIp = $('#my_reply_ip').val();
// Ajax
$.ajax({
url: MY_AJAX.api,
type: 'POST',
data: {
// action name
action: MY_AJAX.action,
// nonce
nonce: MY_AJAX.nonce,
// submit data
submitForum: inputForum,
submitTopic: inputTopic,
submitTitle: inputTitle,
submitContent: inputContent,
submitParent: inputParent,
submitIp: inputIp,
}
})
// scusess
.done(function( response ) {
alert('success'); // Actually, I will display reply instead of alerts.
})
// error
.fail(function( jqXHR, textStatus, errorThrown ) {
alert('error');
});
});
})(jQuery);
functions.php
// nonce
function my_enqueue_scripts() {
$handle = 'my-script';
$jsFile = 'path/to/myscript.js';
wp_register_script($handle, $jsFile, ['jquery']);
$acrion = 'my-ajax-action';
wp_localize_script($handle, 'MY_AJAX', [
'api' => admin_url( 'admin-ajax.php' ),
'action' => $acrion,
'nonce' => wp_create_nonce( $acrion ),
]);
wp_enqueue_script($handle);
}
add_action( 'wp_enqueue_scripts', 'my_enqueue_scripts' );
// post reply
function my_ajax_event() {
$action = 'my-ajax-action';
if( check_ajax_referer($action, 'nonce', false) ) {
$submitForum = esc_html( $_POST['submitForum'] );
$submitTopic = esc_html( $_POST['submitTopic'] );
$submitTitle = esc_html( $_POST['submitTitle'] );
$submitContent = esc_html( $_POST['submitContent'] );
$submitParent = esc_html( $_POST['submitParent'] );
$submitIp = esc_html( $_POST['submitIp'] );
$submitTopicslug = esc_html( $_POST['submitTopicslug'] );
$page = get_post( $submitTopic );
$slug = $page->post_name;
$date = 'Y-m-d H:i:s';
$my_post = array(
'post_title' => (string)wp_strip_all_tags($_POST['submitTitle']),
'post_content' => (string)$_POST['submitContent'],
'post_status' => 'publish',
'post_author' => get_current_user_id(),
'post_type' => 'reply',
'meta_input' => array(
'_bbp_forum_id' => $_POST['submitForum'],
'_bbp_topic_id' => $_POST['submitTopic'],
'_bbp_reply_to' => $_POST['submitParent'],
'_bbp_author_ip' => $_POST['submitIp'],
'_edit_last' => get_current_user_id(),
'_bbp_topic_sort_desc' => 'dft',
'_bbp_sort_desc' => 'dft',
'_bbp_topic_sort_show_lead_topic' => 'dft',
'_bbp_topic_sort_show_lead_topic_forum' => 'dft',
'_wp_old_slug' => $slug,
'_bbp_last_active_time' => $date,
'_bbp_reply_count' => '',
'_bbp_engagement' => '',
'_bbp_reply_count_hidden' => '',
'_bbp_voice_count' => '',
)
);
wp_insert_post( $my_post );
} else {
status_header( '403' );
}
die();
}
add_action( 'wp_ajax_my-ajax-action', 'my_ajax_event' );
add_action( 'wp_ajax_nopriv_my-ajax-action', 'my_ajax_event' );
Im trying to post some data to custom api endpoint that i created,
This is what my wordpress custom endpoint code.
register_rest_route( 'api/v1', '/cities', array(
'methods' => 'POST',
'callback' => 'create_city_from_data'
));
And for testing I am trying to return the request like this
function create_city_from_data($req) {
return ['req' => $req];
}
but always i receive empty object as response, whatever i send in payload i didn't receive anything.
My payload is something like this
{ name: 'Hello', population: 565656 }
This is what is received from the request
{"req":{}}
By using below code you can view your payload.
add_action('rest_api_init', function () {
register_rest_route( 'api/v1', '/cities', array(
'methods' => 'POST',
'callback' => 'create_city_from_data'
));
});
function create_city_from_data($req) {
$response['name'] = $req['name'];
$response['population'] = $req['population'];
$res = new WP_REST_Response($response);
$res->set_status(200);
return ['req' => $res];
}
I have used postman to view the POST parameter
By using this function you can see all post of your custom post type in API...
Get All Post in your API Viewer.
Writer URL on your API viewer (e.g. I used Postman json api view, google chrome adon)
Domain-name/wp-json/showFavorites/v2?post_type=hotel
Here 'hotel' is the custom posttype.
Add this function in your functions.php
add_action( 'rest_api_init', 'wp_api_show_favorites_endpoints' );
function wp_api_show_favorites_endpoints() {
register_rest_route( 'showFavorites', '/v2', array(
'methods' => 'GET',
'callback' => 'showFavorites_callback',
));
}
function showFavorites_callback( $request_data ) {
global $wpdb;
$data = array();
$table = 'wp_posts';
$parameters = $request_data->get_params();
$post_type = $parameters['post_type'];
if($post_type!=''){
$re_query = "SELECT * FROM $table where post_type='$post_type'";
$pre_results = $wpdb->get_results($re_query,ARRAY_A);
return $pre_results;
}else{
$data['status']=' false ';
return $data;
}
}
And using this you can post your content from API
// POST All Posts using API
add_action( 'rest_api_init', 'wp_api_add_posts_endpoints' );
function wp_api_add_posts_endpoints() {
register_rest_route( 'addPost', '/v2', array(
'methods' => 'POST',
'callback' => 'addPosts_callback',
));
}
function addPosts_callback( $request_data ) {
global $wpdb;
$data = array();
$table = 'wp_posts';
// Fetching values from API
$parameters = $request_data->get_params();
$user_id = $parameters['user_id'];
$post_type = $parameters['post_type'];
$post_title = $parameters['post_title'];
$the_content = $parameters['the_content'];
$cats = $parameters['cats'];
$the_excerpt = $parameters['the_excerpt'];
$feature_img = $parameters['featured_image'];
// custom meta values
$contact_no = $parameters['contact_no'];
$email = $parameters['email'];
$hotel_url = $parameters['hotel_url'];
if($post_type!='' && $post_title!=''){
// Create post object
$my_post = array(
'post_title' => wp_strip_all_tags( $post_title),
'post_content' => $the_content,
'post_author' => '',
'post_excerpt' => $the_excerpt,
'post_status' => 'publish',
'post_type' => $post_type,
);
$new_post_id = wp_insert_post( $my_post );
function wp_api_encode_acf($data,$post,$context){
$customMeta = (array) get_fields($post['ID']);
$data['meta'] = array_merge($data['meta'], $customMeta );
return $data;
}
if( function_exists('get_fields') ){
add_filter('json_prepare_post', 'wp_api_encode_acf', 10, 3);
}
// Set post categories
$catss = explode(',', $cats);
if (!empty($catss)) {
if ($post_type == 'post') {
wp_set_object_terms( $new_post_id, $catss, 'category', false );
}
else{
wp_set_object_terms( $new_post_id, $catss, 'Categories', false ); // Executes if posttype is other
}
}
// Set Custom Metabox
if ($post_type != 'post') {
update_post_meta($new_post_id, 'contact-no', $contact_no);
update_post_meta($new_post_id, 'email', $email);
update_post_meta($new_post_id, 'hotel-url', $hotel_url);
}
// Set featured Image
$url = $feature_img;
$path = parse_url($url, PHP_URL_PATH);
$filename = basename($path);
$uploaddir = wp_upload_dir();
$uploadfile = $uploaddir['path'] . '/' . $filename;
$contents= file_get_contents($feature_img);
$savefile = fopen($uploadfile, 'w');
chmod($uploadfile, 0777);
fwrite($savefile, $contents);
fclose($savefile);
$wp_filetype = wp_check_filetype(basename($filename), null );
$attachment = array(
'post_mime_type' => $wp_filetype['type'],
'post_title' => $filename,
'post_content' => '',
'post_status' => 'inherit'
);
$attach_id = wp_insert_attachment( $attachment, $uploadfile );
if ($attach_id) {
set_post_thumbnail( $new_post_id, $attach_id );
}
if ($new_post_id) {
$data['status']='Post added Successfully.';
}
else{
$data['status']='post failed..';
}
}else{
$data['status']=' Please provide correct post details.';
}
return ($data);
}
The object parameter passed into the callback function is a WP_REST_REQUST object and has a get_body() method on it which returns the payload/post body of the HTTP Post Request.
function create_city_from_data(WP_REST_Request $req) {
$body = $req->get_body()
return ['req' => $body];
}
I learnt about this today whilst reading this article
You can also declare the type of object in the method signature in case you need to search the documentation for it (like i have above).
CURL request :
$url = $your_url; // your url should like: http://host.com/wp-json/v1/'.$key
$post_string = json_encode($post_data);// make json string of post data
$ch = curl_init(); //curl initialisation
curl_setopt($ch, CURLOPT_URL, $url); // add url
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); // get return value
curl_setopt($ch, CURLOPT_POST, true); // false for GET request
curl_setopt($ch, CURLOPT_POSTFIELDS, $post_string); // add post data
curl_setopt($crl, CURLOPT_HTTPHEADER, array(
'Content-Type: application/json',
'Content-Length: ' . strlen($post_string))
);// add header
$output = curl_exec($ch);
curl_close($ch); // close curl
$error = curl_error($ch); // get error
if(!$error){
return json_decode($output);
}else{
return $error;
}
For Handle Request in PLUGIN context :
public static function handle_requests(WP_REST_Request $request){
$return_data = [];
//get GET params
$key = $request['key'];
//get POST values
$post_data = json_decode($request->get_body());
//$return_data = $post_data;
if ( empty( $return_data ) ) {
return new WP_Error( 'error', 'Invalid Request', array( 'status' => 404 ) );
}else{
return $return_data;
}
}
Your WP REST API ACTION :
add_action( 'rest_api_init', function () {
register_rest_route( '/v1', '/(?P<key>[\w]+)', array(
'methods' => ['GET', 'POST'],
'callback' => 'YOUR_CLASS::handle_requests',
'permission_callback' => '__return_true'
) );
} );
//permission_callback need to add for wordpress newer versions.