I'm trying to get points from a plugin called myCRED and have those points displayed on another site. This is possible because myCRED has a remote API that works through the WordPress HTTP API. I have the code that allows me to access the API but I'm confused how to use it to echo the point results on to the page. Here's what I have so far
$secret_key = 'mysecretkey';
$remote_url = 'http://siteb.com/api/';
$action = 'GET';
$account = 'john.doe#email.com';
$point_type = 'my_custom_type';
$host = get_bloginfo( 'url' );
$token = md5( $host . $action . $secret_key );
$request = array(
'method' => 'POST',
'body' => array(
'action' => $action,
'account' => $account,
'type' => $point_type,
'token' => $token,
'host' => $host
)
);
$response = wp_remote_post( $remote_url, $request );
How do I get my points to echo on to the page? Where do I put this code?
Correct me if i'm wrong here but you currently have two wordpress websites. One is using a plugin myCRED which has an api. You want to use that api from another wordpress website to display information.
You should handle the templating on the client side. I've included an example for enqueuing a script with an nonce and ajax url exposed to be able to communicate to your wordpress backend.
Using wp_ajax, you can create a function which will return your data from the myCRED api and then return that data back to client side who requested it.
The templating should be handled client side which I left for you since I'm unsure of the end goal here.
This example could be turned into a very simple plugin, but for brevity sakes I've shown to just include this in your functions.php file
Wordpress Enqueue Script
https://developer.wordpress.org/reference/functions/wp_enqueue_script/
// functions.php
function my_cred_script() {
wp_register_script(
'cred-script',
get_template_directory_uri() . '/path/to/js/file.js',
array('jquery'),
null,
true
);
wp_enqueue_script( 'cred-script' );
wp_localize_script( 'cred-script', 'ajax_object', array(
'cred_nonce' => wp_create_nonce( 'cred_nonce' ),
'ajax_url' => admin_url( 'admin-ajax.php' )
)
);
}
Wordpress Ajax Reference
https://codex.wordpress.org/Plugin_API/Action_Reference/wp_ajax_(action)
// functions.php
function get_my_cred_data() {
if(!isset( $_POST['cred_nonce'] ) ||
!wp_verify_nonce( $_POST['cred_nonce'], 'cred_nonce' )) {
die();
}
$secret_key = 'mysecretkey';
$remote_url = 'http://siteb.com/api/';
$action = 'GET';
$account = 'john.doe#email.com';
$point_type = 'my_custom_type';
$host = get_bloginfo( 'url' );
$token = md5( $host . $action . $secret_key );
$request = array(
'method' => 'POST',
'body' => array(
'action' => $action,
'account' => $account,
'type' => $point_type,
'token' => $token,
'host' => $host
)
);
$response = wp_remote_post( $remote_url, $request );
echo $response;
die();
}
add_action('wp_ajax_cred_data', 'get_my_cred_data');
add_action('wp_ajax_nopriv_cred_data', 'get_my_cred_data');
In some javscript file in your theme that was enqueued from the above. We can now call our action ('cred_data') we created in wordpress from the client side. We should get back some json and can template it however we like.
function getCREDData() {
var options = {
action: 'cred_data',
cred_nonce: ajax_object.cred_nonce
};
$.post(ajax_object.ajax_url, options)
.then(function(response) {
// handle response
})
.catch(function(err) {
// handle err
});
}
Related
I am working on a php application that requires me to interact with each merchants store using the WooCommerce Rest API and i am trying to auto-generate the rest api keys like it was documented on their documentation but my callback_url endpoint won't fire and i don't receive the auto-generated keys sent to the callback endpoint.
Here is my code to Create an authentication endpoint URL
public function integrate()
{
$url = $this->input->post('url');
$title = $this->input->post('title');
$user_id = $this->session->userdata('client_id');
$save = $this->Store_model->save_store($user_id,$url, $title);
$genKeyEndpoint = '/wc-auth/v1/authorize';
$params = [
'app_name' => 'App Name',
'scope' => 'read_write',
'user_id' => $user_id,
'return_url' => base_url('stores/integrateForm'),
'callback_url' => base_url('stores/callback-endpoint')
];
$query_string = http_build_query( $params, null, '&', PHP_QUERY_RFC3986 );
$wooAuth = $url . $genKeyEndpoint . '?' . $query_string;
redirect($wooAuth);
}
and here is my code to retrieve the generated keys and store in my database
public function save_api_key() {
$post_data = json_decode(file_get_contents('php://input'), true);
$wooResponseData = [
'consumer_key' => $post_data['consumer_key'],
'consumer_secret' => $post_data['consumer_secret']
];
$this->Store_model->updateStoreKeys($this->session->userdata('client_id'), $wooResponseData);
}
My application is running on codeigniter.
I am working on a project that requires some integration between different WordPress instances and I am in the process of creating a WordPress plugin that will provide that functionality through the REST API.
I have enabled the WP-API plugin and the Basic Authentication plugin and am able to make requests that do not require authentication but when I make a request that does require authentication, such as adding a new page, I am met with 401 - Sorry, you are not allowed to create new posts.
I realize basic authentication is not suitable for production needs but would like to get it working properly for development and have been spinning my wheels on this seemingly small problem. I am perfectly able to make these requests using Postman, so there is something wrong with my implementation. Here is the code in question:
function add_new_page($post) {
// Credentials for basic authentication.
$username = 'user';
$password = 'password';
// Request headers.
$headers = array(
'Authorization' => 'Basic ' . base64_encode( $username . ':' . $password ),
'Content-Type' => 'application/json'
);
// Request URL.
$url = "http://localhost/wp-json/wp/v2/pages";
// Request body.
$body = array(
'slug' => $post->post_name,
'status' => $post->post_status,
'type' => $post->post_type,
'title' => $post->post_title,
'content' => $post->post_content,
'excerpt' => $post->post_excerpt,
);
$body_json = json_encode($body);
// Request arguments.
$args = array(
'method' => 'POST',
'blocking' => true,
'headers' => $headers,
'cookies' => array(),
'body' => $body_json,
);
// Fire request.
$response = wp_remote_request($url, $args);
// Handle response.
if (is_wp_error($response)) {
$error_message = $response->get_error_message();
echo "Something went wrong: $error_message";
} else {
$response_body = json_decode(wp_remote_retrieve_body($response));
// Display response body.
echo '<pre>';
print_r($response_body);
echo '</pre>';
}
// Exit so we can read the response.
exit();
}
I would be really appreciative of any insights somebody out there could provide.
I have a wordpress web site and Phalcon web application on another server. When I'm logged on my web application I have a session. When I'm back on wordpress I want to check if there is a session on my web application and if it's true I'll log the user on wordpress too.
So I thought I'll create a web service in my web application and it will called by wordpress. In this web service I'll check if the session exists and return the email user to log wordpress side.
But I have a problem because when I use the web service with wordpress, the session does not exist. But when I enter the URL via the browser, it works.
Could you help me to do that ?
Wordpress side
add_action( 'init', 'process_post' );
function process_post() {
$url = 'http://exemple.com/webapp/controller/logged';
$response = wp_remote_post( $url, array(
'method' => 'POST',
'timeout' => 45,
'redirection' => 5,
'httpversion' => '1.0',
'blocking' => true,
'headers' => array(),
'body' => array( 'from' => 'authentication' ),
'cookies' => array()
)
);
if ( is_wp_error( $response ) ) {
$error_message = $response->get_error_message();
echo "Something went wrong: $error_message";
} else {
echo 'Response:<pre>';
print_r( $response );
echo '</pre>';
}
}
Phalcon Web application web service
public function loggedAction(){
$this->view->disable();
$auth = $this->session->get('my_session');
if($auth){
$jsonResponse = array('authorization' => 'OK');
return $this->jsonBuilder($jsonResponse);
}
}
This is not the whole code phalcon side but this code can be good just for testing
I'm using wordpress and i want to integrate an SMS API into my wordpress site. Can anyone help in knowing where (in which file) to write the code for integration and also the code to integrate SMS API.
My SMS API Url is :
http://www.elitbuzzsms.com/app/smsapi/index.php?key=KEY&campaign=****&routeid=**&type=text&contacts=< NUMBER >&senderid=SMSMSG&msg=< Message Content >
I want to integrate above API in my wordpress theme so that i can send sms based on mobile number and add required message.
In wordpress you can use wp_remote_get and wp_remote_post
get request example
$url = 'http://www.elitbuzzsms.com/app/smsapi/index.php?key=KEY&campaign=****&routeid=**&type=text&contacts=< NUMBER >&senderid=SMSMSG&msg=< Message Content >';
$response = wp_remote_get( $url );
if( is_array($response) ) {
$header = $response['headers']; // array of http header lines
$body = $response['body']; // use the content
}
post request example
$response = wp_remote_post( $url, array(
'method' => 'POST',
'timeout' => 45,
'redirection' => 5,
'httpversion' => '1.0',
'blocking' => true,
'headers' => array(),
'body' => array( 'username' => 'bob', 'password' => '1234xyz' ),
'cookies' => array()
)
);
if ( is_wp_error( $response ) ) {
$error_message = $response->get_error_message();
echo "Something went wrong: $error_message";
} else {
echo 'Response:<pre>';
print_r( $response );
echo '</pre>';
}
I would like to let the script do a redirection on click of the submit button by using the PHP header function. However, it doesn't seem to work. Any idea how i could get it to work with PHP header function?
Here's part of the function that i thought is relevant:-
switch ( $service ) {
case 'mailchimp' :
$lastname = sanitize_text_field( $_POST['et_lastname'] );
$email = array( 'email' => $email );
if ( ! class_exists( 'MailChimp' ) )
require_once( get_template_directory() . '/includes/subscription/mailchimp/mailchimp.php' );
$mailchimp_api_key = et_get_option( 'divi_mailchimp_api_key' );
if ( '' === $mailchimp_api_key ) die( json_encode( array( 'error' => __( 'Configuration error: api key is not defined', 'Divi' ) ) ) );
$mailchimp = new MailChimp( $mailchimp_api_key );
$merge_vars = array(
'FNAME' => $firstname,
'LNAME' => $lastname,
);
$retval = $mailchimp->call('lists/subscribe', array(
'id' => $list_id,
'email' => $email,
'merge_vars' => $merge_vars,
));
if ( isset($retval['error']) ) {
if ( '214' == $retval['code'] ){
$error_message = str_replace( 'Click here to update your profile.', '', $retval['error'] );
$result = json_encode( array( 'success' => $error_message ) );
} else {
$result = json_encode( array( 'success' => $retval['error'] ) );
}
} else {
$result = json_encode( array( 'success' => $success_message ) );
}
die( $result );
break;
I tried to replace the $result with header("Location: http://www.example.com/"); but it didn't work.
The reason that you can't just change the code to $result = header('Location: ...') is actually quite simple. With this javascript call as an example:
$.post('/myscript.php', { et_lastname: 'Doe', email: 'j.doe#example.com' }, function(data) {
// do something
});
What happens:
An HTTP-POST call is made via AJAX to /myscript.php
Your code is executed, subscribing the given email address.
The PHP code returns a 301
The AJAX call will follow the redirect, but your browser will stay on the same page.
What you actually want is that when the AJAX call was successful, the browser redirects to another page. To achieve that, you'll need to update both your PHP and Javascript.
In your PHP, you'll have to return the location you want the browser to redirect to, for example:
<?php
$result = json_encode(array('location' => 'https://example.com/path/to/page'));
Right now, the PHP script just returns an json-response with a location key. The browser, nor the javascript doesn't do anything with that information unless we tell it to do so:
$.post('/myscript.php', { et_lastname: 'Doe', email: 'j.doe#example.com' }, null, 'json').done(function(data) {
// do something ...
// redirect browser to page we provided in the ajax response
window.location = data.location;
}).fail(function(data) {
// handle the error
});