php教程

超轻量级php框架startmvc

php实现微信小程序授权登录功能(实现流程)

更新时间:2020-04-13 18:43 作者:startmvc
先上图实现流程:1、授权登陆按钮和正文信息放到了同一个页面,未授权的时候显示登陆

先上图

实现流程:

1、授权登陆按钮和正文信息放到了同一个页面,未授权的时候显示登陆按钮,已授权的时候隐藏登陆按钮,显示正文信息,当然也可以授权和正文分开成两个页面,在授权页面的onload里判断是否已授权,若已授权就直接跳转正文的页面。这里只说授权按钮和正文在同一页面的情况。

2、在onload里先判断是否已授权,如果已授权,就隐藏授权登陆按钮,显示正文信息,如果没有授权,显示授权登陆按钮。

3、前端使用button的open-type="getUserInfo"来操作,点击授权按钮之后,“e”中会携带userInfo,用户的基本信息(和使用wx.getUserInfo接口获取的数据一样,所以我是在"e"里面直接取的,没有调用wx.getUserInfo接口)

4、使用wx.login接口获取登陆凭证code,使用code去后解密换取openid,传输code的时候带上第3步获取的用户信息一块发送给后台解密(也可以不携带,携带的目的是为了验证签名,这样安全一些,不验证也可以)

5、后台解密使用的是“auth.code2Session”接口,解密用到的SDK下载地址

“https://developers.weixin.qq.com/miniprogram/dev/framework/open-ability/signature.html”。

5、后台解密之后(后台语言用的是php),会返回openid等敏感信息,就还可以把这些信息存起来了。

6、获取授权成功之后,再隐藏授权登陆按钮,显示正文信息。

7、如果用户点击拒绝授权,提示引导用户再次授权。

注意,要考虑到授权失败的情况

以下是详细代码

wxml


<view wx:if="{{isHide}}">
 <view wx:if="{{canIUse}}" >
 <view class='header'>
 <image src='/images/icon/wx_login.png'></image>
 </view>
 
 <view class='content'>
 <view>申请获取以下权限</view>
 <text>获得你的公开信息(昵称,头像等)</text>
 </view>
 
 <button class='bottom' type='primary' open-type="getUserInfo" lang="zh_CN" bindgetuserinfo="bindGetUserInfo">
 授权登录
 </button>
 </view>
 <view wx:else>请升级微信版本</view>
</view>
 
<view wx:else>
 <view>我的首页内容</view>
</view>

wxss


.header {
 margin: 90rpx 0 90rpx 50rpx;
 border-bottom: 1px solid #ccc;
 text-align: center;
 width: 650rpx;
 height: 300rpx;
 line-height: 450rpx;
}
.header image {
 width: 200rpx;
 height: 200rpx;
}
.content {
 margin-left: 50rpx;
 margin-bottom: 90rpx;
}
.content text {
 display: block;
 color: #9d9d9d;
 margin-top: 40rpx;
}
.bottom {
 border-radius: 80rpx;
 margin: 70rpx 50rpx;
 font-size: 35rpx;
}

js


// pages/test1/test1.js
var app = getApp();
Page({
 /**
 * 页面的初始数据
 */
 data: {
 //判断小程序的API,回调,参数,组件等是否在当前版本可用。
 canIUse: wx.canIUse('button.open-type.getUserInfo'),
 isHide: false
 },
 /**
 * 生命周期函数--监听页面加载
 */
 onLoad: function (options) {
 var that = this;
 // 查看是否授权
 wx.getSetting({
 success: function (res) {
 if (!res.authSetting['scope.userInfo']) {
 // 还未授权,显示授权按钮
 that.setData({
 isHide: true
 });
 } else {
 // 已授权,隐藏授权按钮,显示正文
 that.setData({
 isHide: false
 });
 }
 }
 })
 },
 //授权登陆按钮
 bindGetUserInfo: function (e) {
 var that = this;
 console.log(e)
 if (e.detail.userInfo) {
 //用户授权登陆,并跳转首页
 // that.getOpenid()
 wx.login({
 success: function (res) {
 // 请求自己后台获取用户openid
 wx.request({
 url: app.domain + 'teacherapi/Wx_Decode/WxDecode',
 method: 'POST',
 header: { 'content-type': 'application/x-www-form-urlencoded' },
 data: {
 encryptedData: e.detail.encryptedData,
 signature: e.detail.signature,
 rawData: e.detail.rawData,
 iv: e.detail.iv,
 code: res.code
 },
 success: function (res_user) {
 if (res_user.data.status == 0) {
 var data = JSON.parse(res_user.data.msg)    //json转对象
 //授权成功返回的数据,根据自己需求操作
 console.log(data)
 //授权成功后,隐藏授权按钮,显示正文
 that.setData({
 isHide: false
 });
 }
 }, fail: function () {
 that.showModal('获取授权信息失败')
 }
 })
 }
 })
 } else {
 //用户按了拒绝授权按钮,提示引导授权
 that.showModal('请授权后使用小程序')
 }
 },
 //未授权弹窗
 showModal: function (e) {
 wx.showModal({
 title: '提示',
 content: e,
 showCancel: false,
 confirmText: '返回授权',
 success: function (res) {
 if (res.confirm) {
 console.log('用户点击了“返回授权”')
 }
 }
 })
 },
})

php


<?php
namespace app\teacherapi\controller;
use think\Controller;
/**
* @date: 2018-12
* 微信操作类
*/
class WxDecode extends Controller
{
 public function httpGet($url) {
 $curl = curl_init();
 curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
 curl_setopt($curl, CURLOPT_TIMEOUT, 500);
 curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
 curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
 curl_setopt($curl, CURLOPT_URL, $url);
 $res = curl_exec($curl);
 curl_close($curl);
 return $res;
 }
 /**
 * @author: zxf
 * @date: 2018-12-08
 * @description: 解密微信用户敏感数据
 * @return array
 */
 public function WxDecode()
 {
 // 接收参数
 $data = request() -> param();
 // 引入解密文件 在微信小程序开发文档下载
 vendor('wx.WXBizDataCrypt');
 vendor('wx.ErrorCode');
 $appid = config('TESTPPID');
 $appsecret = config('TESTSECREET');
 $grant_type = "authorization_code"; //授权(必填)
 $code = $data['code']; //有效期5分钟 登录会话
 $encryptedData=$data['encryptedData'];
 $iv = $data['iv'];
 $signature = $data['signature'];
 $rawData = $data['rawData'];
 // 拼接url
 $url = "https://api.weixin.qq.com/sns/jscode2session?"."appid=".$appid."&secret=".$appsecret."&js_code=".$code."&grant_type=".$grant_type;
 $res = json_decode($this->httpGet($url),true);
 $sessionKey = $res['session_key']; //取出json里对应的值
 $signature2 = sha1(htmlspecialchars_decode($rawData).$sessionKey);
 // 验证签名
 if ($signature2 !== $signature){
 return json("验签失败");
 } 
 // 获取解密后的数据
 $pc = new \WXBizDataCrypt($appid, $sessionKey);
 $errCode = $pc->decryptData($encryptedData, $iv, $data );
 if ($errCode == 0) {
 return return_succ($data);
 } else {
 return return_error($errCode);
 }
 }
}