欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

微信小程序+php 授权登陆,完整代码

程序员文章站 2022-06-07 11:51:57
先上图 实现流程: 1、授权登陆按钮和正文信息放到了同一个页面,未授权的时候显示登陆按钮,已授权的时候隐藏登陆按钮,显示正文信息,当然也可以授权和正文分开成两个页面,在授权页面的onload里判断是否已授权,若已授权就直接跳转正文的页面。这里只说授权按钮和正文在同一页面的情况。 2、在onload里 ......

先上图

微信小程序+php 授权登陆,完整代码  微信小程序+php 授权登陆,完整代码  微信小程序+php 授权登陆,完整代码  微信小程序+php 授权登陆,完整代码

 

实现流程:

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下载地址“”。

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);
        }
    }
        
}