小程序登陆

app.js

/**
   * 当小程序启动,或从后台进入前台显示,会触发 onShow
   */
  onShow: function (options) {
    this.getUserInfo();
  },

  /**
   * 获取用户信息
   */
  getUserInfo: function (cb) {

    var that = this

    if (that.globalData.userInfo) {

      typeof cb == "function" && cb(that.globalData.userInfo)

    } else {

      wx.login({
        success: function (res) {
          var code = res.code
          wx.getUserInfo({
            success: function (res2) {
              that.globalData.userInfo = res2.userInfo
              var data = {encryptedData: res2.encryptedData, iv: res2.iv, code: code}
              // 存储用户信息
              util.commonAjax('/recentimgtext/saveuser', 'POST', data).then(function (resolve) {
                if (resolve.data.status === 200) {
                  wx.setStorageSync('userInfo', resolve.data.data)
                  typeof cb == "function" && cb(that.globalData.userInfo)
                } else {
                  console.log('用户信息存储失败');
                }
              })
            },
            fail: function (res2) {
              wx.navigateTo({
                url: '/pages/login/login',
              })
            }
          })
        }
      })
    }
  },

  /**
   * 全局数据
   */
  globalData: {
    userInfo: null,
    url: 'http://ci.test.com',
    // url: 'http://ci.mag998.com',
  }

utils.js

// 访问数据
const commonAjax = function (url, types, data) {
  var app = getApp();
  var promise = new Promise(function(resolve, reject, defaults) {
    wx.request({
      url: app.globalData.url + url,
      data: data,
      method: (types === 'GET') ? 'GET' : 'POST',
      header: (types === 'GET') ? {'content-type': 'application/json'} : {'content-type': 'application/x-www-form-urlencoded'},
      success: resolve,
      fail: reject,
      complete: defaults,
    })
  })
  return promise;
}

module.exports = {
  formatTime: formatTime,
  commonAjax: commonAjax
}

login.wxml

<button wx:if="{{!hasUserInfo && canIUse}}" open-type="getUserInfo" bindgetuserinfo="getUserInfo" type='primary' style='margin-top:50px;width:80%;'> 微信登陆 </button>

login.js

// pages/login/login.js
const app = getApp()
Page({

  data: {
    hasUserInfo: app.globalData.userInfo,
    canIUse: wx.canIUse('button.open-type.getUserInfo'),
  },

  getUserInfo (e) {
    // 防止getUserInfo数据未及时返回
    app.globalData.userInfo = e.detail.userInfo
    
    wx.navigateBack({
      delta: 1
    })
  }

})

saveuser控制器

// 存储用户信息
    public function saveuser()
    {
        $encryptedData = $this->input->post('encryptedData');
        $iv = $this->input->post('iv');

        $code = $this->input->post('code');
        $url = 'https://api.weixin.qq.com/sns/jscode2session?appid=' . RECENT_IMGTEXT_APPID . '&secret=' . RECENT_IMGTEXT_APPSECRET . '&js_code=' . $code . '&grant_type=authorization_code';
        $data = send_get($url);
        $sessionKey = json_decode($data)->session_key;

        $pc = new WXBizDataCrypt(RECENT_IMGTEXT_APPID, $sessionKey);
        $errCode = $pc->decryptData($encryptedData, $iv, $data); // $data为用户信息

        $message = $errCode;
        $status = 0;

        if ($errCode == 0) {

            $userinfo = json_decode($data, true);
            $openid = $userinfo['openId'];
            unset($userinfo['watermark']);
            $checkuser = $this->db->get_where($this->recent_user_table, ['openId' => $openid])->row_array();
            if (empty($checkuser)) {
                $userinfo['created_at'] = date("Y-m-d H:i:s");
                if ($this->db->insert($this->recent_user_table, $userinfo));
                $message = '添加成功';
                $status = 200;
            } else {
                unset($userinfo['openId']);
                $userinfo['updated_at'] = date("Y-m-d H:i:s");
                if ($this->db->update($this->recent_user_table, $userinfo, 'openId = "' . $openid . '"'));
                $message = '更新成功';
                $status = 200;
            }
        }
        echo json_encode(['data' => $data, 'message' => $message, 'status' => $status]);
    }

 

转载于:https://www.cnblogs.com/maoriaty/p/9948411.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值