微信小程序获取用户头像+昵称+openid,小程序登录!附前端后端源码!

做一款小程序,如果需要判断用户,当然要获取一些基本信息,例如头像,昵称,openid。所以本次案例就直接上代码了。

小程序前端

index.wxml

<!--index.wxml-->
<view class="container">
  <view class="userinfo">
    <button wx:if="{{!hasUserInfo && canIUse}}" open-type="getUserInfo" bindgetuserinfo="getUserInfo"> 获取头像昵称 </button>
    <block wx:else>
      <image bindtap="bindViewTap" class="userinfo-avatar" src="{{userInfo.avatarUrl}}" mode="cover"></image>
      <text class="userinfo-nickname">{{userInfo.nickName}}</text>
    </block>
  </view>
  <view class="usermotto">
    <text class="user-motto">{{motto}}</text>
  </view>
</view>

index.js

//index.js
//获取应用实例
const app = getApp()

Page({
  data: {
    motto: 'Hello World',
    userInfo: {},
    hasUserInfo: false,
    canIUse: wx.canIUse('button.open-type.getUserInfo')
  },

  onLoad: function () {
    if (app.globalData.userInfo) {
      this.setData({
        userInfo: app.globalData.userInfo,
        hasUserInfo: true
      })
    } else if (this.data.canIUse){
      // 由于 getUserInfo 是网络请求,可能会在 Page.onLoad 之后才返回
      // 所以此处加入 callback 以防止这种情况
      app.userInfoReadyCallback = res => {
        this.setData({
          userInfo: res.userInfo,
          hasUserInfo: true
        })
      }
    } else {
      // 在没有 open-type=getUserInfo 版本的兼容处理
      wx.getUserInfo({
        success: res => {
          app.globalData.userInfo = res.userInfo
          this.setData({
            userInfo: res.userInfo,
            hasUserInfo: true
          })
        }
      })
    }
  },
  getUserInfo: function(e) {
    console.log(e)
    app.globalData.userInfo = e.detail.userInfo

    //获取openid
    wx.login({
      success: function (res) {
        console.log(res.code)
        //发送请求获取openid
        wx.request({
          url: '你的域名/openid.php?code=code', //接口地址
          data: { code: res.code },
          header: {
            'content-type': 'application/json' //默认值
          },
          success: function (res) {
            //返回openid
            console.log(res.data.openid)
            //向数据库注册用户,验证用户
            var that = this;
            wx.request({
              url: '你的域名/server.php?nickname=' + e.detail.userInfo.nickName + '&avatarUrl=' + e.detail.userInfo.avatarUrl + '&openid=' + res.data.openid,
              data: {

              },
              header: {
                'content-type': 'application/json'
              },
              success: function (res) {
                //打印用户信息
                console.log(res.data)
              }
            })
          }
        })
      }
    })

    
    this.setData({
      userInfo: e.detail.userInfo,
      hasUserInfo: true,
    })
  }
})

index.wxss

/**index.wxss**/
.userinfo {
  display: flex;
  flex-direction: column;
  align-items: center;
}

.userinfo-avatar {
  width: 128rpx;
  height: 128rpx;
  margin: 20rpx;
  border-radius: 50%;
}

.userinfo-nickname {
  color: #aaa;
}

.usermotto {
  margin-top: 200px;
}

后端

openid.php
这是通过code获取openid的后端

<?php
//声明CODE,获取小程序传过来的CODE
$code = $_GET["code"];
//配置appid
$appid = "你的小程序APPID";
//配置appscret
$secret = "你的小程序APPSRCRET";
//api接口
$api = "https://api.weixin.qq.com/sns/jscode2session?appid={$appid}&secret={$secret}&js_code={$code}&grant_type=authorization_code";
//获取GET请求
function httpGet($url){
    $curl = curl_init();
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($curl, CURLOPT_TIMEOUT, 500);
    curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, true);
    curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, true);
    curl_setopt($curl, CURLOPT_URL, $url);
    $res = curl_exec($curl);
    curl_close($curl);
    return $res;
}
//发送
$str = httpGet($api);
echo $str;
?>

server.php
这是把用户名、头像、openid存到数据库的后端

<?php
header("Content-type:text/html;charset=utf8");
$nickname = $_GET["nickname"];
$avatarUrl = $_GET["avatarUrl"];
$openid = $_GET["openid"];
$con = mysql_connect("数据库地址","数据库账号","数据库密码");
mysql_select_db("数据库名", $con);
mysql_query("INSERT INTO 表名 (nickname, avatarUrl, openid) VALUES ('$nickname', '$avatarUrl', '$openid')");
echo "注册成功!";
mysql_close($con);
?>

数据库

clipboard.png

学习交流微信:face6009

阅读 13.1k

推荐阅读