微信小程序登录注册实现

发布时间:2023-05-21

一、小程序基本配置

在开始实现微信小程序登录注册功能之前,我们需要先完成小程序的基本配置。具体步骤如下: 1、登录微信公众平台进行小程序开发,创建小程序,并且获取到AppID。 2、为小程序添加合法域名,这些域名需要在调用微信API时使用,包括登录、获取用户信息等。添加合法域名有两种方法:一种是在小程序设置中添加,另一种是在服务器配置文件中添加。 3、创建小程序登录注册页面,将页面地址添加到小程序的“app.json”文件中,使其成为小程序的子页面。

// app.json文件
{
  "pages": [
    "pages/login/login",
    "pages/index/index",
    "pages/register/register"
  ],
  "window": {
    "backgroundTextStyle": "light",
    "navigationBarBackgroundColor": "#fff",
    "navigationBarTitleText": "小程序登录注册",
    "navigationBarTextStyle": "black"
  },
  "tabBar": {
    "selectedColor": "#1296db",
    "color": "#8a8a8a",
    "borderStyle": "#e6e6e6",
    "list": [
      {
        "pagePath": "pages/index/index",
        "text": "首页"
      },
      {
        "pagePath": "pages/login/login",
        "text": "登录"
      },
      {
        "pagePath": "pages/register/register",
        "text": "注册"
      }
    ]
  }
}

二、小程序登录功能实现

为了实现小程序登录功能,我们需要使用微信开发者工具提供的 wx.login() 接口从微信服务器获取用户临时登录凭证 code。获取 code 之后,我们需要将 code 传递给服务器,在服务器端进行登录验证,通过后返回用户的信息给小程序。 1、在登录页面中使用 wx.login() 接口获取用户登录凭证 code。

// login.js文件
Page({
  data: {},
  onLoad: function () {
    // 小程序启动时首先调用wx.login()获取用户登录凭证code
    wx.login({
      success: res => {
        if (res.code) {
          // 利用code传递给服务器进行登录验证
          wx.request({
            url: 'https://example.com/api/user/login',
            data: {
              code: res.code
            },
            success: function (res) {
              if (res.data.code === 0) {
                var user = res.data.data
                // 将用户信息存储到本地
                wx.setStorageSync('user', user)
              } else {
                wx.showModal({
                  title: '提示',
                  content: res.data.msg,
                  success: function (res) {
                    if (res.confirm) {
                      console.log('用户点击确定')
                    }
                  }
                })
              }
            }
          })
        }
      }
    })
  }
})

2、在服务器端进行登录验证,验证成功后返回用户信息。

// login.php文件
<?php
header('Content-type: application/json');
$code = $_POST['code'];
$url = 'https://api.weixin.qq.com/sns/jscode2session?appid=APPID&secret=SECRET&js_code=' . $code . '&grant_type=authorization_code';
$res = file_get_contents($url);
$res = json_decode($res, true);
$openid = $res['openid'];
// 查询数据库,验证用户是否存在,存在返回用户信息
// 以下为伪代码,实际应用中需要根据自己的具体需求进行编写
$user = query_user($openid);
if ($user) {
  $result = array(
    'code' => 0,
    'msg' => '登录成功',
    'data' => $user
  );
} else {
  $result = array(
    'code' => -1,
    'msg' => '用户不存在,请先注册',
    'data' => null
  );
}
echo json_encode($result);
?>

三、小程序注册功能实现

在实现小程序注册功能时,我们需要在小程序中创建一个注册页面,用户在该页面输入注册信息后,将用户信息传递给服务器进行注册。注册成功后,自动跳转到登录页面,用户可以使用新的账号密码进行登录。 1、创建小程序注册页面,页面布局可以参照下图:

<!-- register.wxml文件 -->
<view class="container">
  <view class="register-box">
    <view class="input-box">
      <view class="icon-box">
        <img src="../../images/user.png">
      </view>
      <input placeholder="请输入您的用户名" value="{{username}}" bindinput="inputUsername">
    </view>
    <view class="input-box">
      <view class="icon-box">
        <img src="../../images/password.png">
      </view>
      <input type="password" placeholder="请输入您的密码" value="{{password}}" bindinput="inputPassword">
    </view>
    <view class="input-box">
      <view class="icon-box">
        <img src="../../images/password.png">
      </view>
      <input type="password" placeholder="请确认您的密码" value="{{confirmPassword}}" bindinput="inputConfirmPassword">
    </view>
    <button type="default" size="default" class="register-btn" bindtap="onRegister">注册</button>
  </view>
</view>

2、在小程序注册页面中处理用户注册输入信息,调用 wx.request() 接口将用户信息传递给服务器进行注册。

// register.js文件
Page({
  data: {
    username: '',
    password: '',
    confirmPassword: ''
  },
  inputUsername: function (e) {
    this.setData({
      username: e.detail.value
    })
  },
  inputPassword: function (e) {
    this.setData({
      password: e.detail.value
    })
  },
  inputConfirmPassword: function (e) {
    this.setData({
      confirmPassword: e.detail.value
    })
  },
  onRegister: function () {
    var that = this;
    if (that.data.password != that.data.confirmPassword) {
      wx.showModal({
        title: '提示',
        content: '密码不一致',
        success: function (res) {
          if (res.confirm) {
            console.log('用户点击确定')
          }
        }
      })
      return
    }
    wx.request({
      url: 'https://example.com/api/user/register',
      data: {
        username: that.data.username,
        password: that.data.password
      },
      success: function (res) {
        if (res.data.code === 0) {
          wx.showToast({
            title: '注册成功',
            icon: 'success'
          })
          wx.navigateTo({
            url: '/pages/login/login'
          })
        } else {
          wx.showModal({
            title: '提示',
            content: res.data.msg,
            success: function (res) {
              if (res.confirm) {
                console.log('用户点击确定')
              }
            }
          })
        }
      }
    })
  }
})

3、在服务器端处理用户注册请求,将用户信息存入数据库。

// register.php文件
<?php
header('Content-type: application/json');
$username = $_POST['username'];
$password = $_POST['password'];
// 将用户信息存入数据库
// 以下为伪代码,实际应用中需要根据自己的具体需求进行编写
$success = write_user($username, $password);
if ($success) {
  $result = array(
    'code' => 0,
    'msg' => '注册成功',
    'data' => null
  );
} else {
  $result = array(
    'code' => -1,
    'msg' => '注册失败,请稍后重试',
    'data' => null
  );
}
echo json_encode($result);
?>

四、小程序获取用户信息

在用户登录成功后,我们可以调用微信开发者工具提供的 wx.getUserInfo() 接口获取用户的基本信息,包括昵称、头像等,并将用户信息存储到本地。

// index.js文件
Page({
  data: {
    userInfo: null
  },
  onLoad: function () {
    var user = wx.getStorageSync('user')
    if (user) {
      this.getUserInfo(user.openid)
    }
  },
  getUserInfo: function (openid) {
    var that = this;
    wx.getUserInfo({
      success: function (res) {
        wx.setStorageSync('userInfo', res.userInfo)
        that.setData({
          userInfo: res.userInfo
        })
        wx.request({
          url: 'https://example.com/api/user/saveUserInfo',
          data: {
            openid: openid,
            userInfo: res.userInfo
          },
          success: function (res) {}
        })
      },
      fail: function (res) {
        wx.showModal({
          title: '提示',
          content: '获取用户信息失败,请检查权限设置',
          success: function (res) {
            if (res.confirm) {
              console.log('用户点击确定')
            }
          }
        })
      }
    })
  }
})

五、小结

通过微信小程序提供的 wx.login() 接口,我们可以获取到用户登录凭证 code,并通过调用服务器接口进行登录验证。而在实现小程序注册功能时,则需要调用 wx.request() 接口将用户注册信息传递给服务器进行注册。在登录成功后,我们可以使用 wx.getUserInfo() 接口获取用户的信息,并将其存储到本地。