小程序获取openid之后将微信获取的信息传入数据库

小程序端代码:
wx.login参考文档:https://developers.weixin.qq.com/miniprogram/dev/api/open-api/login/wx.login.html
auth.code2Session参考文档:https://developers.weixin.qq.com/miniprogram/dev/api-backend/open-api/login/auth.code2Session.html

登录凭证校验。通过 wx.login 接口获得临时登录凭证 code 后传到开发者服务器调用此接口完成登录流程。

请求地址
GET https://api.weixin.qq.com/sns/jscode2session?appid=APPID&secret=SECRET&js_code=JSCODE&grant_type=authorization_code

请求参数
appid string 是 小程序 appId
secret string 是 小程序 appSecret
js_code string 是 登录时获取的 code
grant_type string 是 授权类型,此处只需填写 authorization_code

返回值
openid string 用户唯一标识
session_key string 会话密钥
unionid string 用户在开放平台的唯一标识符,在满足 UnionID 下发条件的情况下会返回,详见 UnionID 机制说明。
errcode number 错误码
errmsg string 错误信息

errcode 的合法值
-1 系统繁忙,此时请开发者稍候再试
0 请求成功
40029 code 无效
45011 频率限制,每个用户每分钟100次

my.wxml

<view class="display_row myViewTop_userinfo">
   <button wx:if="{{!hasUserInfo && canIUse}}" open-type="getUserInfo" bindgetuserinfo="getUserInfo"> 获取头像昵称 </button>
    <block wx:else>
        <image src="{{userInfo.avatarUrl}}"></image> //头像
        <view>{{userInfo.nickName}}</view> // 昵称
    </block>
  </view>

my.js

const app = getApp();
Page({
  data: {
    userInfo: {},
    hasUserInfo: false,
    canIUse: wx.canIUse('button.open-type.getUserInfo'),
    
  },
  // 点击获取头像昵称 按钮获取用户昵称头像及wx.login的code(该code用来获取openid)
  getUserInfo: function (e) {
    var that = this;
    if (e.detail.userInfo){
      app.globalData.userInfo = e.detail.userInfo; //存入全局变量方便后面调用
      // 请求后端获取openid
      wx.login({
        success: function(res){
          app.getAjax('getauthCode',{'code':res.code},that.getauthCode);
        }
      })
    }else{
      this.setData({
        hasUserInfo: false
      })
    }
  },
  
  // 调用后台获取openid接口之后进行绑定数据库
  getauthCode: function(res){
    if(res.data.code == 1){
      var userinfo = app.globalData.userInfo;
      var openid = res.data.data.openid;
      var data = {
        'avatarUrl':userinfo.avatarUrl,
        'nickName':userinfo.nickName,
        'gender':userinfo.gender,
        'openid':openid
      };
      app.getAjax('adduser',data,this.addauth); //将获取到的openid及其他值传入后端添加用户接口中
    }else{
      wx.showToast({
        title: '获取用户信息失败',
        icon:'none'
      })
    }
  },
  // 添加用户接口成功回调函数
  addauth: function(e){
    var that = this;
    if(e.data.code == 1){
      //存入本地缓存
      wx.setStorage({
        data: e.data.data,
        key: 'authinfo',
        success: function(){
          that.setData({
            userInfo:e.data.data,
            hasUserInfo: true
          })
        }
      })
    }
  },
  onShow: function(){
    var that = this;
    wx.getStorage({
      key: 'authinfo',
      success:function(res){
        that.setData({
          userInfo:res.data,
          hasUserInfo: true
        })
      },
      fail:function(){
        that.setData({
          hasUserInfo:false
        })
      }
      }
    })
  },
})

app.js

//app.js
App({
  onLaunch: function () {
    
  },
  globalData: {
    userInfo: null,
    userid:''
  },
  getAjax: function (url, data, callback){
    wx.request({
      url: 'http://192.168.1.38/demo/public/index.php/'+url,
    header: {
      'content-type': 'application/x-www-form-urlencoded',
    },
    method: 'POST',
    data: data,
    dataType: 'json',
    success: function (res) {
      callback(res);
    },
    fail:function(err){
      callback(err);
    }
    })
  },
  
})

后端(thinkphp5)

// 获取用户登录凭证校验(openid)
    public function getauthCode(){
        $appid = ''; // 小程序id
        $secret = ''; // 小程序appSecret
        $js_code = input('post.code'); // wx.login获取的 code
        //grant_type 授权类型,此处只需填写 authorization_code
        $method= "GET";
        $host = "https://api.weixin.qq.com";
        $path = '/sns/jscode2session';
        $querys = "appid={$appid}&secret={$secret}&js_code={$js_code}&grant_type=authorization_code";
        $url= $host.$path.'?'.$querys;
        $weixin = file_get_contents($url);
        $jsondecode = json_decode($weixin);
        $array = get_object_vars($jsondecode);
        return output_data(200,$array);
    }
// 注册用户
    public function adduser(){
        $data = input('post.');
        // 判断是否已有openid
        $userinfo = db("user")->where('openid',input('post.openid'))->find();
        if($userinfo != null || !empty($userinfo)){
            return output_data(200,$userinfo);
        }
        $res=db('user')->insert($data);
        if($res){
            $userinfo = db("user")->where('openid',input('post.openid'))->find();
            return output_data(200,$userinfo);
        }else{
            return output_error(203);
        }
    }

file_get_contents(): Unable to find the wrapper “https” - did you forget to enable it 的解决:
1.windows下的PHP,只需要到php.ini中把extension=php_openssl.dll前面的;删掉,重启服务就可以了。
2.linux下的PHP,就必须安装openssl模块,安装好了以后就可以访问了。
转自:https://blog.csdn.net/tonydandelion2014/article/details/50864786

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值