[go: nahoru, domu]

Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

New Documentation #377

Draft
wants to merge 2 commits into
base: dev
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Next Next commit
First push for new docs
  • Loading branch information
seb86 committed Apr 17, 2023
commit d2da357d1734cf83dc3ef21efade9d70bdbe173e
69 changes: 69 additions & 0 deletions docs/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,69 @@
# CoCart Handbook <!-- omit in toc -->

The CoCart API is written entirely in PHP, and reuses a lot of the existing cart logic (and filter hooks) within WooCommerce. As a result, many plugins that were originally built for the shortcode-based cart will continue to work with the CoCart API that consume it.

If your plugin is making heavy use of PHP templates, or utilizes hooks included in core templates of WooCommerce, you will probably need to use some of our own filter hooks to match the same data result in the CoCart API.

This handbook will help you with what you need.

## Table of Contents <!-- omit in toc -->

- [Introduction](#introduction)
- [API Reference](#api-reference)
- [Plugin Features](#plugin-features)
- [Third party developers](#third-party-developers)
- [Developer Resources](#developer-resources)
- [Tools](#tools)
- [Articles](#articles)
- [Tutorials](#tutorials)

## Introduction

New to CoCart or the REST API in general. [Read our introduction](intro-to-cocart.md) to CoCart to help you get started.

## API Reference

- [Cart API](API/cart.md)
- [Products API](API/products.md)
- [Sessions API](API/sessions.md)

## Plugin Features

- [Load Cart from Session](load-cart-from-session.md)
- [Rate Limiting Guide](rate-limit-guide.md)
- [Override Item Price](override-item-price.md)

## Third party developers

> Are you a third-party developer? The following documents explain how to extend the CoCart plugin with your custom extension.

* Hooks
* * [Actions](https://coderef.cocart.dev/reference/hooks/)
* * [Filters](https://coderef.cocart.dev/reference/hooks/)
* REST API
* [Adding product validation for a custom product type](#)
* [Adding a custom callback for updating the cart](#)
* [Extending details for each cart item](#)
* [Extending the cart response](#)

## Developer Resources

### Tools

### Articles

The following posts from [cocart.dev](https://cocart.dev) provide deeper insights into CoCart's development.

### Tutorials

The following tutorials from [cocart.dev](https://cocart.dev) help you with extending various parts of CoCart. Our [code reference](https://coderef.cocart.dev/) will also provide you with a catalogue of classes, functions, hooks and methods that you can use.

* [Convert cart to order using WC REST API](#)

<!-- FEEDBACK -->

---

🐞 Found a mistake, or have a suggestion? [Leave feedback about this document here.](https://github.com/co-cart/co-cart/issues/new?assignees=&labels=type%3A+documentation&template=doc_feedback.md&title=Feedback+on+./docs/README.md)

<!-- /FEEDBACK -->
196 changes: 196 additions & 0 deletions docs/how-to-create-and-access-cart.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,196 @@
# How to create a cart session and access it <!-- omit in toc -->

## Table of Contents <!-- omit in toc -->

- [Where are the cart sessions stored?](#where-are-the-cart-sessions-stored)
- [How is a cart session created?](#how-is-a-cart-session-created)
- [What is a Cart Key?](#what-is-a-cart-key)
- [Can I create a Cart Key of my own?](#can-i-create-a-cart-key-of-my-own)
- [How does CoCart access the cart session?](#how-does-cocart-access-the-cart-session)
- [For a Guest Customer](#for-a-guest-customer)
- [Finding the Cart Key](#finding-the-cart-key)
- [Updating the cart as a guest](#updating-the-cart-as-a-guest)
- [For a Registered Customer](#for-a-registered-customer)
- [How do I authenticate for a registered customer?](#how-do-i-authenticate-for-a-registered-customer)

## Where are the cart sessions stored?

CoCart creates a single table in your WordPress database upon installing to store the cart sessions. The table name is `cocart_carts`. You will see a prefix in front of the table name based on your WordPress configuration so by default it would be labelled as `wp_cocart_carts`.

## How is a cart session created?

A cart session is created after the first product is added to the cart. Once that cart session is created in the database to save the users cart information, it is given a unique cart key, an expiration timestamp and when the cart will expire if not updated since.

## What is a Cart Key?

A cart key is what identifies the cart session stored in the database.

## Can I create a Cart Key of my own?

If you are wanting to create a cart key of your own for guest customers, it cannot be longer than _42 characters_ as that is the limit for storing the key in the database.

> A cart session will not be created with your cart key until the first item is added to the cart.

## How does CoCart access the cart session?

When requesting the cart session via the Cart API, you first have to decide on the state of the user. Are they a returning customer or a guest customer? Following the state of the user is important to track the cart session throughout the users shopping experience.

- [Guest Customer](#for-a-guest-customer)
- [Registered Customer](#for-a-registered-customer)

### For a Guest Customer

For guest customers, in order to identify the cart session for all Cart API requests you make, you need to store the **cart key** somewhere in your application after it is given to you. This is essentially your token so remembering it is important.

Here are a few storage suggestions for the cart key:

- using a cookie
- or using local storage
- or using a wrapper like localForage or PouchDB
- or using local database like SQLite or Hive
- or your choice based on the app you developed

Once you have captured the cart key in your application, you will then need to use the captured cart key for all future Cart API requests. Not doing so will lead to several cart sessions being created with no way of getting the correct cart session back the next time you add a product or make a change to the cart.

> Example shows getting the cart session with a cart key using [CoCart JS library](https://github.com/co-cart/cocart-js-lib).

```js
CoCart.get("cart?cart_key=43de87a471f517c779841b08be852b26")
.then((response) => {
// Successful request
console.log("Response Status:", response.status);
console.log("Response Headers:", response.headers);
console.log("Response Data:", response.data);
})
.catch((error) => {
// Invalid request, for 4xx and 5xx statuses
console.log("Response Status:", error.response.status);
console.log("Response Headers:", error.response.headers);
console.log("Response Data:", error.response.data);
})
.finally(() => {
// Always executed.
});
```

#### Finding the Cart Key

When the cart session is created you will see the cart key returned in the cart response or via the returned headers. In the cart response you will find it under the field `cart_key`.

```json
{
"cart_hash": "cd541ec1948b600728b49c198b1f4d84",
"cart_key": "43de87a471f517c779841b08be852b26",
"currency": {
"currency_code": "USD",
"currency_symbol": "$",
"currency_minor_unit": 2,
"currency_decimal_separator": ".",
"currency_thousand_separator": ",",
"currency_prefix": "$",
"currency_suffix": ""
},
...
}
```

However, if you filtered the cart response to return only the fields you require, the `cart_key` field may not be there.

Which is why as a backup, you can still find the cart key in the returned headers. Just look for `CoCart-API-Cart-Key`.

> Note: The cart key only returns for guest sessions to help identify the cart session. Logged in users or authenticated users don't require the cart key when using the Cart API.

#### Updating the cart as a guest

When you want to update the cart for a guest session, you need to provide the cart key and query it to the end of the endpoint. This tells CoCart to load that cart session before proceeding with the action requested.

> Here we are showing another product being added to the same cart using [CoCart JS library](https://github.com/co-cart/cocart-js-lib).

```js
CoCart.post("cart/add-item?cart_key=43de87a471f517c779841b08be852b26", {
id: "71",
quantity: "2"
})
.then((response) => {
// Successful request
console.log("Response Status:", response.status);
console.log("Response Headers:", response.headers);
console.log("Response Data:", response.data);
})
.catch((error) => {
// Invalid request, for 4xx and 5xx statuses
console.log("Response Status:", error.response.status);
console.log("Response Headers:", error.response.headers);
console.log("Response Data:", error.response.data);
})
.finally(() => {
// Always executed.
});
```

### For a Registered Customer

For a registered customer, using a cart key is not needed. This is because we identify the cart session using the registered users ID instead and has already fetched the cart session for you.

This allows you to update the cart without having to worry about the cart key.

However, if your user started out as a guest but does have an account on your site then you can use the cart key to transfer over the session as you authenticate them.

#### How do I authenticate for a registered customer?

Assuming you are using the latest [CoCart JS library](https://github.com/co-cart/cocart-js-lib) you would need to pass the customers login credentials before making any Cart API request in the library options.

```js
// import CoCartAPI from "@cocart/cocart-rest-api"; // Supports ESM
const CoCartAPI = require("@cocart/cocart-rest-api").default;

const CoCart = new CoCartAPI({
url: "https://example-store.com",
username: 'sebtest123', // Username, email address or billing phone number
password: 'happycoding24'
});
```

If you are using the [JWT authentication](#) plugin then you need to pass the token in the library options as so.

```js
// import CoCartAPI from "@cocart/cocart-rest-api"; // Supports ESM
const CoCartAPI = require("@cocart/cocart-rest-api").default;

const CoCart = new CoCartAPI({
url: "https://example-store.com",
token: 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJodHRwOlwvXC9jb2NhcnQtcGx1Z2luLXRydW5rLmxvY2FsIiwiaWF0IjoxNjc3ODg0ODQyLCJleHAiOjE2NzgwNTc2NDIsImRhdGEiOnsidXNlciI6eyJpZCI6MSwidXNlcm5hbWUiOiJzZWJhc3RpZW4iLCJwYXNzd29yZCI6ImRhcmtQYW5kYTI2TWF5In0sInNlY3JldF9rZXkiOiJ0aGlzaXN0aGV3YXkifX0.tGW-wGKIv_BnLz6rfQPMx3pvBKnxB9UwyT2IYK2BoKg'
});
```

Other methods require passing **Authorization Headers**.

- **Basic Authentication**

```php
'Authorization: Basic ' . base64_encode($username . ':' . $password)`
```

If you have the _base64_ string of the login credentials already you can put it as is instead of generating the _base64_ encoded string. - **Requires CoCart v4 or above**.

- **JWT Authentication** - [Requires JWT Authentication](#) plugin.

```php
'Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJodHRwOlwvXC9jb2NhcnQtcGx1Z2luLXRydW5rLmxvY2FsIiwiaWF0IjoxNjc3ODg0ODQyLCJleHAiOjE2NzgwNTc2NDIsImRhdGEiOnsidXNlciI6eyJpZCI6MSwidXNlcm5hbWUiOiJzZWJhc3RpZW4iLCJwYXNzd29yZCI6ImRhcmtQYW5kYTI2TWF5In0sInNlY3JldF9rZXkiOiJ0aGlzaXN0aGV3YXkifX0.tGW-wGKIv_BnLz6rfQPMx3pvBKnxB9UwyT2IYK2BoKg'
```

**Queried on the endpoint**

> ⚠️ We don't recommend this method but for basic authentication it's supported.

```sh
curl "https://example-store.com/wp-json/cocart/v2/cart?username=$username&password=$password"
```

<!-- FEEDBACK -->

---

🐞 Found a mistake, or have a suggestion? [Leave feedback about this document here.](https://github.com/co-cart/co-cart/issues/new?assignees=&labels=type%3A+documentation&template=doc_feedback.md&title=Feedback+on+./docs/how-to-create-and-access-cart.md)

<!-- /FEEDBACK -->
6 changes: 6 additions & 0 deletions docs/incompatible-plugins-with-cocart.md
Original file line number Diff line number Diff line change
Expand Up @@ -8,4 +8,10 @@ Next to each listed plugin is the reason for incompatibility.
| :---------: | :----------: | -------------------------- |
| Smart Coupons For WooCommerce Coupons | [Link](https://wordpress.org/plugins/wt-smart-coupons-for-woocommerce/) | Prevents coupons from being applied to the cart. |

<!-- FEEDBACK -->

---

🐞 Found a mistake, or have a suggestion? [Leave feedback about this document here.](https://github.com/co-cart/co-cart/issues/new?assignees=&labels=type%3A+documentation&template=doc_feedback.md&title=Feedback+on+./docs/incompatible-plugins-with-cocart.md)

<!-- /FEEDBACK -->
82 changes: 82 additions & 0 deletions docs/intro-to-cocart.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,82 @@
# Intro to CoCart <!-- omit in toc -->

This guide will be most useful for developers with little to no WordPress experience. This is not intended to be the most comprehensive guide to WordPress in the world, but is intended to provide some insight into how WordPress works and resources to learn more about WordPress.

## Table of Contents <!-- omit in toc -->

- [Introduction](#introduction)
- [What is REST API?](#what-is-rest-api)
- [What is Jamstack?](#what-is-jamstack)
- [What Is WordPress?](#what-is-wordpress)
- [Using WordPress as a Headless CMS](#using-wordpress-as-a-headless-cms)
- [Setting up WordPress on your computer](#setting-up-wordpress-on-your-computer)
- [Setting up WooCommerce](#setting-up-woocommerce)
- [How do Plugins Work with decoupled WordPress?](#how-do-plugins-work-with-decoupled-wordpress)

## Introduction

This guide will be most useful for developers that are new to working with REST API.

This guide isn't a comprehensive deep dive into REST API but should help you get a basic understanding of it and provide you with resources to dive deeper.

## What is REST API?

An API is an Application Programming Interface. REST, standing for “Representational State Transfer,” is a set of concepts for modelling and accessing your application’s data as interrelated objects and collections.

Your application can send and receive JSON data to these endpoints to query, modify and create content on your site. JSON is an open standard data format that is lightweight and human-readable, and looks like Objects do in JavaScript.

When you request content from or send content to the API, the response will also be returned in JSON. Because JSON is widely supported in many programming languages, developers can build WordPress applications in client-side JavaScript, as mobile apps, or as desktop or command line tools.

## What is Jamstack?

Jamstack is an architecture designed to make the web faster, more secure, and easier to scale. It builds on many of the tools and workflows which developers love, and which bring maximum productivity, improving flexibility, scalability, and maintainability.

Jamstack removes the need for logic to dictate the web experience. It enables a composable architecture for the web where custom logic and 3rd party services are consumed through APIs.

## What Is WordPress?

WordPress is currently the most popular CMS on the internet today, used by everyone from small DIY bloggers to small/mid-sized agencies and complex enterprises. Using the built-in REST API, WordPress can power amazing headless experiences while providing content editors and managers an extensible and familiar publishing interface.

It offers structured access to site content and settings over HTTP. Using existing patterns, developers can extend the REST API to support custom content types or create unique routes that support any use case that can be created with PHP and its associated libraries and tools.

## Using WordPress as a Headless CMS

The WordPress CMS already gives site developers a method for server-side rendering (SSR) using themes based on PHP templates, but the platform also offers a robust and extensible REST API that allows developers to create headless sites and apps using any manner of frontend technologies.

### Setting up WordPress on your computer

One of the first things you might want to do is to set up a WordPress site on your personal computer.

Hands-down recommend using a tool called [LocalWP](https://localwp.com/). It’s a desktop application that allows you to create new WordPress sites on your computer with the click of a few buttons. It takes care of configuring PHP, MySQL and basic configuration of WordPress to connect to the database. It provides one-click support for enabling XDebug, allows access to your WordPress site using WP-CLI, and more. And, it’s free.

There are some alternatives for quickly spinning up a local environment:

- [DevKinsta](https://kinsta.com/blog/install-wordpress-locally/#how-to-install-wordpress-locally-with-devkinsta)
- [Lando](https://docs.lando.dev/config/wordpress.html)
- [MAMP](https://codex.wordpress.org/Installing_WordPress_Locally_on_Your_Mac_With_MAMP)
- [XAMP](https://themeisle.com/blog/install-xampp-and-wordpress-locally/)
- [Set it all up on your own](https://wpbeaches.com/setting-up-valet-on-macos-for-local-wordpress-development/)

When setting up your WordPress environment, please check that you have the [requirements](https://wordpress.org/plugins/cart-rest-api-for-woocommerce/#installation) for CoCart.

### Setting up WooCommerce

Once you have your WordPress environment setup. The next step is to install WooCommerce and setup your store. Add products, configure shipping, taxes, payment gateway etc.

A more detailed guide for setting up WooCommerce can be found at [WooCommerce.com documentation](https://woocommerce.com/documentation/plugins/woocommerce/getting-started/).

## How do Plugins Work with decoupled WordPress?

Many WordPress plugins were created with the assumption that WordPress is the CMS as well as the presentation layer, but that’s not always the case today. With the rise of decoupled WordPress, it’s common for WordPress to be used as a CMS, but not be used for its theme layer.

WordPress REST API allows for WordPress plugins to extend so their custom data can be used in decoupled applications. This is the same with extending CoCart if your a plugin author looking to add CoCart support to your plugin, or you're using a WooCommerce extension that doesn't have built-in support for CoCart already and you want to add support, checkout the following resources:

-

<!-- FEEDBACK -->

---

🐞 Found a mistake, or have a suggestion? [Leave feedback about this document here.](https://github.com/co-cart/co-cart/issues/new?assignees=&labels=type%3A+documentation&template=doc_feedback.md&title=Feedback+on+./docs/intro-to-cocart.md)

<!-- /FEEDBACK -->
6 changes: 6 additions & 0 deletions docs/load-cart-from-session.md
Original file line number Diff line number Diff line change
Expand Up @@ -53,4 +53,10 @@ Example: https://example.com/cart/?cocart-load-cart=bbfa8e97ac9cff4c861d62a109e8

If you are merging two cart sessions together and they both contain the same item, that item will not change. It will not increase or decrease the quantity either.

<!-- FEEDBACK -->

---

🐞 Found a mistake, or have a suggestion? [Leave feedback about this document here.](https://github.com/co-cart/co-cart/issues/new?assignees=&labels=type%3A+documentation&template=doc_feedback.md&title=Feedback+on+./docs/load-cart-from-session.md)

<!-- /FEEDBACK -->
6 changes: 6 additions & 0 deletions docs/rate-limit-guide.md
Original file line number Diff line number Diff line change
Expand Up @@ -111,4 +111,10 @@ add_action(
2. Try to apply a coupon or access `/wp-json/cocart/v1/coupon` beyond current limits (currently 25 requests under 10 seconds)
3. Ensure you get presented with an error "Too many requests. Please wait xx seconds before trying again."

<!-- FEEDBACK -->

---

🐞 Found a mistake, or have a suggestion? [Leave feedback about this document here.](https://github.com/co-cart/co-cart/issues/new?assignees=&labels=type%3A+documentation&template=doc_feedback.md&title=Feedback+on+./docs/rate-limit-guide.md)

<!-- /FEEDBACK -->
Loading