Lo que va a crear
Había una vez, las aplicaciones web solían ser monolitos que hicieron todo por sí mismos. En estos días, no tanto. Con los servicios web de abrir sus API, los desarrolladores se están moviendo a la utilización de aplicaciones de terceros para manejar partes de la funcionalidad, cosas tales como la autenticación de usuarios o envío por correo electrónico.
Mientras que el caso más común es uno en el que utiliza una API para conectarse a uno de los servicios en línea (Google, Twitter, etc.) hay momentos en los que las dos aplicaciones que desee conectar son el suyo propio.
Esto me sucedió hace algún tiempo: yo había creado un carrito de la compra personalizado como una aplicación Ruby on Rails y, por un tiempo, estaba dispuesto a utilizarlo junto con una página HTML normal de aterrizaje. Después de algún tiempo, sin embargo, he encontrado que para hacer la página de destino más atractivo, que necesitaba para actualizarlo a algo más actualizada con frecuencia. Yo quería un blog, y así WordPress era la elección natural.
Con el sitio de WordPress construida, todo estaba bien, excepto por una pequeña cosa: cuando los visitantes artículos a la cesta de la compra añadir y luego regresó a la tienda para más, se olvidaron que habían añadido artículos a su cesta de la compra! El carrito de la compra y el sitio web necesarios para trabajar juntos. Que necesitaba para mostrar el contenido de la cesta en el sitio web principal.
Este era un lugar para un cierto desarrollo de la API.
Al exponer la API de carrito de compras para el mundo y luego llamar desde mi tema de WordPress, me gustaría ser capaz de pasar los datos de una manera elegante, sin piratería cualquiera de los sistemas.
En este tutorial, basado en las lecciones aprendidas en hacer este proyecto, voy a ir a través de los dos extremos de la comunicación API: En primer lugar, con la ayuda de la gema de la uva, vamos a crear una API para exponer una parte de un rubí en los carriles basada carro de compras para aplicaciones exteriores. A continuación, vamos a utilizar la API para recuperar el contenido del carrito de compras y mostrarlos en un sitio de WordPress. Dependiendo de cuáles son sus necesidades, puede encontrarse con que la creación de la API es lo que te interesa o que son en realidad sólo está interesado en la parte en llamar a una API externa de WordPress. De cualquier manera, espero que encontrará el tutorial útil e interesante.
Para ejecutar el código en este tutorial, necesitará la siguiente configuración:
Ruby on Rails versión 5.3 3.2PHP Curl y sus bibliotecas de PHP / Apache
Si bien no hay nada realmente complicado sobre el tutorial, una comprensión básica de Ruby y Ruby on Rails, así como PHP y WordPress se requiere.
1. Conozca el ejemplo de aplicación
Como usted está planeando para conectar un Ruby on Rails aplicación a un sitio web de WordPress potencia, es probablemente seguro asumir que ya tiene una aplicación en Rails y tal vez incluso un sitio de WordPress en marcha y funcionando. Por lo tanto, para las necesidades del tutorial, he creado una versión simplificada y funcional de la cesta de la compra, con los métodos de las acciones básicas que se requieren en su lugar.
Puede descargar el código de ejemplo o simplemente leer el tutorial y aplicarlo a un proyecto Rieles de su cuenta.
El proyecto de ejemplo Ruby on Rails es bastante básico y consiste en sólo un modelo (ShoppingCart) y un controlador (ShoppingCartController). En el modelo ShoppingCart, se encuentran los siguientes métodos:
find_or_create_with (token): Este método estático mira hacia arriba y devuelve un objeto con el carrito de la compra Dada la identificación simbólica. Si uno no se encuentra (o se da ninguna ficha), una nueva cesta de la compra se crea y returned.token: Este método devuelve una ficha de identificación de la corriente carrito de la compra object.as_json: Este método devuelve el contenido de la cesta de la compra como JSON cadena con formato.
El controlador, ShoppingCartController contiene un recurso de añadir elementos a un carrito. La acción, añadir, toma dos parámetros: ficha y (producto) Identificación:
Nos pondremos en contacto con todos ellos más tarde, pero ahora, vamos a llegar a trabajar y crear la API para el carrito de compras.
2. Instalación de uva y crear una API
Ahora, con el proyecto de rieles en su lugar, es el momento de empezar a crear la API.
Para construir nuestra API, vamos a utilizar una herramienta llamada uva. La uva es una micro-marco diseñado para la aplicación de las API REST simples, similar en situaciones en las que, como dicen los desarrolladores, "que no es necesario el poder levantar objetos pesados de grandes marcos como rieles."
El marco de la uva puede ser utilizado por sí solo, sino que también se asienta muy bien al lado de los carriles, que proporciona una manera fácil de crear APIs para acceder a un subconjunto (o por qué no todos) de la funcionalidad de su aplicación Rails. Que es exactamente lo que vamos a hacer en este tutorial.
Paso 1: Instalación de uva
Para añadir la gema para su proyecto Rails, agregue la siguiente línea a su Gemfile:
joya 'uva'
A continuación, actualice sus gemas llamando (en la línea de comandos):
bundle install
Eso es. La gema se ha instalado y podemos empezar a utilizarlo.
Paso 2: configurar rutas de uva
Para comenzar a escribir la API, primero tiene que crear un archivo de origen de rubí que llevará a cabo la funcionalidad de la API. Este es un marco ligero, y por lo que podemos escribir toda la API en un solo archivo. Coloque este archivo dentro de su aplicación Rails, en un directorio llamado derecho API en el directorio principal de la aplicación.
En el proyecto de ejemplo, se encuentra el código de la API en app / api / cart_external.rb.
Añadir las siguientes líneas al archivo de configuración application.rb para asegurarse de que los archivos de aplicación / api se incluyen:
config.paths.add "aplicación / api", glob: "rb. ** / *" config.autoload_paths = Dir [ "# {} Rails.root / app / api / *"] Paso 3: Crear el módulo API
Dentro del archivo de la fuente API, ahora vamos a definir un módulo que contendrá nuestra clase API:
módulos CartExternal
API clase <uva :: API versión 'v1',: usando =>: formato de ruta: JSON
ayudantes terminan
de recursos: compra si terminar finales
fin
Esta es la versión más huesos desnudo de los contenidos de un simple API de uva. En este punto, no hace nada, pero vamos a echar un vistazo a los elementos de configuración al inicio del código dentro de la clase.
En primer lugar, la versión de línea 'v1',: usando =>: path dice que esta es la versión v1 de la API y que la versión del usuario de la API quiere acceder deben definirse en la URL, por ejemplo Otras opciones para este campo de configuración se : cabecera,: accept_version_header y: param, cada uno de ellos la definición de un método diferente de pasar la información de la versión. Consulte la documentación de la uva para obtener más información sobre cómo utilizar cada uno de them.format: JSON dice uva para codificar las respuestas salientes como cadenas con formato JSON (txt y: xml también se puede utilizar) .step 4: Montar el API
Antes de empezar la adición de la funcionalidad de la API, como el paso final de la instalación, declarar la clase API para su aplicación Rails para que sabrá que tiene que servir a las personas y servicios que lo soliciten.
Para ello, agregue la siguiente línea a config / routes.rb:
montaje CartExternal :: API => '/' 2. Asegúrese de la API de Hacer Algo
Ahora, vamos a volver a la clase API CartExternal :: definimos anteriormente.
Paso 1: definir un recurso
Dentro de la clase API, se encuentran dos elementos que no he mencionado aún: ayudantes y de los recursos.
ayudantes es una macro que se puede utilizar junto con un bloque (o un módulo) para introducir métodos de ayuda, que luego pueden ser utilizados dentro de las acciones de la API. Estos métodos pueden ser, por ejemplo ayudantes necesarios para verificar los parámetros o métodos de la API para hacer contacto con los rieles de padres application.resource define una colección lógica de métodos de la API. Se pueden añadir tantos como quiera, pero en nuestro caso nos va a hacer bien con sólo uno, que llamaremos: la compra. Este recurso contendrá todos los métodos de la API relacionadas con el carrito de la compra. Con estas definiciones, las llamadas realizadas a serán enviados a nuestro recursos y las acciones definidas en el interior de la misma. Paso 2: Creación de la primera acción de la API
Para ver cómo funciona esto, vamos a empezar por la creación de una llamada a la API para recuperar los artículos en un carro de compras, identificados por el testigo de parámetro.
En el interior del bloque de recursos, agregue el código siguiente:
desc '. Los artículos de vuelta en su cesta params' hacen opcional: ficha, tipo: String, por defecto: nulo final get '/' do elementos token = params [: fichas]
= carrito de contadores ShoppingCart.find_or_create_with
respuesta = {status: 200, token: cart.token, cesta: cart.as_json}
final response.as_json
Ahora, hemos creado una acción que responde a las peticiones GET enviados a la ruta / artículos.
La acción tiene un parámetro de cadena opcional, contador, declarada en el bloque params. Si bien no es obligatorio declarar los parámetros, es una buena práctica ya que hace que el código sea más fácil de leer y también le ahorra tiempo ya que la uva va a hacer la mayor parte de la validación de parámetros para usted. Para los parámetros requeridos, se puede utilizar una construcción similar, en sustitución opcional con requiere. Los parámetros requeridos no pueden tener un valor por defecto.
Nuestra acción se ve un carro de compras que coincide con la señal o crea uno nuevo si no se pasa el token. A continuación, se devuelve una respuesta codificada JSON que consiste en un estado, el token real carrito de la compra, y el contenido de la cesta de la compra.
Paso 3: Prueba de la acción de la API
Si se está ejecutando la aplicación Rails localmente, ahora se puede iniciar el servidor y escribir en el navegador para ver la respuesta, que debe ser algo como esto:
{“status”:200,”token”:”XBrf2nCkTYfQJoU8d4A1nw”,”cart”:{“item_count”:0,”items”:[]}}
Como no pasó un token en nuestro llamado, una nueva cesta de la compra se crea y se le asigna un valor de token generado de forma aleatoria, única. Esa es también la razón por la compra está vacía.
Si lo desea, para la prueba, se puede utilizar la acción de añadir en ShoppingCartController para agregar un artículo a la cesta:
Después de añadir el producto, cuando se llama a la API de nuevo, se dará cuenta de que ahora hay un elemento de la cesta:
{“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 Producto "," PRODUCT_PRICE ":" 10,0 "," updated_at ":" 2014-05-20T16: 44: 24Z "}]}}
Añadir tantos elementos como desee, y luego, antes de añadir cualquier funcionalidad más, vamos a completar la configuración y tienen WordPress hablar con la API.
3. Llame a la API de WordPress
Ahora hemos probado la API llamando desde un navegador web y el próximo, es el momento de hacer WordPress comunicarse con él.
El código de WordPress que sigue se puede incluir ya sea en un plugin de WordPress o en functions.php de un tema de WordPress en función de su proyecto y el contexto de donde es necesaria la comunicación API. En mi propio carrito de compras integración, decidí agregar el código en un tema menor para la simplicidad.
Cualquiera sea la forma que decida ir, el código será el mismo.
Paso 1: Crear una función para llamar a la API
Abra el archivo functions.php (o un archivo PHP plug-in adecuado) e insertar la siguiente función de PHP. Es una función auxiliar que encapsula la API de comunicación para que en el futuro, si es necesario cambiar la API de firma u otros elementos genéricos en las llamadas, puede hacerlo en un solo lugar.
Éstos son el esqueleto de lo que se necesita para estar en esa función:
api_get_as_json función ($ action, $ params) {
$ Api_endpoint = "
Si (null == $ params) {$ params = array (); }
// Crear URL con params $ url = $ api_endpoint. $ acción. '?'. http_build_query ($ params);
// Usar rizo para hacer la consulta $ ch = curl_init ();
curl_setopt_array ($ ch, array (CURLOPT_URL => $ url, CURLOPT_RETURNTRANSFER => true));
$ Salida = curl_exec ($ ch);
// Salida de decodificación en un array $ json_data = json_decode ($ salida, true);
curl_close ($ ch);
devolver $ json_data; }
La función toma en el camino a la acción de la API y los parámetros requeridos, las combina en una URL y luego utiliza cURL para hacer una petición a la API.
Después de recibir la respuesta, la función analiza en una matriz, utilizando json_decode, una función que es una parte de las bibliotecas de PHP estándar.
Paso 2: Llame a la API y Render respuesta
Ahora que hemos creado la funcionalidad para llamar a la API, vamos a utilizar para consultar el contenido de la cesta de la compra a través de este método API / compra / artículos y luego imprimir la respuesta:
show_shopping_cart función () {$ cart_data = api_get_as_json ( '/ artículos', null); ?> <Div class = "carrito de compras"> <h3> Compras </ h3> <ul> <? Php if (isset ($ cart_data [ "compra"] [ "elementos"]) && $ cart_data [ "cesta "] [" elementos "] de longitud> 0):.?>
<? Php foreach ($ cart_data [ "compra"] [ "elementos"] como $ item):>? <Li> <? Php echo $ item [ "product_name"]; ?> $ <? Php echo $ item [ "PRODUCT_PRICE"]; ?> </ Li> <? Php endforeach; ?>
<? Php otra cosa:?>
Su cesta está vacía.
<? 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!
.