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

Zend Studio 13.0.1
Powerful PHP integrated development environment

SublimeText3 Linux new version
SublimeText3 Linux latest version

SAP NetWeaver Server Adapter for Eclipse
Integrate Eclipse with SAP NetWeaver application server.

MinGW - Minimalist GNU for Windows
This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

DVWA
Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software
