I'm trying to add an sms api to Wordpress which sends an order confirmation message using Woocommerce hooks. After some research, I found the following code here which works the same way.
add_action('woocommerce_payment_complete', 'custom_process_order', 10, 1);
function custom_process_order($order_id) {
//Lets get data about the order made
$order = new WC_Order( $order_id );
//Now will fetch customer/buyer id here
$customer_id = $order->user_id;
//now finally we fetch phone number
$billing_phone = get_user_meta( $customer_id, 'billing_phone', true );
// Now put your HTTP SMS API URL . I PUT WHICH WE ARE USING
$jsonurl = "http://tsms.thirdeyegoa.com/api/sendmsg.php?user=USERNAME&pass=PASSWORD&sender=MYSENDERID&phone=".$billing_phone."&priority=ndnd&stype=normal&text=MY MESSAGE TO CUSTOMER.";
// NOW WILL CALL FUNCTION CURL
$json = curl($jsonurl);
return $order_id;
}
The Api Code my sms gateway provided is
// Include provided Java Script
<script language="javascript" src="https://domainapi.js" type="text/javascript"> </script>
<script language="javascript">
// Replace your API key at below line
var apikey = 'ABCDEFGH1234567890abcdefghQWERTY123=';
// Form your data object
var mail_details = { email : 'John.Doe#foo.com', msgid : '82', listname : '', prefix : '', firstname : 'John', middlename : '', lastname : 'Doe', telephone : '', address : '', city : '', state : '', pincode : '', country : '', mobile : '9999999999', designation : '', company : '', companyphone : '', birthdate : '', anniversary : '', extra1 : '', extra2 : '' }
call_api(apikey, 'sendSingleSMS', mail_details, function(response) { document.getElementById('show').innerHTML=response; });</script>
Please tell me how to integrate this API in the above script for Wordpress.
Presumably, you are trying to blend your API's script into the "WordPress way" and load some data from WooCommerce's order. First, you'd want to register your scripts in your main plugin file:
add_action( 'wp_enqueue_scripts', 'so_38554614_enqueue_scripts' );
function so_38554614_enqueue_scripts(){
wp_register_script( 'your-api', 'https://domainapi.js', array(), '1.0', true );
wp_register_script( 'your-script', 'path-to-your-script.js', array('your-api'), '1.0', true );
}
And then you'll want to load them on the payment complete page. You will also want to take advantage of wp_localize_script() to pass some variables to the script.
add_action('woocommerce_payment_complete', 'custom_process_order', 10, 1);
function custom_process_order($order_id) {
//Lets get data about the order made
$order = new WC_Order( $order_id );
wp_enqueue_script('your-api');
wp_enqueue_script('your-script');
$l18n = array( 'mail_details'=>
array(
email' => $order->billing_email,
'msgid' => 82,
'listname' => '',
'firstname' => $order->billing_first_name,
'middlename' => '',
'lastname' => $order->billing_last_name,
'telephone' => $order->billing_phone,
'address'= >$order->billing_address_1 . ' ' . $order->billing_address_2,
'city' => $order->billing_city,
'state' => $order->billing_state,
'pincode' => '',
'country' => $order->billing_country,
'mobile' => $order->billing_phone
'designation' => '',
'company' => $order->billing_company,
'companyphone' => '',
'birthdate' => '',
'anniversary' => '',
'extra1' => '',
'extra2' => ''
),
'apikey' => 'ABCDEFGH1234567890abcdefghQWERTY123=' );
wp_localize_script( 'your-script', 'Your_JS_Object', $l18n );
wp_localize_script()
return $order_id;
}
And finally, your javascript file, stored somewhere in your plugin. It takes advantage of the javascript object Your_JS_Object which was created by wp_localize_script():
// Java Script path-to-your-script.js
call_api( Your_JS_Object.apikey, 'sendSingleSMS', Your_JS_Object.mail_details, function(response) { document.getElementById('show').innerHTML=response; });
Related
I am currently programming a webservice. on of its method is to send some information to delete a user from event. this is documentation:
the json is like this
{
"users": "[users :['userid' : 1, 'role' : 'participant'],['userid' : 2, 'role' : 'teacher'],['userid' : 3, 'role' : 'assistant']]"
}
but I always get the error of "field users is required";
I appreciate any answer. thanks alot
I tried this
function delete_user_from_event( $event_id, $user_id ){
$webService = 'https://pnlapi.alocom.co/api/v1/agents/events/'. $event_id .'/remove-users';
$params = array(
'users' => array(
'users' => array(
[
'userid' => $user_id,
'role' => 'participant',
] )
)
);
return $this -> post_request( $webService, false, $params, 'patch' );
}
but I get error. I think I do not understand json array.
I use the following snippet to create a WordPress post via the REST API, using the Node.js wrapper:
var wp = new WPAPI({
endpoint: 'http://your-site.com/wp-json',
username: 'someusername',
password: 'password'
});
wp.posts().create({
title: 'Your Post Title',
content: 'Your post content',
status: 'publish',
meta: { "custom_field": "my custom field value" }
}).then(function( response ) {
console.log( response.id );
})
When fetching the posts, the meta is empty.
Why is that and how can I fix that?
For some reason that did not work for me either. I ended by using a WordPress REST hook.
In functions.php I added:
add_filter( 'pre_post_update' , function ( $post_id , $post ) {
$body = json_decode(file_get_contents('php://input'), true);
$meta_fields = $body["meta"];
foreach ($meta_fields as $meta_key => $value) {
update_post_meta($post_id, $meta_key, $value);
}
}, '99', 2 );
The snippet above will parse the meta field and will update the post metadata fields.
If you want to include the custom fields in the responses, you can use:
//Get custom fields via Rest API
add_action( 'rest_pre_echo_response', function( $response, $object, $request ) {
//* Get the post ID
$post_id = $response[ 'id' ];
if ($response['type'] !== 'post' && $response['type'] !== 'page') return $response;
$response['custom_fields'] = get_post_meta($post_id);
return $response;
}, 10, 3 );
I have made a customized control for the Wordpress Customizer and I would like to set my control inside a script (Instafeed.js), to change the limit number.
Following this answer this is how I did it so far
<script type="text/javascript">
var userFeed = new Instafeed({
get: '',
tagName: '',
clientId: '',
limit: var imglimit = <?php echo json_encode($imglimit); ?>;,
});
userFeed.run();
</script>
Functions
$wp_customize->add_setting(
'imglimit',
array(
'default' => '',
'section' => 'section',
));
$wp_customize->add_control('imglimit', array(
'label' => __('test'),
'section' => 'section',
'settings' => 'imglimit',
'type' => 'select',
'choices' => array(
'5' => '5',
'10' => '10',
'20' => '20',
),
));
function theme_customizer()
{
$imglimit = get_theme_mod('imglimit');
}
Could anyone tell me where is the mistake ? I've been searching for this for a while.
Well, you've got a syntax error here :)
var userFeed = new Instafeed({
get: '',
tagName: '',
clientId: '',
limit: var imglimit = <?php echo json_encode($imglimit); ?>;,
// ^^^^^^^^^^^^ here and here ^
});
So, you should change that block of code to
var userFeed = new Instafeed({
get: '',
tagName: '',
clientId: '',
limit: <?php echo json_encode($imglimit); ?>,
});
Actually you don't necessarily need to json encode here since it's just a number. But if that was some array or object, yes, you should've encoded that.
And in your php code you should make $imglimit global:
function theme_customizer()
{
global $imglimit;
$imglimit = get_theme_mod('imglimit');
}
Or just put that into js:
var userFeed = new Instafeed({
get: '',
tagName: '',
clientId: '',
limit: <?php echo json_encode(get_theme_mod('imglimit')); ?>,
});
I am having a problem getting a custom query to alphabetize. It keeps defaulting to displaying in the order of the date it was posted. Below is my php function.
function json_info2() {
// The $_REQUEST contains all the data sent via ajax
if ( isset($_REQUEST) ) {
$paged = (get_query_var('paged')) ? get_query_var('paged') : 1;
// get values for all three drop-down menus
$status = $_REQUEST['status'];
$industry = $_REQUEST['services'];
$state = $_REQUEST['state'];
// array of values for each of the three drop-downs
$statusAll = array('complete','incomplete');
$industryAll = array('mining','textile','machinery');
$statesAll = array('SC','TX','WA');
// set $statusArray dependent on whether or not "all" is selected in the dropdown menu
if($status == "all") {
$statusArray = array( 'key' => 'status', 'value' => $statusAll, 'compare' => 'IN');
} else {
$statusArray = array( 'key' => 'status', 'value' => $status, 'compare' => '=');
}
if($industry == "all") {
$industryArray = array( 'key' => 'industry', 'value' => $industryAll, 'compare' => 'IN');
} else {
$industryArray = array( 'key' => 'industry', 'value' => $industry, 'compare' => '=');
}
if($state == "all") {
$stateArray = array( 'key' => 'state', 'value' => $statesAll, 'compare' => 'IN');
} else {
$stateArray = array( 'key' => 'state', 'value' => $state, 'compare' => '=');
}
$pages = array(
'post_type' => 'page',
'orderby' => 'title',
'order' => 'ASC',
'paged' => $paged,
'posts_per_page' => 5,
'meta_query' => array(
'relation' => 'AND',
$statusArray,
$industryArray,
$stateArray,
array(
'key' => '_wp_page_template',
'value' => 'template-individual-project.php',
'compare' => '='
)
)
);
// query results by page template
$my_query = new WP_Query($pages);
if($my_query->have_posts()) :
while($my_query->have_posts()) :
$my_query->the_post();
<li>
<?php the_title(); ?>
</li>
<?php
endwhile;endif;
wp_reset_query();
} // end of isset
?>
<?php
die();
}
add_action( 'wp_ajax_json_info2', 'json_info2' );
add_action( 'wp_ajax_nopriv_json_info2', 'json_info2' );
?>
This above function is called by the ajax function that follows:
function do_ajax() {
// Get values from all three dropdown menus
var state = $('#states').val();
var markets = $('#markets').val();
var services = $('#services').val();
$.ajax({
url: ajaxurl,
data: {
'action' : 'json_info2',
'state' : state,
'status' : markets,
'services' : services
},
success:function(moredata) {
// This outputs the result of the ajax request
$('#project-list').html( moredata );
$('#project-list').fadeIn();
}/*,
error: function(errorThrown){
var errorMsg = "No results match your criteria";
$('#project-list').html(errorMsg);
}*/
}); // end of ajax call
} // end of function do_ajax
Is there something simple that I'm missing here? I have a similar custom query on the page when it loads (although that initial load query doesn't have the select menu values as args), and they display in alphabetical order just fine. It's only after the ajax call to filter the list that they are no longer in order.
I have found the issue after googling the problem for quite a while. I read that some of the people who were having this problem found that their theme was using a plugin called Post Types Order. It overrides the ability to set the orderby arg.
I looked at the plugins, and sure enough, Post Types Order was there. Everything I read said that the problem could be solved by unchecking "auto sort" in the settings for the plugin. However, I did that, and orderby still didn't work. I had to completely deactivate the plugin to get orderby title to work.
The below is my code I'm using for my Stripe Subscription Payments, because the site I'm implementing this into is AngularJS I want to keep the site from Refreshing so I'm opting for this AJAX option.
I have commented out a piece of the PHP which is
$charge = Stripe_Charge::create(array(
'customer' => $customer->id,
'amount' => $amount,
'currency' => 'gbp'
));
If I exclude this, the payment goes through once and I'm unsure how this application is able to process the charge if there is no call for it in the PHP file.
If I include the above snippet then the charge goes through twice.
My config.php only has require_once('Stripe.php'); along with my API keys.
So I'm hoping someone could explain why the charge goes through without the charge code piece in there if my code is actually okay for me to continue with.
HTML
<button id="proBtn">Subscribe</button>
JavaScript
Stripe.setPublishableKey('HIDDEN');
$('#proBtn').click(function(){
var token = function(res){
var $input = $('<input type="hidden" name="stripeToken" />').val(res.id);
var tokenId = $input.val();
var email = res.email;
setTimeout(function(){
$.ajax({
url:'/assets/lib/charge.php',
cache: false,
data:{ stripeEmail : email, stripeToken:tokenId, stripePlan: 'pro' },
type:'POST'
})
.done(function(data){
// If Payment Success
console.log(data);
$('#proBtn').html('Thank You').addClass('disabled');
})
.error(function(){
$('#proBtn').html('Error, Unable to Process Payment').addClass('disabled');
});
},500);
//$('form:first-child').append($input).submit();
};
StripeCheckout.open({
key: 'HIDDEN', // Your Key
address: false,
amount: 500,
currency: 'gbp',
name: 'Pro Account',
description: '',
panelLabel: 'Checkout',
allowRememberMe: false,
token: token
});
return false;
});
charge.php
<?php
require_once($_SERVER['DOCUMENT_ROOT'].'/assets/lib/config.php');
$token = $_POST['stripeToken'];
$email = $_POST['stripeEmail'];
$plan = $_POST['stripePlan'];
if ( $plan == 'pro' ) {
$amount = 500;
$amountFormat = number_format( $amount / 100, 2) ;
$plan = 'pro';
}
if ( $plan == 'team' ) {
$amount = 2000;
$amountFormat = number_format( $amount / 100, 2) ;
$plan = 'team';
}
Stripe_Plan::retrieve("pro");
Stripe_Plan::retrieve("team");
$customer = Stripe_Customer::create(array(
'email' => $email,
'card' => $token,
'plan' => $plan
));
try {
/*
$charge = Stripe_Charge::create(array(
'customer' => $customer->id,
'amount' => $amount,
'currency' => 'gbp'
));*/
echo 'success';
} catch(Stripe_CardError $e) {
echo "The card has been declined";
echo $token;
}
print_r($token);
echo '<br/>';
print_r($email);
echo '<br/>';
echo $customer->id;
echo '<h1>Successfully charged '.$amountFormat.'!</h1>';
?>
When you create a customer in Stripe it automatically charges them if you pass in a plan. You're basically saying create this customer and sign them up for this plan. That's why you are charging them twice.
Here's a link to the Customer API:
https://stripe.com/docs/api#create_customer