Nuxt wechat development – Authorized login to project deployment

I have been using Vue to develop SPA (single-page Application – single-page Application) on wechat. Authorization is done by the back end, and the front end only needs to pull the interface to fill data.

Due to the asynchronous acquisition of data, there may be a situation that the page loading is completed but the data is not completely filled. In order to improve user experience, the project later adopted Nuxt framework and server rendering, and everything was relatively smooth, except that it stepped on the pit of wechat authorization.

Of course, if I did not step on, there would be no this article, in line with the purpose of learning to share with you, if there is wrong place we also hope to criticize and correct ~

Let’s get down to business

Environment set up

Nuxt-related scaffolding is already integrated into vuE-CLI and provides starter, Express, KOA, and Adonuxt templates. We chose the Express template

Initialize our project with the following command

// initialize $vue init nuxt-community/express-template vue-ssrCopy the code

Then install the dependencies

$ cd vue-ssr

$ npm install
Copy the code

Start the project

$ npm run dev
Copy the code

Go to localhost:3000, if you see the following screen, you have successfully installed





Home page

We found that the official has already made a demo for us, and we just need to modify it.

Wechat authorization Settings

In order to conduct wechat authorization, you need to have your own server and domain name (if not, you can only debug the test number, wechat provides that the official number must use the domain name). Please refer to the official document of wechat authorization here

Apply for wechat public platform test number

1. We enter the wechat public platform to apply for a test account, and it is a good choice to use the test account for development. After successful application, we enter the background, and there will be a developer tool option in the sidebar at the lower right corner





Public number test configuration

Not surprisingly, you’ll get two important data, appID and Appsercet, as follows





Test Number information

2. We need to bind the user to the test account and scan the qr code of the test number below. After success, your information will appear in the list on the right.

3. Finally, we also need to set the callback domain name, i.e





Correction of the domain name





Example Callback domain name Settings

Note: 1. This is the domain name (a string), not the URL, so do not add http:// or other protocol headers. 2. Configure the domain name for authorization callback as the full domain name. For example, the domain name for web page authorization is: www.qq.com, this domain name after configuration the following page http://www.qq.com/music.html and http://www.qq.com/login.html can be OAuth2.0 authentication. However, http://pay.qq.com, http://music.qq.com, and http://qq.com cannot perform OAuth2.0 authentication.

By now, we have basically completed the background configuration of wechat authorization, and the next step is to write the server code

Server code

According to the official authorization steps of wechat, there are mainly four steps as follows:

Wechat authorization uses OAuth2.0 authorization. There are mainly the following brief steps:

Step 1: The user agrees to authorize and gets the code

Step 2: Exchange web authorization access_token with code

Step 3: Refresh the access_token (if necessary)

Step 4: Pull user information (scope is snsapi_userinfo)

We create an oauth.js file under the SERVER API folder for wechat authorization.

To do this, we need to install a Request module so that we can handle requests, i.e

npm install request --save
Copy the code

Then, we write oauth.js file, the specific code is as follows:

Import {Router} from 'express'; import request from 'request' const router = Router(); Router. Get ('/oauth', function (req, res, next) {// Let router = 'get_access_token'; // Encoding address let return_URL = 'HTTP %3A%2F%2F** Set the callback domain name **%2Fapi%2F' + router; let scope = 'snsapi_userinfo'; / / redirected to WeChat authorization link res. Redirect (' https://open.weixin.qq.com/connect/oauth2/authorize?appid= '+ AppID + =' + '& redirect_uri return_url + '&response_type=code&scope=' + scope + '&state=STATE#wechat_redirect'); }) router.get('/get_access_token',function (req, res, next) { request.get({ url:'https://api.weixin.qq.com/sns/oauth2/access_token?appid=' + AppID + '&secret='+ AppSecret + '&code=' + code + '&grant_type=authorization_code' }, function (error, response, Parse (body) {if(response.statuscode == 200){// Step 3: pull user information (scope = snsapi_userinfo) let data = json.parse (body); let access_token = data.access_token; let openid = data.openid; request.get({ url : 'https://api.weixin.qq.com/sns/userinfo?access_token=' + access_token + '&openid=' + openid + '&lang=zh_CN', }, Function (error, response, body) {if(response.statusCode == 200){ Parse let userInfo = json.parse (body); Console. log(userinfo) res.send("\ < H1 > openID :" + userinfo.openID +" </h1>\ <h1>"+userinfo.nickname+" personal information </ H1 >\ <p>! [] (+ the userinfo. Headimgurl "+") < / p > \ < p > "+ the userinfo. City +", "+ the userinfo. Province +", "+userinfo.country+"</p>\ ") }else{ console.log(response.statusCode); } } ) }else{ console.log(response.statusCode); } } ) }) export default routerCopy the code

Well, the authorization code is done, remember to mount it in the API directory index.js

import { Router } from 'express'
import oauth from './oauth'

const router = Router()

// Add USERS Routes
router.use(oauth)

export default router
Copy the code

Well, if you browser to access http://localhost:3000/api/oauth now, not surprisingly, you will see the following interface:





Wechat authorization tips

Congratulations, you’re halfway there!

The deployment of

Our project is running on port 3000, now we need to put it on the server, through port 80 to access it, we need to use Nginx to do forwarding (for nginx installation not to be described here, recommend not to know how to look at it), we need to configure it, here, Nginx installation directory nignx.conf for simple configuration, I give a reference:





Nginx configuration

The next step is to deploy our Nuxt project, which is deployed slightly differently from VUE, and we need to run it locally in our project first

npm run build
Copy the code

Create a package.json file (without dev dependencies in the original project) as follows:

{" name ":" vue - SSR ", "version" : "1.0.0", "description" : "Nuxt. Js project", "author" : "chenwei <[email protected]>", "private": true, "scripts": { "dev": "backpack dev", "build": "nuxt build && backpack build", "start": "cross-env NODE_ENV=production node build/main.js", "precommit": "npm run lint", "lint": "eslint --ext .js,.vue --ignore-path .gitignore ." }, "dependencies": { "axios": "^ 0.16.2", "cross - env" : "^ 5.0.1", "express" : "^ 4.15.3", "nuxt" : "^ 1.0.0 -rc3", "request" : "^2.83.0", "source-map-support": "^0.4.15"}}Copy the code

Put the packaged.nuxt folder, bulid folder and package.json files in the project directory of the server (I used vUE – SSR here), go to that folder, run NPM install to install dependencies, and run NPM start. The project can run, then we access the API/OAuth interface, it will pop up wechat authorization, as shown in the figure





WeChat authorization

After confirming login, authorization is successful and user information can be pulled, as shown in the following figure





Authorization success

At the same time, we can also see the following personal information printed in the log on the server side:





Server-side printing

At this point, we complete the authorization of wechat, the next as long as the user information into the database

Well, one more thing, if the project needs to be run in the server background, I recommend using PM2 for management. There are many online tutorials on how to use PM2, and it is very convenient to use. Here I am only for Nuxt project.

Run the pm2 start NPM — start command, the project is mounted in the background, and the following interface is displayed





pm2

Of course, you can also use the pm2 list to view all node applications currently running. This id is the id of the current application. If you want to exit the application, use pm2 delete _id ~