close
Kaspersky Endpoint Security

Welcome to

Kaspersky Endpoint Security


By Kaspersky Endpoint Security


Buetts Zaun Unternehmen



Was Sie erschaffen

Es war einmal, Web-Anwendungen verwendet Monolithen zu sein, die alles von selbst tat. In diesen Tagen, nicht so sehr. Mit Web-Services ihre APIs eröffnet, bewegen sich die Entwickler an Anwendungen von Drittanbietern unter Verwendung von Teilen der Funktionalität-Dinge wie Authentifizierung oder E-Mail-Benutzer zu handhaben.

Während der häufigste Fall ist eine, wo man eine API verwenden, um eine der beliebtesten Online-Dienste (Google, Twitter, usw.) gibt es Zeiten, zu verbinden, wenn beide der Anwendungen, die Sie Ihren eigenen anschließen möchten sind.

Dies geschah einige Zeit mir vor: Ich habe einen benutzerdefinierten Warenkorb als Ruby on Rails erstellt hatte Anwendung und für eine Weile war glücklich, es zu verwenden, zusammen mit einem einfachen HTML-Zielseite. Nach einiger Zeit fand ich jedoch, dass die Zielseite attraktiver zu machen, die ich brauchte es, um etwas zu aktualisieren häufiger aktualisiert. Ich wollte ein Blog, und so war Wordpress die natürliche Wahl.

Mit dem Wordpress-Seite gebaut, alles war gut bis auf eine Kleinigkeit: Wenn Besucher Artikel in den Warenkorb hinzugefügt und dann kam wieder für mehr zu bestellen, sie vergaßen sie Gegenstände zu ihren Warenkorb gelegt hatte! Der Warenkorb und die Web-Site erforderlich, zusammen zu arbeiten. Ich brauchte den Inhalt des Wagens auf der Web-Seite angezeigt werden soll.

Dies war ein Ort für einige API-Entwicklung.

das Warenkorb-API in der Welt durch Belichten und dann ist es aus meiner Wordpress-Theme nennen, würde ich in der Lage sein, die Daten auf elegante Weise zu passieren, ohne jedes System hacken.

In diesem Tutorial über die Lehren dabei, dieses Projekt gelernt, basiert, werde ich den beiden Enden der API-Kommunikation durchlaufen: Zuerst mit Hilfe der Traube Juwel, werden wir eine API erstellen einen Teil eines Ruby on Rails zu belichten basiert in den Warenkorb zu Anwendungen im Außenbereich. Dann werden wir die API verwenden, die den Warenkorb Inhalt abrufen und sie auf einem Wordpress-Seite angezeigt werden soll. Je nachdem, was Ihre Bedürfnisse sind, können Sie feststellen, dass die API zu schaffen ist, was Sie interessiert, oder dass Sie eigentlich nur Interesse an dem Teil über eine externe API von Wordpress-Aufruf. So oder so, ich hoffe, Sie werden das Tutorial nützlich und interessant finden.

Um den Code in diesem Tutorial starten, müssen Sie die folgenden ein:

Ruby on Rails-Version 3.2PHP 5.3 Curl und seine PHP / Apache-Bibliotheken

Zwar gibt es nichts ist wirklich über das Tutorial kompliziert, ist ein grundlegendes Verständnis von Ruby und Ruby on Rails sowie PHP und Wordpress erforderlich.

1. Holen Sie sich das Beispiel Anwendung kennen

Wie Sie eine Ruby on Rails-Anwendung zu einem Wordpress-Website zu verbinden, planen, dann ist es wahrscheinlich sicher Sie bereits eine Rails-Anwendung-und müssen davon ausgehen, vielleicht sogar ein Wordpress-Website-und läuft. Also, für die Bedürfnisse des Tutorial, ich habe eine vereinfachte, aber funktionsfähige Version des Einkaufswagens erstellt, mit Methoden für die grundlegenden Aktionen an Ort und Stelle erforderlich.

Sie können den Beispielcode herunterladen oder einfach nur das Tutorial lesen und es zu einer Rails-Projekt Ihrer eigenen Anwendung.

Das Beispiel Ruby on Rails-Projekt ist nackten Knochen und besteht aus nur ein Modell (ShoppingCart) und eine Steuerung (ShoppingCartController). Im ShoppingCart Modell, werden Sie die folgenden Methoden finden:

find_or_create_with (Token): Diese statische Methode schaut nach oben und gibt einen Warenkorb Objekt mit dem Zeichen gegeben zu identifizieren. Wenn man nicht gefunden wird (oder kein Zeichen gegeben wird), ein neues Warenkorb erstellt und returned.token: Diese Methode gibt einen Token, um den aktuellen Warenkorb object.as_json identifizieren: Diese Methode gibt den Inhalt des Einkaufswagens als JSON formatierten String.

Der Controller enthält ShoppingCartController eine Aktion für Elemente in einen Warenkorb legen. Die Aktion, zu ergänzen, hat zwei Parameter: Token und (Produkt) ID:

Wir werden später auf alle diese zurück, aber jetzt wollen wir die API für den Warenkorb zu arbeiten und zu schaffen.

2. Installieren Sie Traube und erstellen eine API

Jetzt, mit dem Rails-Projekt an Ort und Stelle, ist es Zeit zu beginnen, die API zu schaffen.

Zum Aufbau unserer API, werden wir ein Tool namens Grape verwenden. Grape ist ein Mikro-Framework für die Umsetzung einfach, REST-APIs wie in Situationen, in denen, wie die Entwickler sagen: "Sie nicht über die schweren Hebekraft von großen Frameworks wie Rails brauchen."

The Grape Rahmen kann allein verwendet werden, aber es sitzt auch schön neben Rails, eine einfache Möglichkeit bietet APIs zu erstellen für eine Untergruppe Zugriff (oder warum nicht alle) der Funktionalität Ihrer Rails-Anwendung. Das ist genau das, was wir in diesem Tutorial werden, zu tun.

Schritt 1: Installieren Grape

Um das Juwel zu Ihrem Rails-Projekt, fügen Sie die folgende Zeile in Ihre Gemfile:

Juwel "Traube"

Aktualisieren Sie dann Ihre Edelsteine ​​durch (auf der Kommandozeile) Aufruf:

bundle install

Das ist es. Der Edelstein wurde installiert, und wir können es benutzen.

Schritt 2: Konfigurieren Grape Paths

So starten Sie den API zu schreiben, müssen Sie zunächst eine rubinQuellDatei zu erstellen, die die API-Funktionalität halten wird. Dies ist ein leichtes Rahmen, und so können wir die gesamte API in nur eine Datei schreiben. Speichern Sie diese Datei in Ihrem Rails-Anwendung, in einem Verzeichnis api direkt unter dem Haupt-App-Verzeichnis.

Im Beispielprojekt finden Sie in der API-Code in app / api / cart_external.rb finden.

Fügen Sie die folgenden Zeilen zu Ihrer application.rb Konfigurationsdatei sicherstellen, dass die Dateien in app / api enthalten sind:

config.paths.add "app / api", glob: ". ** / * rb" config.autoload_paths = Dir [ "# {Rails.root} / app / api / *"] Schritt 3: Erstellen Sie das API-Modul

Innerhalb der API-Quelldatei, werden wir jetzt ein Modul definieren, die unsere API-Klasse enthalten wird:

CartExternal Module

Klasse API <Traube :: API-Version 'v1',: mit =>: Pfadformat: json

Helfer beende

Ressource: Warenkorb tun end end

Ende

Dies ist die am blanken Knochen Version des Inhalts eines einfachen Grape API. An dieser Stelle macht es noch nichts, aber lassen Sie uns die Konfigurationselemente am Anfang des Codes innerhalb der Klasse einen Blick.

Zuerst 'V1' die Zeilenversion,: mit =>: Pfad sagt, dass dies Version v1 der API und dass die Version der API-Benutzer möchte, sollte in der URL definiert zuzugreifen, zum Beispiel Andere Optionen für dieses Konfigurationsfeld werden : Header: accept_version_header und: param, von denen jede eine andere Methode der Weitergabe der Versionsinformationen zu definieren. Siehe die Trauben Dokumentation für weitere Informationen zu den einzelnen them.format mit: json Grape scheidende Antworten als JSON formatiert Strings zu kodieren, sagt (: txt und: xml kann auch verwendet werden) .Schritt 4: Montieren Sie die API

Bevor wir Hinzufügen von Funktionen an die API zu starten, als die letzte Installationsschritt, erklären die API-Klasse zu Ihrer Rails-Anwendung, so dass es weiß, dass es um Menschen und Dienstleistungen dienen fordert wird.

Um dies zu tun, fügen Sie die folgende Zeile / routes.rb config:

Mount CartExternal :: API => '/' 2. Stellen Sie die API Do Something

Nun lassen Sie uns wieder auf die CartExternal :: API-Klasse wir oben definiert.

Schritt 1: Eine Ressource definieren

Innerhalb der API-Klasse, werden Sie zwei Elemente finde ich noch nicht erwähnt habe: Helfer und Hilfsmittel.

Helfer ist ein Makro, das zusammen mit einem Block verwendet werden kann (oder ein Modul) Hilfsmethoden einzuführen, die dann innerhalb der API-Aktionen verwendet werden kann. Diese Verfahren können zum Beispiel Helfer sein notwendig, um API-Parameter oder Methoden zur Kontaktierung der Eltern Rails überprüfen application.resource eine logische Sammlung von API-Methoden definiert. Sie können so viele, wie Sie wollen, aber in unserem Fall werden wir mit nur einem feinen tun, die wir nennen werden: Warenkorb gelegt. Diese Ressource wird alle API-Methoden enthalten in den Warenkorb bezogen. Mit diesen Definitionen, werden alle Anrufe werden zu unserer Ressource geleitet werden und die Aktionen in der es definiert. Schritt 2: Erstellen einer ersten API Aktion

Um zu sehen, wie das funktioniert, lassen Sie uns zunächst einen API-Aufruf zu schaffen für die Artikel in einem Warenkorb Abrufen durch den Parameter-Token identifiziert.

Im Inneren des Ressourcen-Block, fügen Sie den folgenden Code:

desc '. Zurück Artikel im Warenkorb' params tun optional: Token, Typ: String, default: nil Ende get '/ items' = do Token params [: token]

Warenkorb = ShoppingCart.find_or_create_with Token

Antwort = {status: 200, Zeichen: cart.token, Warenkorb: cart.as_json}

response.as_json Ende

Nun haben wir eine Aktion erstellt, die den Pfad / Artikel gesendete Anfragen GET reagiert.

Die Handlung spielt einen optionalen String-Parameter, Token, im params Block deklariert. Es ist zwar nicht zwingend Parameter zu erklären, ist es gute Praxis, wie es Ihr Code besser lesbar und spart Ihnen Zeit als Traube macht für Sie den größten Teil der Parameterüberprüfung tun. Für erforderlichen Parameter können Sie ein ähnliches Konstrukt verwenden, mit erfordert optional zu ersetzen. Erforderliche Parameter können keinen Standardwert haben.

Unsere Aktion sieht einen Einkaufswagen auf, der das Token übereinstimmt oder ein neues erstellt, wenn kein Token weitergegeben wird. Dann gibt es eine JSON-codierte Antwort, die von einem Status besteht, dem tatsächlichen Warenkorb-Token, und der Inhalt des Einkaufswagens.

Schritt 3: Testen Sie die API-Aktion

Wenn Sie Ihre Rails-Anwendung lokal ausgeführt werden, können Sie jetzt Ihre Server zu starten und in Ihrem Browser um die Antwort zu sehen, die wie folgt aussehen etwas sollte:

{“status”:200,”token”:”XBrf2nCkTYfQJoU8d4A1nw”,”cart”:{“item_count”:0,”items”:[]}}

Da wir nicht bestanden hat wurde ein Token in unseren Aufruf, ein neues Einkaufswagen angelegt und eine zufällig generierte, eindeutige Tokenwert zugewiesen. Das ist auch, warum der Wagen ist noch leer.

Wenn Sie möchten, für die Prüfung, können Sie die Aktion hinzufügen in ShoppingCartController verwenden einen Artikel in den Warenkorb zu legen:

Nach dem Hinzufügen des Produkts, wenn Sie die API erneut aufrufen, werden Sie, dass jetzt bemerken, dass es sich um ein Angebot in den Warenkorb gelegt:

{“status”:200,”token”:”XBrf2nCkTYfQJoU8d4A1nw”,”cart”:{“item_count”:1,”items”:[{“cart_id”:2,”created_at”:”2014-05-20T16:44:24Z”,”id”:4,”product_id”:1,”product_name”:”Test Produkt "," PRODUCT_PRICE ":" 10.0 "," updated_at ":" 2014-05-20T16: 44: 24Z "}]}}

Fügen Sie so viele Artikel, wie Sie möchten, und dann, bevor sie eine weitere Funktionalität hinzufügen, lassen Sie uns das Setup abzuschließen und haben Wordpress an die API sprechen.

3. Rufen Sie die API von Wordpress

Wir haben getestet nun die API, indem sie es von einem Web-Browser aufrufen und als nächstes ist es Zeit zu Wordpress machen mit ihm kommunizieren.

Der Code Wordpress, die folgt, kann entweder in einem Wordpress-Plugin enthalten sein oder in einer functions.php des Wordpress-Theme abhängig von Ihrem Projekt und Kontext, wo die API-Kommunikation benötigt wird. In meinem eigenen Warenkorb-Integration, entschied ich mich, den Code in ein Kind Thema der Einfachheit halber hinzuzufügen.

Unabhängig davon, welche Art und Weise Sie sich entscheiden zu gehen, wird der Code gleich sein.

Schritt 1: Erstellen Sie eine Funktion, die API für den Aufruf

Öffnen Sie Ihre functions.php-Datei (oder ein geeignetes Plugin PHP-Datei) und fügen Sie die folgende PHP-Funktion. Es ist eine Hilfsfunktion, die die API-Kommunikation kapselt, so dass in der Zukunft, wenn Sie die Signatur-API oder andere generische Elemente in den Aufrufen ändern müssen, können Sie es an einem Ort tun können.

Hier sind die nackten Knochen von dem, was in dieser Funktion sein muss:

Funktion api_get_as_json ($ action, $ params) {

$ Api_endpoint = "

if (null == $ params) {$ params = array (); }

// Erstellen URL mit params $ url = $ api_endpoint. $ Action. '?'. http_build_query ($ params);

// Verwenden curl die Abfrage $ ch = curl_init () zu machen;

curl_setopt_array ($ ch, array (CURLOPT_URL => $ url, CURLOPT_RETURNTRANSFER => true));

$ Output = curl_exec ($ ch);

// Decode Ausgang in ein Array $ json_data = json_decode ($ Ausgabe, true);

curl_close ($ ch);

return $ json_data; }

Die Funktion nimmt in dem Pfad zu dem API Aktion und der erforderlichen Parameter, kombiniert sie in eine URL und verwendet dann cURL eine Anforderung an die API zu machen.

Nach Erhalt der Antwort, analysiert die Funktion, die sie in ein Array mit json_decode, eine Funktion, die ein Teil der Standard-PHP-Bibliotheken ist.

Schritt 2: Die API-Aufruf und Render-Antwort

Nun, da wir die Funktionalität für den Aufruf der API erstellt haben, nutzen wir sie den Inhalt des Einkaufswagens durch unsere API-Methode / Warenkorb / Artikel abzufragen und dann aus der Antwort drucken:

Funktion show_shopping_cart () {$ cart_data = api_get_as_json ( '/ Elemente', null); ?> <Div class = "shopping-cart"> <h3> Warenkorb </ h3> <ul> <? Php if (isset ($ cart_data [ "Warenkorb"] [ "items"]) && $ cart_data [ "Warenkorb "] [" items "] Länge> 0):.?>

<? Php foreach ($ cart_data [ "Warenkorb"] [ "items"] as $ item):>? <Li> <? Php echo $ item [ "product_name"]; ?> $ <? Php echo $ item [ "PRODUCT_PRICE"]; ?> </ Li> <? Php endforeach; ?>

<? Php else:?>

Dein Einkaufswagen ist leer.

<? Php endif; ?> </ Ul>

<div style=”margin-top: 20px;”> <pre style=”font-size: 8pt;”><?php print_r($cart_data); ?></pre> <?php }

The function makes an API call to /items and prints out the response with some basic HTML formatting. At the end of the function, I included a simple print_r block to render the contents of the JSON response for debugging purposes. 

This is useful especially in the beginning, when the cart is still empty and we want to make sure there are no communication errors preventing the code from showing its contents.

Step 3: Hook the Function to WordPress

Now that we have the functions for making the call and printing the response in place, all that is left is making WordPress call them. 

The simplest way to do this would be to go straight to the theme’s template files and just call show_shopping_cart right there in the place where you want to show the shopping cart. If the theme is your own and you are sure this is all you need, it might be a viable option. 

At the other end of the spectrum is the most flexible and user friendly approach of embedding the call into a WordPress widget. This way, you can move the shopping cart around and place it in any sidebar area on your WordPress site. It’s not all that hard, so let’s go ahead and do that. 

All we need is a WP_Widget sub class with a constructor and some code for rendering the shopping cart contents in the function widget. The two other functions, form and options can be left empty for now (if you want to add customization to the widget, this is where it will go). 

class ShoppingCartWidget extends WP_Widget {

public function __construct() { parent::__construct( ‘shopping_cart_widget’, __( ‘Shopping Cart Widget’, ‘shopping_cart’ ), array( ‘description’ => __( ‘A widget for displaying a shopping cart.’, ‘shopping_cart’ ) ) ); }

/** * Outputs the content of the widget */ public function widget( $args, $instance ) { echo $args[‘before_widget’];

show_shopping_cart();

echo $args[‘after_widget’]; }

/** * Outputs the options form. */ public function form( $instance ) { // The widget takes no options }

/** * Processing widget options on save */ public function update( $new_instance, $old_instance ) { // The widget takes no options }

}

function register_shopping_cart_widget() { register_widget( ‘ShoppingCartWidget’ ); } add_action(‘widgets_init’, ‘register_shopping_cart_widget’);

Now, go to your WordPress admin, and drag the widget Shopping Cart Widget to one of your sidebars:

Now, visit the WordPress site to see the code in action. You should see something like this:

Your shopping cart is still empty, but as you can see from the print_r output below the shopping cart, the communication works and the WordPress blog is receiving data from our Rails application.

Now, with the basics covered, let’s look at making the communication a bit more secure.

4. Secure the Connection With an API Key

We have now built an API for a Ruby on Rails application and called it from a WordPress site; however, there is still something important missing: securing the API so that it’s not open for everyone on the Internet to call as they like. I’m sure you can think of all kinds of bad things that would happen if you left the door completely open for everyone, right?

A simple way to secure an API is to generate a secret key for every application you allow to call your API. This way, whenever an application makes a request to the API, it needs to send its API key for the server to check. Callers without a valid API key will not be allowed to make requests. For added security, most services also include an API secret in addition to the API key.

So now, let’s get back to work and add the API key, first to our Ruby code and then on the WordPress side.

Step 1: Add a Method for Checking the API Key

First, add a method for checking the API key. This one goes in the helpers block of your API class:

def is_valid_api_key?(key) key == ‘API_KEY’ end

This is a simple version with just one API key, so depending on your application you might have to extend it. For example, if you have multiple applications calling the API, you will need to define a unique API key for each of them and store them in the database. You might also want to create an admin page for creating new API keys. 

At the very least, you need to replace API_KEY with a real, generated key that is not too easy to guess. For this example however, all that matters is that you have an API key and a method for checking that the key passed in matches with the one stored in the system.

Step 2: Use the Helper Method to Verify an API Key

With the helper method in place, we can add the check to our one and only API call by surrounding the code in it with the following if…else construct:

if is_valid_api_key? params[:key] token = params[:token]

cart = ShoppingCart.find_or_create_with token

response = { status: 200, token: cart.token, cart: cart.as_json }

response.as_json else error!(‘401 Unauthorized’, 401) end

Notice the else block where we raise an error using the Grape method error!.

Now, restart the Rails server and reload your WordPress home page and you will see something like this:

This is because we haven’t yet add the API key to our WordPress code and so the Rails API no longer accepts the requests it makes. If you like, at this point, you can add some proper error handling and display a nice error message. 

Then, let’s move on and make the API call work again.

Step 3: Add Settings Field for API Key

For now, you could just go ahead and hard code the API key in your api_get_as_json function, but as adding new options to the WordPress General Settings page is very straightforward, let’s do this through a settings field. 

And while add it, we can also add an option for defining the URL for the API. 

This way, later when you deploy the WordPress code to an actual live server, you will be able to configure it without having to touch the code—which is always nice.

$cart_api_settings_field = new CartApiSetting();

class CartApiSetting { function CartApiSetting() { add_filter( ‘admin_init’, array( $this , ‘register_fields’ ) ); }

function register_fields() { register_setting( ‘general’, ‘cart_api_key’, ‘esc_attr’ );

add_settings_field( ‘cart_api_key’, ‘<label for=”cart_api_key”>’ . __( ‘Shopping Cart API key’ , ‘shopping_cart’ ).'</label>’ , array( $this, ‘fields_html’ ) , ‘general’ ); }

function fields_html() { $value = get_option( ‘cart_api_key’, ” ); echo ‘<input type=”text” id=”cart_api_key” name=”cart_api_key” value=”‘ . $value . ‘” />'; } }

Here’s the settings field definition for the API endpoint URL using the same construct:

$cart_api_endpoint_settings_field = new CartApiEndpointSetting();

class CartApiEndpointSetting { function CartApiEndpointSetting() { add_filter( ‘admin_init’, array( $this, ‘register_fields’ ) ); }

function register_fields() { register_setting( ‘general’, ‘cart_api_endpoint’, ‘esc_attr’ );

add_settings_field( ‘cart_api_endpoint’, ‘<label for=”cart_api_endpoint”>’ . __( ‘Shopping Cart API URL’ , ‘shopping_cart’ ).'</label>’ , array( $this, ‘fields_html’ ) , ‘general’ ); }

function fields_html() { $value = get_option( ‘cart_api_endpoint’, ” ); echo ‘<input type=”text” id=”cart_api_endpoint” name=”cart_api_endpoint” value=”‘ . $value . ‘” />'; } }

Visit your WordPress General Settings menu to set the proper values for these settings, making sure the API key matches with whatever you have set its value to be in your Rails service.

Step 4: Pass API Key With API Requests

Now, with the API key and URL stored in the WordPress options, let’s update the function that makes the API call. 

The changes go at the beginning of the function, like this:

function api_get_as_json($action, $params) {

if ( null == $params ) { $params = array(); }

$api_key = get_option( “cart_api_key” ); $api_endpoint = get_option( “cart_api_endpoint” );

if ( ! isset( $api_key ) || ! isset( $api_endpoint ) ) { return false; }

$params[“key”] = $api_key;

}

Looking at the new code above, you will notice that the $api_key and $api_endpoint settings are read from WordPress options. $api_endpoint was already used to create the URL to call, but for $api_key, we need to add a line (14) to include the value in the parameters sent to the API.

Refresh your WordPress home page and the shopping cart contents pop up again, this time secured with an API key. Everything looks good—actually, the same as before requiring the API key—and you have connected the Rails application with your WordPress site.

5. Add a Shared Session

The WordPress code we have written so far makes API calls and secures them with an API key, but does so in a completely stateless way. For simple, stateless actions such as posting updates to a message board or your own Twitter like microblogging platform, one-off calls like this are all you need. However, for our shopping cart example, this is not quite enough. 

As you notice when testing the code, while our Rails server identifies a shopping cart with a token, we haven’t used this token anywhere, so every time a call to cart/list is made, the server creates a new, empty shopping cart.

Not very good. For a shopping cart connection to be of any use, you need to be able to add items to your cart and keep them there for a while, even as you move from one page to the other. 

In one word, you need a session.

There are multiple ways you could create a session, but let’s go with the simplest one, using the token passed to us by the Rails application and storing it in a client cookie. As your WordPress site is the interface the user (and her web browser) sees and communicates with, that’s also where we need to set the cookie.

Step 1: Set a Cookie

Cookies can only be set in the header, before any content has been rendered, so we need to do some rearranging in the code, moving the /cart/items call up in the execution flow. To do this, let’s create a new PHP function, get_shopping_cart, and call it right at the beginning of the WordPress site’s execution.

This can be done using WordPress action hooks. For a full list of hooks, you can look at the WordPress Codex. In this case, the action init does what we need, so let’s hook our request to that one.

add_action( “init”, “get_shopping_cart” );

The function get_shopping_cart itself looks like this:

function get_shopping_cart() {

$cart_data = api_get_as_json( ‘/items’, null ); $token = $cart_data[‘token’];

// Expire cookie in 30 minutes setcookie( ‘bread_cart’, $token, time() 60 * 30 ); set_saved_cart_data( $cart_data );

}

First, the function makes the by now familiar call to our /items API action. Then we have something new: on line 3, we extract the shopping cart token returned by the API and then, a couple of lines later, save it in a cookie. The cookie is set to expire in 30 minutes as I assume someone shopping in an online store will have forgotten about the shop by that time…

On line 7, you may notice another new function call: set_saved_cart_data. We’ll get back to it in just a minute. But first, let’s make the API calls use the token too. 

Step 2: Use the Token From the Cookie

First, let’s create a helper function to retrieve the token from the cookie:

function api_shopping_cart_token() {

$token = null;

if ( isset( $_COOKIE[‘shopping_cart_token’] ) ) { $token = $_COOKIE[‘shopping_cart_token’]; }

return $token; }

And then, using that function, add the following line to api_get_as_json, right after the line where we set the API key parameter:

$params[‘token’] = api_shopping_cart_token();

With this addition, every time a call to the API is made, the method api_get_as_json looks up the shopping cart token from the cookie and adds it to the request parameters. If a cookie isn’t found, the API will receive an empty token and treat the call as a new visitor, creating a new, empty shopping cart.

Step 3: Optimize Execution By Saving Some Data

And now, back to set_saved_cart_data.

As we notice in the code above, get_shopping_cart receives the full contents of the shopping cart—the very same data that we are querying in show_shopping_cart. This means that we are calling the API twice in one WordPress page render when one call should be enough. Saving the response for the HTTP request’s duration is a simple optimization that we can use to reduce the number of API calls into half.

In PHP, global variables are specific to and only live through one HTTP request, so we can safely use one for storing the data from get_shopping_cart to the point where it is used for actually rendering the shopping cart contents. 

To do this, I have created a simple pair of functions, set_saved_cart_data and get_saved_cart_data, which wrap the global variable $g_shopping_cart_data to keep the code readable and easy to maintain: 

global $g_shopping_cart_data;

function set_saved_cart_data( $cart_data ) {

global $g_shopping_cart_data; $g_shopping_cart_data = $cart_data;

}

function get_saved_cart_data() {

global $g_shopping_cart_data; return $g_shopping_cart_data;

}

With the shopping cart data stored to a global variable, all you need to do is to change the first line in show_shopping_cart to:

$cart_data = get_saved_cart_data();

With this change done, the shopping cart now has a session and the user can add items to the cart and move between pages while still seeing the same shopping cart. 

Step 4: Test By Adding Some Items to Cart

To test the functionality, let’s create a link to the controller action shopping_cart/add and print it out at the end of show_shopping_cart. Notice, that for the controller to share our session it too needs the shopping cart token as a parameter:

$product_id = 1;

$token_params = http_build_query(array(‘token’ => api_shopping_cart_token())); $url = “. $product_id . “?” . $token_params;

echo ‘

<a href=”‘ . $url . ‘”>Add test item to cart</a>

';

Click on the link, Add test item to cart, to add an item. Then return to your WordPress site and now you can see an item from the shopping cart appear on the WordPress blog!

Some Final Words

That’s it: you have now successfully connected a Ruby on Rails based shopping cart to your WordPress blog or web site. 

Remove the print_r debugging, style the output with some CSS and create some real “Add to Cart” links (as well as a “Check Out” button that leads the user back to the actual shopping cart application) and you have a fully functional shopping cart integration.

More importantly, however, you can use the method of creating and talking back to an API to link two applications of your own. They could be anything, so now, go ahead and create some APIs!


Endpoint-Security 2012     Endpoint-Security-10 Download

Categories and tags