首页 微信小程序 正文
  • 本文约5406字,阅读需27分钟
  • 2317
  • 0

微信小程序获取openid(php后台)

温馨提示:本文最后更新于2020年8月17日 10:38,若内容或图片失效,请在下方留言或联系博主。

openid是微信提供给每个微信用户独一无二的识别码,

 

这里简单介绍用php后台实现获取openid并保存到数据库;

微信的登陆流程是这样的

官方文档地址

 

首先前端发送请求到服务器:   

<view class='confirm-login'>
    <view class='title'>登录</view>
    <view class='tips'>请点击以下按钮授权登录,以便使用小程序相关功能</view>
    <button class="get-info" open-type="getUserInfo"  bindgetuserinfo="bindGetUserInfo">授权登录</button>
    <view class="bdl" bindtap="bdl">先不登录</view>
</view>

js

bindGetUserInfo: function (e) {
    console.log(e.detail.errMsg)
    this.bdl();
    wx.showLoading({
      title: '登录中...',
      mask:true,
    })
    if (e.detail.errMsg == 'getUserInfo:ok') {

      this.getUser();
      wx.hideLoading();
    } else {
      wx.hideLoading();
      wx.showModal({
        title: '授权失败',
        content: '请重新授权?',
        showCancel: false,//是否显示取消按钮
        confirmText: "好的",//默认是&ldquo;确定&rdquo;
        confirmColor: 'skyblue',//确定文字的颜色
        success: function (res) {

        },
        fail: function (res) { },//接口调用失败的回调函数
        complete: function (res) { },//接口调用结束的回调函数(调用成功、失败都会执行)
      })
    }
  },
  //获取 用户信息
  getUser: function () {
    // 获取用户信息
    let that = this;
    wx.getSetting({
      success: res => {
        if (res.authSetting['scope.userInfo']) {
          // 已经授权,可以直接调用 getUserInfo 获取头像昵称,不会弹框
          wx.getUserInfo({
            success: res => {
              // 可以将 res 发送给后台解码出 unionId
              console.log(res);
              let user = res.userInfo;
              that.setData({ user: user })
              that.loginWX()
            }
          })
        } else {
          that.setData({ loding: true });
        }
      }
    })
  },
// 微信登录
  loginWX() {
    var that = this;
    // 发起微信登录请求
    wx.login({
      success: res => {
        console.log(res.code)
        wx.request({
          url: url + 'api/wx/openid.php', //获取openid
          data: {
            code: res.code
          },
          method: 'POST',
          header: { 'content-type': 'application/x-www-form-urlencoded' },
          success: res => {
            that.setData({ openid: res.data.openid });
            that.setData({ 'user.openid': res.data.openid });
            wx.setStorage({
              key: 'openid',
              data: res.data.openid,
            });
          }
        })
      }
    })
  },

这样就实现了将前端获取的code发送到服务器,code每次获取的都不一样;

服务器openid.php代码:

<?php

    $code=$_REQUEST["code"];
  // 获取openid
  function getOpenid($code,$xcxid,$xcxkey){ // $code为小程序提供
    $appid = ''; // 小程序APPID
    $secret = ''; // 小程序secret
    $url = 'https://api.weixin.qq.com/sns/jscode2session?appid=' . $appid . '&secret='.$secret.'&js_code='.$code.'&grant_type=authorization_code';    
        
    $curl = curl_init();
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($curl, CURLOPT_TIMEOUT, 500);
    // 为保证第三方服务器与微信服务器之间数据传输的安全性,所有微信接口采用https方式调用,必须使用下面2行代码打开ssl安全校验。    
    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; // 这里是获取到的信息
}

成功实现了获取openid并存入数据库和小程序的本地缓存,不过微信小程序不建议直接将opneid作为值直接返回给小程序端,而是用户实现自己的前后端验证。

 附报错表:

image.png

官方文档地址

标签:小程序
评论