TypechoJoeTheme

至尊技术网

统计
登录
用户名
密码
/
注册
用户名
邮箱

微信小程序开发用户授权登录、获取手机号、昵称、头像

2022-02-28
/
0 评论
/
794 阅读
/
正在检测是否收录...
02/28

login.wxml

<button open-type="getUserProfile" bindtap="getUserProfile"> 获取头像昵称 </button>
<button bindtap='onLogin'>授权登录</button>
<button open-type="getPhoneNumber" bindgetphonenumber="getPhoneNumber">获取手机号</button>

server.js

// 服务接口地址
const base = 'http://localhost/';
// 开放接口配置
export default{
  apiUrl:base + 'api.php'
}

login.js

//加载公共api文件server.js
import API from '../../config/server.js'
Page({
  /**
   * 页面的初始数据
   */
  data: {
    
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function () {
    this.userLogin();
    var uid = wx.getStorageSync('uid');
    console.log(uid);
  },
  userLogin(){
    if(!wx.getStorageSync('uid')){
        onLogin()
    }else{
        wx.request({
            url: API.apiUrl,
            method: 'post',
            data: {act: 'isUser',id: wx.getStorageSync('uid')},
            success: function(res){
                if(res.data.code == -1){
                    onLogin()
                }else{
                    wx.checkSession({
                        success () {
                            //session_key 未过期,并且在本生命周期一直有效
                            console.log('已登录');
                            var pages = getCurrentPages()    //获取加载的页面
                            var currentPage = pages[pages.length-1]    //获取当前页面的对象
                            var url = currentPage.route    //当前页面url
                            var options = currentPage.options    //如果要获取url中所带的参数可以查看options
                            console.log(url)
                            if(url.indexOf('/login') != -1){
                                wx.navigateBack({
                                delta: 2
                                })
                            }
                        },
                        fail () {
                            // session_key 已经失效,需要重新执行登录流程
                            onLogin() //重新登录
                            console.log('未登录');
                        }
                    })
                }
            }
        })
    }
  },
  onLogin() {
    wx.login({
      success (res) {
        if (res.code) {
          //发起网络请求
          wx.request({
            url: API.apiUrl,
            method: 'post',
            data: {
              act: 'onLogin',
              code: res.code
            },
            success:function(res){
              console.log(res.data)
              if(res.data.code == 0){
                wx.setStorage({key: 'uid',data: res.data.id})
              }else{
                wx.showToast({
                  title: '获取用户id失败',
                  icon: 'error'
                })
                setTimeout(() => {
                  this.onLogin();
                }, 1500);
              }
            }
          })
        } else {
          console.log('登录失败!' + res.errMsg)
        }
      }
    })
  },
  getUserProfile(e){
    wx.getUserProfile({
      desc: '用于完善会员资料', // 声明获取用户个人信息后的用途,后续会展示在弹窗中,请谨慎填写
      success: (res) => {
        console.log(res.userInfo)
        wx.setStorage({key: 'userInfo',data: res.userInfo})
      }
    })
  },
  getPhoneNumber (e) {
    console.log(e.detail.code)
    wx.request({
      url: API.apiUrl,
      method: 'post',
      data: {
        act: 'getPhone',
        code: e.detail.code
      },
      success:function(res){
        console.log(res.data)
        if(res.data.code != 0){
          wx.showToast({
            title: res.data.msg,
            icon: 'error'
          })
        }else{
          wx.setStorage({key: 'phone',data: res.data.phone})
        }
      }
    })
  }
})

api.php

<?php
header('content-type: application/json;charset=utf-8');
require 'common.php';
$post = $_POST;
$data = ['code' => -1,'msg' => '获取失败'];
if(empty($post)){
    $post = json_decode(file_get_contents('php://input'),true);
}
switch($post['act']){
    case 'onLogin':
        if(!preg_match('/\w/',$post['code'])){
            $data['msg'] = 'code格式错误';
            break;
        }
        $code2Session = get_curl("https://api.weixin.qq.com/sns/jscode2session?appid={$config['appId']}&secret={$config['appSecret']}&js_code={$post['code']}&grant_type=authorization_code");
        $code2Session = json_decode($code2Session,true);
        if(isset($code2Session['errcode']) && $code2Session['errcode'] != 0){
            $data['msg'] = '登录失败';
        }else{
            $data = ['code' => 0,'msg' => '登录成功'];
            $row = getOne("select id from userlist where openid='{$code2Session['openid']}'");
            if($row){
                $data['id'] = $row['id'];
            }else{
                $res = insert('userlist',['nickname' => '','avatar_url' => '','phone' => '','login_time' => time(),'openid' => $code2Session['openid']]);
                $data['id'] = $res;
            }
        }
    break; 

    case 'getPhone':
        if(!preg_match('/\w/',$post['code'])){
            $data['msg'] = 'code格式错误';
            break;
        }
        $getAccessToken = get_curl("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={$config['appId']}&secret={$config['appSecret']}");
        $getAccessToken = json_decode($getAccessToken,true);
        $getPhoneNumber = get_curl("https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token={$getAccessToken['access_token']}",json_encode(['code' => $post['code']]));
        $getPhoneNumber = json_decode($getPhoneNumber,true);
        if($getPhoneNumber['errcode'] == 0){
            $data['phone'] = $getPhoneNumber['phone_info']['purePhoneNumber'];
        }
    break;
}
echo json_encode($data);
微信小程序经验头像授权登录手机号昵称
朗读
赞(0)
版权属于:

至尊技术网

本文链接:

https://www.zzwws.cn/archives/6330/(转载时请注明本文出处及文章链接)

评论 (0)