微信小程序--授权登录

1.wxml

通过按钮触发绑定事件,来授权登录。

<!-- 如果只是展示用户头像昵称,可以使用 <open-data /> 组件 -->
<open-data type="userAvatarUrl"></open-data>
<open-data type="userNickName"></open-data>
<!-- 需要使用 button 来授权登录 -->
<button type="primary" open-type="getUserInfo" bindtap="login">授权登录</button>

 

2.js

       在后端js页面里面写入。

 data: {
    canIUse: wx.canIUse('button.open-type.getUserInfo')
  },

  login() {
    undefined
    wx.getUserProfile({
      undefined,
      desc: '用于完善会员资料',
      success: (res) => {
        undefined
        wx.login({
          undefined,
          success(res) {
            undefined
            // 判断是否有code
            console.log(res.code)
            if (res.code) {
              undefined
              //发起网络请求
              wx.request({
                undefined,
                url: 'http://www.xiao.com/index.php/Wlogin',//填写自己的地址
                method: "POST",
                data: {
                  undefined,
                  code: res.code
                },
                success(res) {
                  undefined
                  console.log(res.data.data)
                  // 缓存session_key
                  wx.setStorage({
                    undefined,
                    key: "openid",
                    data: res.data.data.openid
                  })
                  // 跳转到成功页面
                  wx.navigateTo({
                    undefined,
                    url:"/pages/me/me"//跳转页面地址
                  })
                }
              })
            } else {
              undefined
              console.log('登录失败!' + res.errMsg)
            }
          }
        })
      }
    })
  },

3.后端框架

//微信授权登录
    public function WxLogin(Request $request)
    {
        //   接收code
        $code = $request->post("code");
        //   读取appid
        $appId = "wxa2469ff6402360ff";
        //  读取开发密钥
        $appSecret = "47732169fb165797f0303f1f781de142";
        //向平台换取session_key和open_id
        $url = "https://api.weixin.qq.com/sns/jscode2session?appid={$appId}&secret={$appSecret}&js_code={$code}&grant_type=authorization_code";
        //    用curl对接
        $headerArray = array("Content-type:application/json;", "Accept:application/json");
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_HTTPHEADER, $headerArray);
        $output = curl_exec($ch);
        curl_close($ch);
        $output = json_decode($output, true);
        return json(['data' => $output]);
    }

效果图:

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值