Wednesday, 18 February 2015

How to send push Notification to iPhone from PHP (web services/API)

Hello Developers,
   If you want to send push notification from php to iPhone application then create a new file with iphone_push.php and save it in your api folder. Paste following code in file :

 <?php
function pushnofitication($deviceToken, $message)
{

// Put your device token here (without spaces):
$deviceToken = $deviceToken;

// Put your private key's passphrase here:
$passphrase = '12345';

// Put your alert message here:
$message = $message;

////////////////////////////////////////////////////////////////////////////////

$ctx = stream_context_create();
stream_context_set_option($ctx, 'ssl', 'local_cert', 'apns_cert.pem');
stream_context_set_option($ctx, 'ssl', 'passphrase', $passphrase);

// Open a connection to the APNS server
$fp = stream_socket_client(
'ssl://gateway.sandbox.push.apple.com:2195', $err,
$errstr, 60, STREAM_CLIENT_CONNECT|STREAM_CLIENT_PERSISTENT, $ctx);

if (!$fp)
exit("Failed to connect: $err $errstr" . PHP_EOL);

// Create the payload body
$body['aps'] = array(
'alert' => 
array (
"body" => $message,
),
'sound' => 'default',
);

// Encode the payload as JSON
$payload = json_encode($body);

// Build the binary notification
$msg = chr(0) . pack('n', 32) . pack('H*', $deviceToken) . pack('n', strlen($payload)) . $payload;

// Send it to the server
$result = fwrite($fp, $msg, strlen($msg));

/*if (!$result)
echo 'Message not delivered' . PHP_EOL;
else
echo 'Message successfully delivered' . PHP_EOL;
*/
// Close the connection to the server
fclose($fp);
}
?>

For this you need a .pem file. Get this file from your iphone developer and save in your folder with name apns_cert.pem. While create pem file firstly they create .cert file. After create .cert file they need to enter a passphrase to create .pem file. so also you need to change passphrase.

The Above code is for sandbox mode when you app is live then replace .pem file and change url with live so your push notification is also work with live app.

When you want to send push notification include this file in your file and call function :
pushnofitication($deviceToken, $message)
$deviceToken : device token in unique id of iphone so when you register user get this token and save it in database. When you send push notification get this token from database and pass in this function.
$message : Message which you want to show in notification.

Thanks & Regard
Pulkit Jalani
http://www.webtecso.com

Sunday, 8 February 2015

How to add order in Woocommerce From PHP Web Services / Web Apis

Hello Developers,
   If you want to add order of woocommerce from php web api then you can create a file in your api folder named : add_order.php
Paste following code in your add_order.php file :

<?php
include ('../wp-load.php');

$order_data = array(
    'post_name'     => 'order-' . date_format($order_date, 'M-d-Y-hi-a'), //'order-jun-19-2014-0648-pm'
    'post_type'     => 'shop_order',
    'post_title'    => 'Order &ndash; ' . date_format($order_date, 'F d, Y @ h:i A'), //'June 19, 2014 @ 07:19 PM'
    'post_status'   => 'wc-completed',
    'ping_status'   => 'closed',
    'post_excerpt'  => $_REQUEST['note'],
    'post_date'     => date_format($order_date, 'Y-m-d H:i:s e'), //'order-jun-19-2014-0648-pm'
    'comment_status' => 'open'
);

// create order
$order_id = wp_insert_post( $order_data, true );
$order->imported = true;

 // get product by item_id
    $product = $_REQUEST['product_id'];


if( $product ) {

        // add item
        $item_id = wc_add_order_item( $order_id, array(
            'order_item_name'       => {Your Item name, which you can fetch from product post type with product id},
            'order_item_type'       => 'line_item'
        ) );

        if ( $item_id ) {

            // add item meta data
            wc_add_order_item_meta( $item_id, '_qty', $_REQUEST['quantity'] ); 
            wc_add_order_item_meta( $item_id, '_product_id',$product );

        }

        // set order status as completed
        wp_set_object_terms( $order_id, 'completed', 'shop_order_status' );


    } else {

        $order->errors = 'Product SKU (' . $order->$item_id . ') not found.';
    }
?>

After you can pass all parameter with below api link
http://www.webtecso.com/api/add_order.php

Wednesday, 4 February 2015

How to Update Blog content in WordPress from Web Services (API)

Hello Developers,
  If you want to update your blog content with web api then you create a new file with name update_blog.php in your api folder and paste following code :

<?php
require ("../wp-load.php");
if ($_REQUEST['id'] != "") {
global $wpdb;

$my_post = array(
 'ID'           => $_GET['id'],
                 "title"       => $_GET['title'],
 );

// Update the post into the database
 wp_update_post( $my_post );

$ar = array('reg'=>'true','msg'=>'success');
echo json_encode( $ar );
exit();
} else {
$ar = array ("reg" => 'false', "msg" => "Require Field Missing");
echo json_encode( $ar );
exit();
}
?>

You can added as many all argument of post in $my_post array and save your blog post, its required post id for update post. Now you api url is as follows :

http://www.webtecso.com/api/update_blog.php?id=

Monday, 2 February 2015

How to Display post content of WordPress from Web Services (API)

Hello Developers,
   If you want to display the content of your blog post in your app. Then you need to create a php page with names display_blog.php (you can change this name) in your previous API folder and paste below code :

<?php

require ("../wp-load.php");

$args = array( 
'post_type' => "post",
'author' => $_GET['user_id'],
'post_status' => 'publish',
'posts_per_page' => -1,
);



// The Query
$the_query = new WP_Query( $args );
// The Loop
if ( $the_query->have_posts() ) {
while ( $the_query->have_posts() ) : $the_query->the_post();
$b[] = array(
"id" => get_the_ID(),
"name" => get_the_title(),
);
endwhile;
} else {
// no posts found
}
/* Restore original Post Data */
wp_reset_postdata();

echo json_encode ($b);

?>

You can also pass user id in url so you can fetch blog post according to user or you can remove this line :
'author' => $_GET['user_id'],

Then you need to call this url :
www.webtecso.com/api/display_blog.php?usser_id={Your user id}

Thursday, 29 January 2015

Find Apple Phone Device Id / Udid online

Hello Developer,
   For sending apple app for testing, you need to know your device id or udid of phone, so by open this url in your phone safari browser you will get your device id / udid

http://get.udid.io/

Thanks
Pulkit Jalani
PHP, Wordpress, Cake PHP
www.webtecso.com

How to Send Push Notification to Android Phone from PHP (Web Service / Web API)

Hello Developers,

   If you want to send push notification from your php web services to an Android Phone then copy below function in your php file 

<?php
function AndroidPushNotification($deviceToken, $parameter1, $parameter2) {
// Set POST variables
$url = 'https://android.googleapis.com/gcm/send';

$fields = array (
'registration_ids' => array (
$deviceToken 
),
'data' => array (
"key1" => $parameter1,
"key2"  => $parameter2,

);

$headers = array (
'Authorization: key=AIzaSyDBQ0JGlQgh9LcXiQrOLNnzdMt7BKopPKM',
'Content-Type: application/json' 
);

// Open connection
$ch = curl_init ();

// Set the url, number of POST vars, POST data
curl_setopt ( $ch, CURLOPT_URL, $url );
curl_setopt ( $ch, CURLOPT_POST, true );
curl_setopt ( $ch, CURLOPT_HTTPHEADER, $headers );
curl_setopt ( $ch, CURLOPT_RETURNTRANSFER, true );

curl_setopt ( $ch, CURLOPT_POSTFIELDS, json_encode ( $fields ) );

// Execute post
$result = curl_exec ( $ch );

// Close connection
curl_close ( $ch );
}
?>

Function have following parameters :

$deviceToken : Every Android phone have unique device id / device token. So tell your developer to send this token in time of registration and save it in your user table. When you want to send push notification to some user then fetch this device id from user table and pass this in as first argument of function.

Other argument you can use as your developers choice and pass it in array keyd "data" and that will send to Android phone by Google.

GCM (Google Cloud Messaging Server) also required a authorization header that uses "Authorization: key=". This key you can get by register an app in Google developer console and provide server key in it.

Then you can send this from anywhere and also its rquired CURL on in your server and if you want to debug this print $result variable and this will return result by GCM.

Wednesday, 28 January 2015

Send Push Notification to Windows Phone From PHP (Web API / Web Services)

Hello Developers,
   If you want to send push notification from PHP website to a windows app or windows phone displayed as Toast. Write below function in any php file and save this file :

<?php
function makeWebRequest($url, $msg, $value1, $value2)
{
    //the actual data
  $toastMessage = "<?xml version='1.0' encoding='utf-8'?>" .
    "<wp:Notification xmlns:wp='WPNotification'>" .
    "<wp:Toast>" .
     "<wp:Text1>".$value1."</wp:Text1>" .
     "<wp:Text2>".$msg."</wp:Text2>" .
     "<wp:Param>/AgentChat.xaml?agentId=".$value2."&amp;notif=true</wp:Param>" .
    "</wp:Toast>" .
    "</wp:Notification>";

$r = curl_init();
curl_setopt($r, CURLOPT_URL,$url);
curl_setopt($r, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($r, CURLOPT_POST, true);
curl_setopt($r, CURLOPT_HEADER, true); 

// add headers
$httpHeaders=array('Content-type: text/xml; charset=utf-8', 'X-WindowsPhone-Target: toast',
'Accept: application/*', 'X-NotificationClass: 2','Content-Length:'.strlen($toastMessage));

curl_setopt($r, CURLOPT_HTTPHEADER, $httpHeaders);

// add message
curl_setopt($r, CURLOPT_POSTFIELDS, $toastMessage);

// execute request
$output = curl_exec($r);
curl_close($r);
}
?>

Function Parameter :

1. $url : Every windows phone have a unique url for identity. So kindly tell your windows app team to send that url and you can save it in your user table. When you want to send notification get this url from user table and pass it as first argument of function.

2. $toastMessage  = get many parameter as you want to throw with this notification, so you can get this from your windows app developer.

For any query please free to contact with me.

Thanks

Pulkit Jalani

www.webtecso.com


Wednesday, 14 January 2015

Insert new Post with Feature Image From web services / API in Wordpress

Hello Developers,
  If you want to insert new post from Web Service in Wordpress.

Create a file add_post.php in your api folder
paste below code :

<?php
require ("../wp-load.php");

if ( $_REQUEST['title'] != "") {
$post = array(
'post_content'   => $_REQUEST['Description'] , // The full text of the post.
'post_title'     => $_REQUEST['title'], // The title of your post.
'post_status'    => 'draft' , // Default 'draft'.
'post_type'      => 'product', // Default 'post'.
'post_author'    => $_REQUEST['user_id'], // The user ID number of the author. Default is the current user ID.
);  
$post_id = wp_insert_post( $post, false);


if ( $_FILES['ProductImage']['name'] != "" ) {
global $wpdb;
//For Uploading photo from front End
if (!function_exists('wp_generate_attachment_metadata')){
require_once(ABSPATH . "wp-admin" . '/includes/image.php');
require_once(ABSPATH . "wp-admin" . '/includes/file.php');
require_once(ABSPATH . "wp-admin" . '/includes/media.php');
}
$uploadedfile = $_FILES['ProductImage'];
$upload_overrides = array( 'test_form' => false );
$movefile = wp_handle_upload( $uploadedfile, $upload_overrides );

$filename = $movefile['file'];

$wp_filetype = wp_check_filetype(basename($filename), null );
$attachment = array(
'post_mime_type' => $wp_filetype['type'],
'post_title' => preg_replace('/\.[^.]+$/', '', basename($filename)),
'post_content' => '',
'post_status' => 'inherit'
);
$attach_id = wp_insert_attachment( $attachment, $filename);
$attach_data = wp_generate_attachment_metadata( $attach_id, $filename );
wp_update_attachment_metadata( $attach_id, $attach_data );

$a = add_post_meta($post_id, '_thumbnail_id', $attach_id, true);
}


$ar = array ("reg" => 'true', "msg" => "Product Added Successfully");
echo json_encode( $ar );
exit();

} else {
$ar = array ("reg" => 'false', "msg" => "Require Field Missing");
echo json_encode( $ar );
exit();
}
?>

when you add new post you can get $post_id. With this id you can add many extra parameters in post meta table of wordpress with below code :

update_post_meta($post_id, 'geo_latitude', $_REQUEST['lat']);

For insert new post your url may be look like :
www.webtecso.com/api/add_post.php?title=&user_id=&title=

Saturday, 10 January 2015

How to Create Login web Service (API) in Wordpress

Hello Developers,
   if you want to make web service that send username or email and password in a url and find that login detail is correct or not and send user id related to that login detail with a json data. Your code look like that :

In your api folder (previously define in register api) create a file with login.php

Write below code :

<?php
require ("../wp-load.php");

if($_REQUEST['pass'] != "" && $_REQUEST['email'] != "") {

$ar = wp_authenticate_username_password("", $_REQUEST['email'], $_REQUEST['pass']);

$class_name = get_class ($ar);
if ( $class_name == "WP_User" ) {
$user_id = $ar->data->ID;

$arr = array(
"id" => $user_id,
"email" => $ar->data->user_email,
"name" => $ar->data->display_name,
);
$ar = array ("result" => 0, "message" => $arr);
echo json_encode($ar);
exit();
} else {
$ar = array ("result" => 0, "message" => "Email or Password is Wrong");
echo json_encode($ar);
exit();
}
} else {
$ar = array ("result" => 0, "message" => "Require Field Missing");
echo json_encode($ar);
exit();
}
?>

run your url with following link
www.webtecso.com/api/login.php?email=&pass=

Wednesday, 7 January 2015

How to Create Registration Web Service (API) in Wordpress

Hello Developers,
   Sometimes we want to register user from Iphone or Android Application. for that you can create a file in your root directory

like

create a folder named "api" in your root directory
and create "register.php" file in this folder
then your url like this www.webtecso.com/api/register.php

for registration you need to pass argument

  • Name
  • Email
  • Password
  • Username (if your username same as email then no need to pass this parameter)
then your PHP script is look like below :-

<?php
require ("../wp-load.php");
if ( $_REQUEST['names'] != "" && $_REQUEST['emails'] != "" && $_REQUEST['password'] != "") {
global $wpdb;
if ( !username_exists( $_REQUEST['emails'] ) ) {

$device_id = $_REQUEST['device_id'];

$name = $_REQUEST['names'];
$user_login = $_REQUEST['emails'];
$user_email = $_REQUEST['emails'];
$user_pass = $_REQUEST['password'];

$userdata = compact('name', 'user_login', 'user_email', 'user_pass');
$user_id = wp_insert_user( $userdata );

if ( $_FILES['image_url']['name'] != "" ) {
global $wpdb;
//For Uploading photo from front End
if (!function_exists('wp_generate_attachment_metadata')){
require_once(ABSPATH . "wp-admin" . '/includes/image.php');
require_once(ABSPATH . "wp-admin" . '/includes/file.php');
require_once(ABSPATH . "wp-admin" . '/includes/media.php');
}
$overrides = array( 'test_form' => false);
$file = wp_handle_upload($_FILES['image_url'], $overrides);
$file['url'];

$content = $file['url'];
}

update_user_meta( $user_id, "user_pic_url", $content );


$ar = array('reg'=>'true','msg'=>'success', "id" => $user_id);
echo json_encode( $ar );
exit();

} else {
$ar = array ("reg" => 'false', 'false' => "registration failed: Sorry, that username already exists!");
echo json_encode( $ar );
exit();
}
} else {
$ar = array ("reg" => 'false', "msg" => "Require Field Missing");
echo json_encode( $ar );
exit();
}
?>

this will take url as follows :-
www.webtecso.com/api/register.php?names=&emails=&password=

then return error or success.
if your successfully registered then its return user id in JSON format
If there is any error then its return error in JSON format

Monday, 5 January 2015

How to upload image from Front End in Wordpress

Hello Developers

 If you want to upload image from front website then you can done as follows


//php code for file upload
//condition check if file is selected or not
if ( $_FILES['image_url']['name'] != "" ) {
global $wpdb;
//For Uploading photo from front End
if (!function_exists('wp_generate_attachment_metadata')){
require_once(ABSPATH . "wp-admin" . '/includes/image.php');
require_once(ABSPATH . "wp-admin" . '/includes/file.php');
require_once(ABSPATH . "wp-admin" . '/includes/media.php');
}
$overrides = array( 'test_form' => false);
$file = wp_handle_upload($_FILES['image_url'], $overrides);
$content = $file['url'];
}

you can use $content variable to save file url

your form is look like below

<form method="post" enctype="multipart/form-data">
     <input type="file" name="image_url">
</form>

Friday, 5 December 2014

Google No Captcha

We know to stop spamming we all are used captcha in our form, but its very difficult to understand by user, for this reason Google introduced "Google No Captcha". Please follow below link and try to use this in your form for better user experience.

http://googleonlinesecurity.blogspot.in/2014/12/are-you-robot-introducing-no-captcha.html

Friday, 26 September 2014

How to Install WordPress Plugin and How to Use WordPress Plugin

In WordPress its only provide blog post functions, if you want to more in your site then you have to use WordPress Plugins. Like in our site below Header Section we have a slider. So find the slider plugin over net and download it.

I uses This Plugin
http://www.wonderplugin.com/wordpress-slider/

Download it and Go to Admin Panel.

  • Login with Admin Panel
  • Go to Plugin menu -> Add New
  • From Above Link Choose "Upload"
  • Choose File and Click on "Install Now" Button
  • Click on "Activate Plugin" Link.
Now Its Create a new menu "WonderPlugin Slider";

  • Click on it and click on "Create New Slider" button.
  • Click on "Add Image" Button (Its Open Popup)
  • Click on Upload Button and then click on Select Files
  • After Select Click on "OK" button
  • Add as much Image that you Want and Click on "Save & Publish" button
Now its shows you a SortCode [wonderplugin_slider id="1"]


You can Use this code for shows this slider. This Sortcode work in Wordpress Editor. If you want to show in Your file then you can use this code


<?php echo do_shortcode('[wonderplugin_slider id="1"]'); ?>

This Also Do same work, but its shows in File System.