w3bdesign / nuxtjs-woocommerce

⚡️ Nuxt 3 and Vue 3 headless eCommerce site with WooCommerce backend and Algolia search
https://nuxt.dfweb.no
GNU Affero General Public License v3.0
204 stars 45 forks source link

Consider implementing order page #1052

Open w3bdesign opened 1 year ago

w3bdesign commented 1 year ago

Certainly! Here's an updated guide that includes the JWT Authentication plugin:

  1. Install and activate the WPGraphQL plugin and the WPGraphQL-JWT-Authentication plugin.

  2. Define a secret key for JWT Authentication. This key will be used to encode and decode JSON Web Tokens. You can define the key in your wp-config.php file like this:

    define( 'GRAPHQL_JWT_AUTH_SECRET_KEY', 'your-secret-key' );

    Replace your-secret-key with a unique, randomly generated string of characters. You can use a tool like the WordPress Salt generator (https://api.wordpress.org/secret-key/1.1/salt/) to generate a random string.

    Alternatively, you can use the graphql_jwt_auth_secret_key filter to define the key in a custom function:

    add_filter( 'graphql_jwt_auth_secret_key', function() {
       return 'your-secret-key';
    } );
  3. Ensure that your server is passing the HTTP_AUTHORIZATION header to WordPress. In some cases, this header may not be passed due to server configurations. You can enable the header in your server configuration file, such as .htaccess file for Apache, or by following instructions specific to your server.

  4. Use the login mutation to authenticate a user and retrieve a JWT token. The login mutation takes a LoginUserInput input type and returns an authToken and user object with id and name fields. You can store the authToken in local storage (or similar) and use it in subsequent requests as an HTTP Authorization header to authenticate the user.

    Here's an example query for the login mutation:

    mutation LoginUser {
       login(
           input: {
               clientMutationId: "uniqueId",
               username: "your_login",
               password: "your password"
           }
       ) {
           authToken
           user {
               id
               name
           }
       }
    }

    Replace your_login and your_password with the user's login credentials. You can use a tool like GraphiQL or Insomnia to send the query to your WordPress site and retrieve the token.

  5. Use the authToken retrieved from the login mutation as an HTTP Authorization header in subsequent requests to authenticate the user. The header should be in the format Authorization: Bearer {authToken}.

    The method for setting the Authorization header varies depending on your HTTP client library. For example, you can set the header in Apollo Client like this:

    const client = new ApolloClient({
       uri: 'http://your-wordpress-site/graphql',
       headers: {
           Authorization: `Bearer ${authToken}`,
       },
    });
  6. Use the registerUser mutation to create a new user with a JWT token. The registerUser mutation takes a RegisterUserInput input type and returns a user object with jwtAuthToken and jwtRefreshToken fields.

    Here's an example query for the registerUser mutation:

    mutation RegisterUser {
       registerUser(
           input: {
               clientMutationId: "uniqueId",
               username: "your_username",
               password: "your_password",
               email: "your_email"
           }
       ) {
           user {
               jwtAuthToken
               jwtRefreshToken
           }
       }
    }

    Replace your_username, your_password, and your_email with the desired values for the new user.

  7. Use the refreshJwtAuthToken mutation to refresh an expired JWT token. The `refreshJwtAuthToken

w3bdesign commented 1 year ago

Sure! Here's an updated guide that uses the composition API with <script setup> syntax:

  1. Install the necessary libraries: You will need to install the following libraries:

You can install these libraries using npm or yarn.

  1. Set up Apollo Client: Next, you will need to set up Apollo Client. You can do this by creating a new file in the plugins directory of your Nuxt project called apollo.js. In this file, you can create a new instance of Apollo Client and set up the necessary links and cache. Here's an example:
import { ApolloClient, InMemoryCache, HttpLink } from '@apollo/client/core';

export default function (context) {
  const httpLink = new HttpLink({
    uri: 'https://yourwordpresssite.com/graphql',
  });

  const cache = new InMemoryCache();

  const apolloClient = new ApolloClient({
    link: httpLink,
    cache,
  });

  context.app.apolloProvider = apolloClient;
}

Replace https://yourwordpresssite.com/graphql with the URL of your WordPress site's GraphQL endpoint.

  1. Create a login mutation: As mentioned in the documentation you provided, you will need to create a login mutation to authenticate the user and get the necessary tokens. You can create a new file in the graphql directory of your Nuxt project called login.gql and add the following code:
mutation Login($username: String!, $password: String!) {
  login(
    input: {
      clientMutationId: "someId"
      username: $username
      password: $password
    }
  ) {
    customer {
      jwtAuthToken # JWT User Authentication token
      sessionToken # WooCommerce Session token
    }
  }
}

This mutation takes in a username and password variable and returns the JWT authentication token and WooCommerce session token.

  1. Create a page to display orders: Next, you can create a new page in your Nuxt project to display the customer's orders. You can create a new file in the pages directory of your Nuxt project called orders.vue and add the following code:
<template>
  <div>
    <h1>Orders</h1>
    <ul>
      <li v-for="order in orders" :key="order.id">
        {{ order.number }} - {{ order.date_created }}
      </li>
    </ul>
  </div>
</template>

<script setup>
import { useQuery } from '@vue/apollo-composable';
import { ref } from 'vue';

import ORDERS_QUERY from '~/graphql/orders.gql';

const orders = ref([]);

const { result } = useQuery(ORDERS_QUERY);

orders.value = result.value?.data?.customer?.orders?.edges?.map((edge) => edge?.node);

</script>

This page uses the useQuery composable function from @vue/apollo-composable to fetch the customer's orders using the orders.gql query. The orders variable is a reactive reference that stores the fetched orders.

  1. Create a query to fetch orders: You will need to create a new query to fetch the customer's orders. You can create a new file in the graphql directory of your Nuxt project called orders.gql and add the following code:
query Orders {
  customer {
    orders {
      edges {
        node {
          id
          number
          date_created
        }
      }
    }
  }
}

This query fetches the id, number, and date_created fields for each of the customer's orders.

That's it! You can now navigate to the orders page in your Nuxt app to see the customer's orders.