


How to implement login and authorization for mini programs
Login:
If we want to implement the login of the mini program, we might as well try to complete the login when opening the mini program. In other words, we can add the mini program login code in the onlaunch method in app.js.
is as follows:
//微信的登录方法wx.login({ success: res => { //登录成功后会返回一个微信端提供的 code ,用来自定义登录使用 console.log("code",res.code); //向自己的后台发送请求 wx.request({ url: this.globalData.URL+'login/', data:{ code:res.code }, header:{ "content-type": "application/json" }, method:"POST", success:function(e){ console.log(e) //请求成功后会返回一个自己后端生成的 token 用来做其他操作的校验,把token保存在本地 wx.setStorageSync("token", e.data.data.token) } }) // 发送 res.code 到后台换取 openId, sessionKey, unionId } })
Backend code:
from rest_framework.views import APIViewfrom rest_framework.response import Responsefrom app01.wx import Wx_loginfrom django.core.cache import cachefrom app01 import modelsimport timeimport hashlibclass Login(APIView): def post(self,request): param = request.data if param.get("code"): #Wx_login是微信为我们提供的登录方法,这里的data已经有一个session_key和openid了 data=Wx_login.login(param.get("code")) if data: # 1 session_key+时间戳等到一个key.(md5 md5=hashlib.md5() md5.update(data.get("session_key").encode("utf8")) md5.update(str(time.time()).encode("utf8")) key=md5.hexdigest() #2 session_key与openid做绑定等到val val=data.get("session_key")+'&'+data.get("openid") #3key->val存到redis, cache.set(key,val) #4把openid存到数据库 user_data=models.Wxuser.objects.filter(openid=data.get("openid")).first() if not user_data: models.Wxuser.objects.create(openid=data.get("openid")) #5把key返回给小程序 return Response({"code": 200, "msg": "suc","data":{"token":key}}) else: return Response({"code": 202, "msg": "code无效"}) else: return Response({"code":201,"msg":"缺少参数"})
Wx_login
import requests# appid={}&secret={}&js_code={}from app01.wx import settingsdef login(code): #code2Session是wx提供的url,填入你的appid和appsecret以及前端发送来的code url=settings.code2Session.format(settings.AppId,settings.AppSecret,code) reponse=requests.get(url=url) #得到的data里面有session_key和openid。 data=reponse.json() print(data) if data.get("session_key"): return data else: return False
settings
#你注册的小程序的 appid 和 appsecret,code2Session是有官方提供的。pay_mchid是商铺号,需要工商证才能办理,所以自己没法搞。 AppId="wx69a0dca5c6b02a43"AppSecret="9d0f80642f4861b53df04a2f7bd65a59"code2Session="https://api.weixin.qq.com/sns/jscode2session?appid={}&secret={}&js_code={}&grant_type=authorization_code"pay_mchid ='1415981402'pay_apikey = 'xi34nu5jn7x2uujd8u4jiijd2u5d6j8e'
The login is completed.
Authorization
html is a button plus a click event, I won’t write it down, it mainly depends on what the click event does
luying: function () { //这个方法的作用是获取配置,看所有的权限 wx.getSetting({ //获取成功后进入 success(res) { console.log("res", res.authSetting['scope.record']) //authSetting是这个权限的列表,这一句是看里面有没有录音这个权限 if (!res.authSetting['scope.record']) { //没有权限的话就会走这一句,这个方法的作用是获取权限 wx.authorize({ //固定写法权限就是scope.xxx这样的 scope: 'scope.record', success() { // 用户已经同意小程序使用录音功能,后续调用 wx.startRecord 接口不会弹窗询问 wx.startRecord() }, //在失败前就已经调用了上面的获取权限,如果没有给权限的话,就会走这个方法。 fail() { console.log("你没有授权") } }) } else { // wx.startRecord() } } }) },
(Learning video sharing: php Video tutorial)
Permission to obtain user information
Because user information may contain some sensitive information, such as session_key or openid, etc., if you want to obtain information on the front end, just Permission must be requested.
It should be noted that this method is wrong
<button bind:tap="info">用户信息</button>
It must be written like this, so that when obtaining the request, some key things will be passed into the click event inside.
<button open-type="getUserInfo" bindgetuserinfo="info1">获取用户信</button>
js
info1: function (res) { console.log(res, "按钮") // wx.getUserInfo({ // success: function (res) { // console.log(res, "用户信息") // } // }) var that = this //这个方法是用来看你session_key有没有过期的 wx.checkSession({ success() { //session_key 未过期,并且在本生命周期一直有效 wx.request({ url: app.globalData.URL + "userinfo/", data: { //这个东西就是用户信息了,里面包含敏感信息,是按钮点击的时候传进来的 encryptedData: res.detail.encryptedData, //同上,也是点击的时候传进来的 iv: res.detail.iv, //登录成功后返回的token带上 token: wx.getStorageSync("token") }, header: { "content-type": "application/json" }, method: "POST", success: function (e) { console.log(e) } }) }, fail() { // session_key 已经失效,需要重新执行登录流程 wx.login() //重新登录 } }) }
Related recommendations: 小program development tutorial
The above is the detailed content of How to implement login and authorization for mini programs. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

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

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics











With the rapid development of social media, Xiaohongshu has become a popular platform for many young people to share their lives and explore new products. During use, sometimes users may encounter difficulties logging into previous accounts. This article will discuss in detail how to solve the problem of logging into the old account on Xiaohongshu, and how to deal with the possibility of losing the original account after changing the binding. 1. How to log in to Xiaohongshu’s previous account? 1. Retrieve password and log in. If you do not log in to Xiaohongshu for a long time, your account may be recycled by the system. In order to restore access rights, you can try to log in to your account again by retrieving your password. The operation steps are as follows: (1) Open the Xiaohongshu App or official website and click the "Login" button. (2) Select "Retrieve Password". (3) Enter the mobile phone number you used when registering your account

When you log in to someone else's steam account on your computer, and that other person's account happens to have wallpaper software, steam will automatically download the wallpapers subscribed to the other person's account after switching back to your own account. Users can solve this problem by turning off steam cloud synchronization. What to do if wallpaperengine downloads other people's wallpapers after logging into another account 1. Log in to your own steam account, find cloud synchronization in settings, and turn off steam cloud synchronization. 2. Log in to someone else's Steam account you logged in before, open the Wallpaper Creative Workshop, find the subscription content, and then cancel all subscriptions. (In case you cannot find the wallpaper in the future, you can collect it first and then cancel the subscription) 3. Switch back to your own steam

Thousands of ghosts screamed in the mountains and fields, and the sound of the exchange of weapons disappeared. The ghost generals who rushed over the mountains, with fighting spirit raging in their hearts, used the fire as their trumpet to lead hundreds of ghosts to charge into the battle. [Blazing Flame Bairen·Ibaraki Doji Collection Skin is now online] The ghost horns are blazing with flames, the gilt eyes are bursting with unruly fighting spirit, and the white jade armor pieces decorate the shirt, showing the unruly and wild momentum of the great demon. On the snow-white fluttering sleeves, red flames clung to and intertwined, and gold patterns were imprinted on them, igniting a crimson and magical color. The will-o'-the-wisps formed by the condensed demon power roared, and the fierce flames shook the mountains. Demons and ghosts who have returned from purgatory, let's punish the intruders together. [Exclusive dynamic avatar frame·Blazing Flame Bailian] [Exclusive illustration·Firework General Soul] [Biography Appreciation] [How to obtain] Ibaraki Doji’s collection skin·Blazing Flame Bailian will be available in the skin store after maintenance on December 28.

The solution to the Discuz background login problem is revealed. Specific code examples are needed. With the rapid development of the Internet, website construction has become more and more common, and Discuz, as a commonly used forum website building system, has been favored by many webmasters. However, precisely because of its powerful functions, sometimes we encounter some problems when using Discuz, such as background login problems. Today, we will reveal the solution to the Discuz background login problem and provide specific code examples. We hope to help those in need.

Recently, some friends have asked me how to log in to the Kuaishou computer version. Here is the login method for the Kuaishou computer version. Friends who need it can come and learn more. Step 1: First, search Kuaishou official website on Baidu on your computer’s browser. Step 2: Select the first item in the search results list. Step 3: After entering the main page of Kuaishou official website, click on the video option. Step 4: Click on the user avatar in the upper right corner. Step 5: Click the QR code to log in in the pop-up login menu. Step 6: Then open Kuaishou on your phone and click on the icon in the upper left corner. Step 7: Click on the QR code logo. Step 8: After clicking the scan icon in the upper right corner of the My QR code interface, scan the QR code on your computer. Step 9: Finally log in to the computer version of Kuaishou

When we no longer want to continue using the current Win10 Enterprise Edition 2016 Long-Term Service Edition, we can choose to switch to the Professional Edition. The method is also very simple. We only need to change some contents and install the system image. How to change win10 enterprise version 2016 long-term service version to professional version 1. Press win+R, and then enter "regedit" 2. Paste the following path directly in the address bar above: Computer\HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\WindowsNT\CurrentVersion3 , then find the EditionID and replace the content with "professional" to confirm

Baidu Netdisk can not only store various software resources, but also share them with others. It supports multi-terminal synchronization. If your computer does not have a client downloaded, you can choose to enter the web version. So how to log in to Baidu Netdisk web version? Let’s take a look at the detailed introduction. Baidu Netdisk web version login entrance: https://pan.baidu.com (copy the link to open in the browser) Software introduction 1. Sharing Provides file sharing function, users can organize files and share them with friends in need. 2. Cloud: It does not take up too much memory. Most files are saved in the cloud, effectively saving computer space. 3. Photo album: Supports the cloud photo album function, import photos to the cloud disk, and then organize them for everyone to view.

115 Netdisk is a netdisk that can store many resources, so what is the login entrance for the 115 Netdisk web version? Users need to enter the URL https://115.com to enter the Netdisk, and they can use it after logging in. This 115 Netdisk web version login latest entrance sharing can tell you how to use this function, so take a look. 115 Netdisk web version login portal website sharing: https://115.com Detailed introduction: 1. First, you need to choose a way to log in to the Netdisk. 2. You can see the uploaded file in the upper right corner. 3. You can create a new folder here and switch between different modes. 4. You can add different tags to the file. 5. Users’ private messages can be seen on the website.
