Home WeChat Applet Mini Program Development Solution to authorized login of mini program (with code)

Solution to authorized login of mini program (with code)

Dec 14, 2018 am 10:59 AM
javascript Applets

The content of this article is about the solution to the authorized login of the mini program (with code). It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.

I have recently been working on a small program project, which is still a shopping mall, and I have started to study the login authorization pit of WeChat. It is the first time I came into contact with a small program, and the authorization login is also a mess. I will slowly improve it later

Scenario

WeChat users can enter the mini program through search
They can also enter the mini program through sharing with others
After entering the mini program, user authorization is required to obtain user information for registration

Code implementation

Initialization page home page Users entering the mini program for the first time must authorize background registration and log in
app.json

{
"pages": [
    "pages/home/index", 
    "pages/login/index",
     ...
   ]
}
Copy after login

login. js logic enters the page to determine whether it has been authorized, and determines whether the user has been authorized. If authorized, the login will be displayed, if there is no authorization, the authorization will be displayed. Whether the user is registering or logging in, he or she uses the same interface provided by the background. The returned token is stored locally
login.js

const App = getApp()
import { loginModel } from '../../models/login.js'
import { MineModel } from '../../models/mine.js'
import { encodeUnicode } from '../../utils/index.js'
const ModelLogin = new loginModel()
const Modelmine = new MineModel()
Page({
  data: {
    logged: !1,
    isauth: false,
    locked: false
  },
  onLoad: function(options) {
    // 返回到之前要刷新
    var pages = getCurrentPages() // 获取页面栈
    var prevPage = pages[pages.length - 2] // 前一个页面
    prevPage.setData({
      isBack: true
    })
  },
  onShow: function() {
    // 如果已经授权则显示登录,直接登录不调用授权
    App.WxService.getSetting().then(res => {
      if (res.authSetting['scope.userInfo']) {
        this.setData({
          isauth: true
        })
      }
    })
    //token 不能在page外面定义,变量写在 page 外面有缓存
    const token = App.WxService.getStorageSync('utoken')
    // 如果有token显示已经授权
    this.setData({
      logged: !!token
    })
    token && setTimeout(this.goBack, 1500)
  },
  login() {
    this.wechatSignUp()
  },
  goBack() {
    // 返回登录之前的页面
    wx.navigateBack({
      delta: 1
    })
  },
  // 登陆注册
  wechatSignUp(cd) {
    // 上锁如果正在请求接口那么就返回
    if (this.data.locked) {
      return
    }
    this.data.locked = true
    //注册或者登陆获取token
    let code = ''
    App.WxService
      .login()
      .then(data => {
        code = data.code
        wx.setStorageSync('logincode', data.code)
        return App.WxService.getUserInfo()
      })
      .then(data => {
        // 请求后台登录注册接口
        return ModelLogin.wechatSignUp({
          encrypteData: data.encryptedData,
          iv: data.iv,
          rawData: encodeUnicode(data.rawData), // 编码
          signature: data.signature,
          code: code
        })
      })
      .then(data => {
        this.data.locked = false
        if (data.data.token == '') {
          wx.showToast({
            title: '登录失败',
            icon: 'none'
          })
          return
        }
        App.WxService.setStorageSync('utoken', data.data.token)
        // 访问后台接口获取用户信息
        ModelLogin.getVipInfo({ token: data.data.token }).then(res => {
          App.globalData.userInfo = res.data.userInfo
          // 返回上一页
          this.goBack()
        })
      })
      .catch(err => {
        this.data.locked = false
        console.log(err)
      })
  }
})
Copy after login

App.WxService here is equivalent to wx because wx is a callback method, and promise is used here.
First determine whether there is authorization. If there is no authorization, click Authorize. If there is authorization, click Login. The calling methods are all wechatSignUp. Get the code of wx.login and the data of wx.getUserInfo to the background, and then the background returns the token, and then Then access the backend to obtain user information
The logic of login is probably these
login.wxml

<view class="login-container">
  <view class="login" wx:if="{{ !logged }}">
    <view class="app-info">
      <image class="app-logo" src="./s-toplogo@2x.png" />
      <text class="app-name">商城</text>
    </view>
    <view class="alert">
      <view class="alert-title" wx:if="{{!isauth}}">请同意授权</view>
      <view class="alert-title" wx:if="{{isauth}}">请登录</view>
      <view class="alert-desc">
        <view class="alert-text">为了让头号买手可以更好的为您服务</view>
      </view>
    </view>
    <button type=&#39;primary&#39; wx:if="{{!isauth}}" class="sui-f16" open-type="getUserInfo" bind:getuserinfo="wechatSignUp">确认授权</button>
    <button type="primary" wx:if="{{isauth}}" class="weui-btn" bindtap="login">确认登录</button>
  </view>
  <view class="logged" wx:else>
    <image class="logged-icon" src="./s-toplogo@2x.png" />
    <view class="logged-text">近期你已经授权登陆过商城</view>
    <view class="logged-text">自动登录中</view>
  </view>
</view>
Copy after login

When accessing the backend interface, pass the token in the header. If the backend does not get the token, it will return 401. The front end Unified interception and jump to the login page

End

About app.js was originally intended to be intercepted in the app, but asynchronous requests are always obtained after entering the page The data returned by the background is because the user may enter the mini program from other pages such as the product details page and return to the entry page after authorization. If intercepted in app.js, the page cannot be returned, so the user can directly judge it in the js of the page. Well, there aren’t many pages to share, so I didn’t write anything in app.js. This is my first contact, I hope I can optimize it in the future and then post it to record it

The above is the detailed content of Solution to authorized login of mini program (with code). For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Roblox: Bubble Gum Simulator Infinity - How To Get And Use Royal Keys
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Nordhold: Fusion System, Explained
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Mandragora: Whispers Of The Witch Tree - How To Unlock The Grappling Hook
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Clair Obscur: Expedition 33 - How To Get Perfect Chroma Catalysts
2 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1677
14
PHP Tutorial
1278
29
C# Tutorial
1257
24
WebSocket and JavaScript: key technologies for implementing real-time monitoring systems WebSocket and JavaScript: key technologies for implementing real-time monitoring systems Dec 17, 2023 pm 05:30 PM

WebSocket and JavaScript: Key technologies for realizing real-time monitoring systems Introduction: With the rapid development of Internet technology, real-time monitoring systems have been widely used in various fields. One of the key technologies to achieve real-time monitoring is the combination of WebSocket and JavaScript. This article will introduce the application of WebSocket and JavaScript in real-time monitoring systems, give code examples, and explain their implementation principles in detail. 1. WebSocket technology

How to implement an online speech recognition system using WebSocket and JavaScript How to implement an online speech recognition system using WebSocket and JavaScript Dec 17, 2023 pm 02:54 PM

How to use WebSocket and JavaScript to implement an online speech recognition system Introduction: With the continuous development of technology, speech recognition technology has become an important part of the field of artificial intelligence. The online speech recognition system based on WebSocket and JavaScript has the characteristics of low latency, real-time and cross-platform, and has become a widely used solution. This article will introduce how to use WebSocket and JavaScript to implement an online speech recognition system.

How to use JavaScript and WebSocket to implement a real-time online ordering system How to use JavaScript and WebSocket to implement a real-time online ordering system Dec 17, 2023 pm 12:09 PM

Introduction to how to use JavaScript and WebSocket to implement a real-time online ordering system: With the popularity of the Internet and the advancement of technology, more and more restaurants have begun to provide online ordering services. In order to implement a real-time online ordering system, we can use JavaScript and WebSocket technology. WebSocket is a full-duplex communication protocol based on the TCP protocol, which can realize real-time two-way communication between the client and the server. In the real-time online ordering system, when the user selects dishes and places an order

How to implement an online reservation system using WebSocket and JavaScript How to implement an online reservation system using WebSocket and JavaScript Dec 17, 2023 am 09:39 AM

How to use WebSocket and JavaScript to implement an online reservation system. In today's digital era, more and more businesses and services need to provide online reservation functions. It is crucial to implement an efficient and real-time online reservation system. This article will introduce how to use WebSocket and JavaScript to implement an online reservation system, and provide specific code examples. 1. What is WebSocket? WebSocket is a full-duplex method on a single TCP connection.

JavaScript and WebSocket: Building an efficient real-time weather forecasting system JavaScript and WebSocket: Building an efficient real-time weather forecasting system Dec 17, 2023 pm 05:13 PM

JavaScript and WebSocket: Building an efficient real-time weather forecast system Introduction: Today, the accuracy of weather forecasts is of great significance to daily life and decision-making. As technology develops, we can provide more accurate and reliable weather forecasts by obtaining weather data in real time. In this article, we will learn how to use JavaScript and WebSocket technology to build an efficient real-time weather forecast system. This article will demonstrate the implementation process through specific code examples. We

Simple JavaScript Tutorial: How to Get HTTP Status Code Simple JavaScript Tutorial: How to Get HTTP Status Code Jan 05, 2024 pm 06:08 PM

JavaScript tutorial: How to get HTTP status code, specific code examples are required. Preface: In web development, data interaction with the server is often involved. When communicating with the server, we often need to obtain the returned HTTP status code to determine whether the operation is successful, and perform corresponding processing based on different status codes. This article will teach you how to use JavaScript to obtain HTTP status codes and provide some practical code examples. Using XMLHttpRequest

How to use insertBefore in javascript How to use insertBefore in javascript Nov 24, 2023 am 11:56 AM

Usage: In JavaScript, the insertBefore() method is used to insert a new node in the DOM tree. This method requires two parameters: the new node to be inserted and the reference node (that is, the node where the new node will be inserted).

How to get HTTP status code in JavaScript the easy way How to get HTTP status code in JavaScript the easy way Jan 05, 2024 pm 01:37 PM

Introduction to the method of obtaining HTTP status code in JavaScript: In front-end development, we often need to deal with the interaction with the back-end interface, and HTTP status code is a very important part of it. Understanding and obtaining HTTP status codes helps us better handle the data returned by the interface. This article will introduce how to use JavaScript to obtain HTTP status codes and provide specific code examples. 1. What is HTTP status code? HTTP status code means that when the browser initiates a request to the server, the service

See all articles