当前位置:网站首页>Use abp Zero builds a third-party login module (4): wechat applet development

Use abp Zero builds a third-party login module (4): wechat applet development

2022-07-24 12:22:00 Lin Xiao LX

Briefly review the process of wechat applet :

  1. The user enters the authentication page of the applet by scanning the code , Update status to ACCESSED Scanned code
  2. The user clicks confirm Authorization , Wechat through wx.login() Interface to obtain the necessary information of the third party login :Code Login credentials .

Wechat applet mainly provides interactive functions for user authorization , The user scans the code , Provide an interaction UI, as follows :

stay 《 Use Abp.Zero Build a third-party login module ( Two ): Server development 》 The interface that the server has built is introduced in , This time we will call Access and Authenticate, Call respectively to complete the update of scanned code and authorized status .

Project structures,

  use first vue-cli Create a web project , Name it mp-weixin

vue create -p dcloudio/uni-preset-vue mp-weixin

  stay Pages Create login/index.vue page , As the login authorization page

The directory structure is as follows :

pages.json:

{
	"pages": [ //pages The first item in the array represents the application startup page , Reference resources :https://uniapp.dcloud.io/collocation/pages
		{
			"path": "pages/index/index",
			"style": {
				"navigationBarTitleText": "uni-app"
			}
		},
		{
			"path": "pages/login/index",
			"style": {
				"navigationBarTitleText": " Authorization page "
			}
		}
	],
	"globalStyle": {
		"navigationBarTextStyle": "black",
		"navigationBarTitleText": "uni-app",
		"navigationBarBackgroundColor": "#F8F8F8",
		"backgroundColor": "#F8F8F8"
	}
}

 login New under the directory ajaxRequire.ts, establish request object , This object will utilize uni-axios-ts Library send ajax request

import axios from 'uni-axios-ts'
// Send network request 
export const request = async (url: string, methods, data: any, onProgress?: (e) => void, cancelToken?) => {
    let token = null
    let timeout = 3000;
    if (cancelToken) {
        token = cancelToken.token
        timeout = 0;
    }
    const service = axios.create()


    service.interceptors.request.use(
        (config) => {
            config.header['Content-Type'] = "application/json"
            return config
        },
        (error) => {
            Promise.reject(error)
        }
    )


    const re = await service.request({
        headers: { 'Content-Type': 'multipart/form-data' },
        url: url,
        method: methods,
        data: data,
        cancelToken: token,
        timeout: timeout,
        onUploadProgress: function (progressEvent) { // The event that gets the upload progress 
            if (progressEvent.lengthComputable) {
                if (onProgress) {
                    onProgress(progressEvent);
                }
            }
        },
    })
    return re as any;
}

/// Get cancellation token 
export const getCancelToken = () => {
    const source = axios.CancelToken.source();
    return source;
}

index.vue Created in loginExternalForms As a parameter transfer object

export default {
  data() {
    return {
      loginExternalForms: {
        WeChat: {
          token: "",
          providerAccessCode: "",
        },
      }
    };
  }
}

onLoad Function ,option Stored in the scanning applet code scene Parameters , take scene The parameter is assigned to token Variable

 onLoad(option) {
    this.loginExternalForms.WeChat.token = option.scene;
    this.start();
  },

start In, we call Access Interface , Change status to ACCESSED( Scanned code ) , If the return is successful , Then prompt the user to click confirm authorization , If the returned result is abnormal "WechatMiniProgramLoginInvalidToken" when , Indicates that the applet code has expired at this time , You need to update the applet code on the webpage .

    async start() {
      var currentForms = this.loginExternalForms["WeChat"];
      this.loading = true;
      await request(`${this.prefix}/MiniProgram/Access`, "post", currentForms)
        .then((re) => {
          this.successMessage(" You have scanned the QR code , Please click confirm login to complete ");
        })
        .catch((c) => {
          var err = c.response?.data?.error?.message;
          if (err != null) {
            if (err == "WechatMiniProgramLoginInvalidToken") {
              this.isInvalid = true;
            } else {
              this.errorMessage(c.err);
            }
          }
        })
        .finally(() => {
          setTimeout(() => {
            this.loading = false;
          }, 1.5 * 1000);
        });
    },

Prefix Is your service address prefix

prefix: "https://localhost:44311/api/services/app"

stay Html in , We create authorized login and Cancel buttons , Only when the isInvalid by true You can click authorize

      <button
        @click="handleWxLogin"
        :disabled="isInvalid || loading"
        class="sub-btn"
      >
         Authorized login 
      </button>

      <button @click="cancelWxLogin" :disabled="loading" class="sub-btn">
         Cancel 
      </button>

establish  handleExternalLogin It is used to process the logic after the user clicks the authorization to log in , call Authenticate Interface , Update status to AUTHORIZED( Authorized ) You need to call before that uni.login Get applet login credentials code.

of uni.login function , Please refer to the official documentation uni.login(OBJECT) | uni-app Official website (dcloud.io)

uniapp Support a variety of applets , In order to retain certain expansion capability ,handleExternalLogin We keep parameters in the function authProvider, Wechat applet login has been implemented handleWxLogin Pass parameters when a function is called "WeChat",

    async handleExternalLogin(authProvider) {
      var currentForms = this.loginExternalForms[authProvider];
      this.loading = true;
      await request(
        `${this.prefix}/MiniProgram/Authenticate`,
        "post",
        currentForms
      )
        .then((re) => {
          uni.redirectTo({
            url: "/pages/index/index",
          });
        })
        .catch((c) => {
          var err = c.response?.data?.error?.message;
          if (err != null) {
            if (err == "WechatMiniProgramLoginInvalidToken") {
              this.isInvalid = true;
            } else {
              this.errorMessage(c.err);
            }
          }
          setTimeout(() => {
            this.loading = false;
          }, 1.5 * 1000);
        });
    },


   async handleWxLogin() {
      const that = this;
      uni.login({
        provider: "weixin",
        success: (loginRes) => {
          that.loginExternalForms.WeChat.providerAccessCode = loginRes.code;
          that.handleExternalLogin("WeChat");
        },
      });
    },

Create the unregister function

    cancelWxLogin() {
      uni.redirectTo({
        url: "/pages/index/index",
      });
    },

Execute the success notification function

    successMessage(value = " Successful implementation ") {
      uni.showToast({
        title: value,
        icon: "success",
        duration: 1.5 * 1000,
      });
    },

Next, simply write an interface ,

The interface will clearly reflect isInvalid And loading Corresponding to UI Interaction :

normal

Applet code is out of date  

Overall test

Simulator test

When I open the page , Save image as

 

  In wechat applet debugging tool ,“ Through two-dimensional code compilation ”

  Wait for the mobile interface to display the authorization page and click “ Authorized login ”:

 

 GetCurrentUser The interface returns the correct data , And displayed on web On the page

 

So far, the development of the applet side has been completed

Project address

jevonsflash/abp-mp-auth (github.com)

Conclusion

Applet login has certain scalability , Although wechat applet login is introduced throughout , But login authentication is an abstract function of applet ,uniapp Integrated with various platforms ( WeChat 、 Alipay 、 Baidu 、 Bytedance applet ) Login interface , adopt uni.login You can get the code

原网站

版权声明
本文为[Lin Xiao LX]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/203/202207220656345441.html