Category Archives: PHP

How to generate X-WSSE Token using PHP

Learn how to generate X-WSSE Token and how to authorize requests using X-WSSE header authentication.

If you’re not familiar with X-WSSE Token Authentication and why you should use it, go ahead and read this article that contains the basics of this type of authentication.

In this article I’ll describe how to generate a X-WSSE Token using PHP.

function getWsseHeader($username, $secret) {
 
    $nonce = md5(rand());
    $created  = date('c');
    $digest   = base64_encode(hash('sha256', $nonce . $created . $secret, false));
 
    $wsseHeader = sprintf(
        'UsernameToken Username="%s", PasswordDigest="%s", Nonce="%s", Created="%s"',
        $username,
        $digest,
        $nonce,
        $created
    );
 
    return $wsseHeader;
 
}
 
$xwsse = getWsseHeader("CLIENT_ID", "CLIENT_SECRET");
echo $xwsse;

That’s it. Check my other X-WSSE Articles and learn how to generate the token using other programming languages.

What is X-WSSE Token Authentication and how does it work

Learn the basics of X-WSSE Token Authentication and how to authorize requests using X-WSSE header authentication.

X-WSSE Token Authentication can be used to authenticate backend-to-backend integrations using client_id and client_secret properties. The main benefit of this type of authentication is that the client_secret value never leaves the backend of the integrating client, and that each token, even if lost, is only valid for 5 minutes.

The X-WSSE Token is a string with the following format, usually a single HTTP header line which is broke down into multiple lines for easier readability:

X-WSSE: UsernameToken
Username="USERNAME",PasswordDigest="ASDFbasEHAPRo395MBANgoaiERJGJHSOSLGUsernameToken Username="68037425-fa69-49da-8715-fa393dc55471", PasswordDigest="OWRkZGRjMjk3ZjhiOGFhZmMzNGIzMjAwMWIyNmNjY2JkMTM2M2E5OGFlMGM2ZDI3OGIzZmQ5ZDAwY2RiODMzZg==", Nonce="ee2e8c783398782fd63af15141a1cb62", Created="2019-03-14T16:17:24.211Z"==",Nonce="b35f7341829e35d89851497a82894f",Created="2019-03-20T12:10:20Z"

I’ll briefly describe each component of the X-WSSE Token:

X-WSSE

The name of the HTTP header that must be present in order to authorize the request.

UsernameToken

Value represents the authentication method of the use X-WSSE Token. Currently X-WSSE only supports UsernameToken type of authentication.

Username

The client_id property that you should generate for each integration of X-WSSE Token.

PasswordDigest

Field specifies the hashed token that will authorize the reuqest. For each request a new hash must be generated. Check my other posts and learn how to generate the X-WSSE Token using different server-side programming languages

Computing the Password Digest

Computing the password digest involves 5 simple steps:

  1. Generate random 16 byte Nonce formatted as 32 hexadecimal characters.
  2. Retrieve the current timestamp in ISO8601 format.
  3. The properties nonce, timestamp, secret should be concatenated in this order.
  4. Compute the SHA256 hash value of the string from #3 and convert it to hexadecimal format
  5. Encode the value from #5 in BASE64 and obtain the PasswordDigest

Nonce

Random value with the purpose to make your request unique so it cannot be replicated by unknown parties. This string is always 16 bytes long and should be represented as a 32 characters long hexadecimal value.

Created

This field contains the current UTC, GMT, ZULU timestamp (YYYY-MM-DDTHH:MM:SS) according to the ISO8601 format. e.g. 2018-05-20T12:51:45+01:00

Now you know what is a X-WSSE Token and the purpose of each of its components so let’s go to the Implementation. Check my other X-WSSE articles and learn more.


How to build dynamic query in Laravel

Dynamic query allows us to start with a base query and extend it so that we properly filter our data. You probably already used and know what Laravel is and how to create a basic database query.

We’ll cut straight to the problem:

How do we dynamically apply query conditions in Laravel?

Let’s take a look at the following example that I consider quite easy and basic query on a Listing model that has title, description, price, images and date columns:

$title = "planet";
$listings = Listing::where(function($q) use ($title) {
$q->where('title', 'like', $title .'%');
})->get();

This query will return all our documents for which the title has the form planet% (they start with planet word).

You already knew how to achieve this so let’s extend this to a condition based query generation. Follow bellow:

$title = 'planet;
$price_min = 10;
$price_max = 100;
$listings = Listing::select('title', 'description', 'price', 'images', 'date');

// we're only going to filter by title if it's available
if(isset($title) && !empty($title)) {
$listings->where(function($q) use ($title) {
$q->where('title', 'like', $title.'%');
});
}

// but there's more
// what about the price?
if(is_numeric($price_min)) {
$listings->where('price', '>=', $price_min);
}

We’ve now learned how to build a dynamic query and how to add conditions on the run.

So how do we view our results? 1 line:

$listings = $listings->latest()->get();

That’s it. Now go and build you great app!


How to create a basic Google Maps plugin for WordPress

There might be some WordPress plugins out there that could be used to add Google map to posts and pages. Still I didn’t find it necessary to install one when creating it is fun and easy.

Adding the final plugin to a post/page will be done using shortcode.

First of all you must create the plugin directory in wp-content/plugins/plugin_name.

Add two files here, the first an empty index.php and the second plugin_name.php

In order to be able to activate this plugin some basic details need to be added at the beginning:

/**
 * Plugin Name: Custom Google Maps
 * Plugin URI: http://catalinmunteanu.com
 * Description: Create Google Map element using a location query
 * Version: 1.0.0
 * Author: Catalin Munteanu
 * Author URI: http://catalinmunteanu.com
 */

Then we must create a function that will process this plugin’s shortcode:

 

function google_map_print($attrs, $content=null) {
    $item = shortcode_atts(
        array(
            'location' => null
        ),
        $attrs,
        'google-map'
    );

    $result = '<div>';
        $result .= '<iframe
            width="100%"
            height="250"
            scrolling="no" marginheight="0" marginwidth="0"
            frameborder="0" style="border:0"
            src="https://maps.google.com/maps?f=q&hl=en&geocode=&q='.$item['location'].'&aq=t&ie=UTF8&hq=&t=m&z=17&output=embed">
            </iframe>';
    $result .= '</div>';
    return $result;

}

add_shortcode('google-map', 'google_map_print');

 

That’s all. After you activate the plugin you can add it in your posts and pages using the shortcode:

[google-map location="Bucharest"]

Result: