作者:Duzling
链接:https://www.jianshu.com/p/205a244b4c1f
来源:简书
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。

登录及获取微信用户信息

调用wx.login()获取登录凭证code,再调用后端接口换取用户登录态信息(openid, session_key)

    此时获得的登录状态具有时效性,可以调用wx.checkSession()检查是否过期,若过期,则需要重新调用wx.login()执行登录流程

使用wx.getSetting()获取用户授权列表
    若已授权:调用wx.getUserInfo()获取用户信息
    若未授权:弹出模态框展示一个 微信授权登录 按钮提示用户点击登录
        同意授权:用户授权后可通过绑定的方法获取用户信息
        拒绝授权:则无法获取用户信息,若必须微信授权登录才可用,可以以恰当的方式给出说明,如使用wx.openSetting()引导用户手动打开授权开关

将获取到的用户信息和第1部中得到的code使用服务端提供的接口更新用户信息,如1中的示例

授权绑定微信手机号

显示授权绑定微信手机号的按钮(必须用户手动点击)
用户同意授权后,调用成功回调处理后续操作

相应接口代码示例

用户授权列表:wx.getSetting()

wx.getSetting({
  success (res) {
    console.log(res.authSetting)
    // res.authSetting = {
    //   "scope.userInfo": true, // true已授权 false未授权
    //   "scope.userLocation": true
    //    ...
    // }
  }
})

检查登录态是否过期

wx.checkSession({
  success () {
    //session_key 未过期,并且在本生命周期一直有效
  },
  fail () {
    // session_key 已经失效,需要重新执行登录流程
    wx.login() //重新登录
  }
})

调用wx.login()进行登录并获取cookies

wx.login({
    success: function(res) {
        // 得到了code
        if (res.code) {
            wx.request({
                url: api.user.authLogin(res.code) // 后端提供的验证登录接口
                success: function(response) {
                 // 验证成功,保存cookies, 封装在全局统一的请求方法中,如get, post
                    wx.setStorage({
                     key: 'cookies',
                     data: response.data.res.cookies
                    })
                 
                    wx.getUserInfo({
                     withCredentials: true,
                        success: function(res) {
                            // 取得用户微信信息,调用后端接口更新用户信息
                            const userInfo = res.userInfo
                            const encryptedData = res.encryptedData
                         const iv = res.iv
                            
                            const params = {
                              nick_name: userInfo.nickName,
                              gender: userInfo.gender,
                              province: userInfo.province,
                              city: userInfo.city,
                              country: userInfo.country,
                              avatar_url: userInfo.avatarUrl,
                              encrypted_data: encryptedData,
                              encrypt_iv: iv
                            }

                            server.get(api.user.updateBaseInfo(), params, () => {
                             // 成功保存用户信息
                            })
                        }
                    })
             }
            })
        }
    }
})

微信授权登录

<button open-type="getUserInfo" bindgetuserinfo="onGetUserInfo">微信登录</button>
methods = {
    onGetUserInfo: this.handleGetUserInfo
}

// 同意授权
handleGetUserInfo(e) {
    wx.getUserInfo()
}

授权获取微信绑定的手机号

<button open-type="getPhoneNumber" bindgetphonenumber="onGetPhoneNumber">
    绑定微信手机号
</button>
methods = {
    onGetPhoneNumber: this.handleGetPhoneNumber
}

/**
* 同意授权获取手机号
* @desc 获取到 encryptedData,iv信息,需要服务端解密才能获取到真正的手机号
*/
handleGetPhoneNumber(e) {
    if (e.detail.iv) {
        server.post(api.user.bindWXPhoneNumber(), {
            encrypted_data: e.detail.encryptedData,
            encrypt_iv: e.detail.iv
        }, data => {
            wx.showToast({ title: '绑定成功' })
            // do something
        }, error => {
            wx.showModal({
                title: '绑定失败',
                content: '[服务端返回的错误信息]',
                showCancel: false,
                success: res => {
                    if (res.confirm) { // 用户确认后
                        // do something
                    }
                }
            })
        })
    } else { // 用户拒绝授权
        // do something
    }
}

 #多维数组创建
let app_info =[
    {appid:info[appid],path:info[path],extend_data:info[extend_data]}
  ]

 #一维数组创建

let app_info ={appid:info[appid],path:info[path],extend_data:info[extend_data]}
  

    swipclick:function(event){
  console.log(event)
  let item_url =event.currentTarget.dataset.url // 页面跳转地址
  console.log(item_url)
  let tolink  = '../../pages/h5view?url='+encodeURIComponent(item_url);
  if(item_url){
    //先提示后跳转
     wx.showModal({
      title: '跳转提示',
      content: '您即将离开XXX,请注意您的账号和财产安全!',
      confirmColor: "#1aad19",
      success: function (sm) {
          if(sm.confirm){
              wx.navigateTo({
              url: tolink,
              })
          }
      }
   })
  }
  console.log('嘿嘿')
},

一、先解决焦点图的点击事件
wxml部分

<swiper indicator-dots='true' 
    indicator-active-color='#ff5777'
    autoplay='true'
    circular='true'
    interval='5000'
    class='swiper'>

<block wx:for="{{bannerList}}" wx:key="index">

<swiper-item>
  <image class="swiper-image" src="{{item.img_url}}" data-id="{{item.img_id}}" data-url="{{item.img_path}}" bindtap="swipclick" mode='scaleToFill'/>
</swiper-item>

</block>
</swiper>

js部分

    swipclick:function(event){
  console.log(event)
  let item_url =event.currentTarget.dataset.url // 页面跳转地址
  let tolink  = '../../pages/h5view?url='+encodeURIComponent(item_url);
  wx.navigateTo({
    url: tolink,
  })
  console.log('嘿嘿')
},

二、制作一个空白page承载URL的加载内容
我这里在page/h5view创建了一个page
h5view.js在

/**

  • 生命周期函数--监听页面加载
    */

onLoad: function (options) {

  let now_url =decodeURIComponent(options.url);
  //获取url内容
  url:now_url ,
  this.setData({
      url: now_url,
  })

},

这里接收从navigateTo过来的参数

然后渲染到wxml里

<view class="container">

<view class="pageH5">
<web-view src="{{url}}"></web-view>
</view>
</view>

frontend/web/index.php

<?php

defined('YII_DEBUG') or define('YII_DEBUG', true);  //false 换成true

1.composer安装phpoffice

命令如下

composer require phpoffice/phpexcel

5.png

2.读取demo.xsl示例

命名空间

use PhpOfficePhpSpreadsheetCellCoordinate;
use PhpOfficePhpSpreadsheetReaderXlsx;
use PhpOfficePhpSpreadsheetReaderXls;
use PhpOfficePhpSpreadsheetReaderCsv;
use PhpOfficePhpSpreadsheetSharedDate;

use thinkexceptionPDOException;
use thinkCache;
use thinkConfig;
use thinkDb;

A、读取xsl的数据成数组

    //读取excel的数据为数组
public function haha()
{
    /*$file = $this->request->request('file');
    if (!$file) {
        $this->error(__('Parameter %s can not be empty', 'file'));
    }*/
    $filePath ='E:/betahost/mini.ejiegd.com/public/demo.xls';
    //$filePath = ROOT_PATH . DS . 'public' . DS . $file;
    if (!is_file($filePath)) {
        $this->error(__('No results were found'));
    }
    //实例化reader
    $ext = pathinfo($filePath, PATHINFO_EXTENSION);
    if (!in_array($ext, ['csv', 'xls', 'xlsx'])) {
        $this->error(__('Unknown data format'));
    }
    if ($ext === 'csv') {
        $file = fopen($filePath, 'r');
        $filePath = tempnam(sys_get_temp_dir(), 'import_csv');
        $fp = fopen($filePath, "w");
        $n = 0;
        while ($line = fgets($file)) {
            $line = rtrim($line, "\n\r\0");
            $encoding = mb_detect_encoding($line, ['utf-8', 'gbk', 'latin1', 'big5']);
            if ($encoding != 'utf-8') {
                $line = mb_convert_encoding($line, 'utf-8', $encoding);
            }
            if ($n == 0 || preg_match('/^".*"$/', $line)) {
                fwrite($fp, $line . "\n");
            } else {
                fwrite($fp, '"' . str_replace(['"', ','], ['""', '","'], $line) . "\"\n");
            }
            $n++;
        }
        fclose($file) || fclose($fp);

        $reader = new Csv();
    } elseif ($ext === 'xls') {
        $reader = new Xls();
    } else {
        $reader = new Xlsx();
    }

    //加载文件
    $insert = [];
    try {
        if (!$PHPExcel = $reader->load($filePath)) {
            $this->error(__('Unknown data format'));
        }
        $currentSheet = $PHPExcel->getSheet(0);  //读取文件中的第一个工作表
        $allColumn = $currentSheet->getHighestDataColumn(); //取得最大的列号
        $allRow = $currentSheet->getHighestRow(); //取得一共有多少行
        $maxColumnNumber = Coordinate::columnIndexFromString($allColumn);
        $fields = [];
        for ($currentRow = 1; $currentRow <= 1; $currentRow++) {
            for ($currentColumn = 1; $currentColumn <= $maxColumnNumber; $currentColumn++) {
                $val = $currentSheet->getCellByColumnAndRow($currentColumn, $currentRow)->getValue();
                $fields[] = $val;
            }
        }

        for ($currentRow = 2; $currentRow <= $allRow; $currentRow++) {
            $values = [];
            for ($currentColumn = 1; $currentColumn <= $maxColumnNumber; $currentColumn++) {
                //第9列为日期格式
                if($currentColumn==9){
                 $val = $currentSheet->getCellByColumnAndRow($currentColumn, $currentRow)->getValue();
                 if(!empty($val)){
                 $val_data =Date::excelToTimestamp($val);
                 $val =date('Y-m-d H:i:s',$val_data);
                 }else{
                 $val ='';
                 }
                }else{
                $val = $currentSheet->getCellByColumnAndRow($currentColumn, $currentRow)->getValue();
                }
                $values[] = is_null($val) ? '' : $val;
            }
            $row = [];
            $temp = array_combine($fields, $values);
            foreach ($temp as $k => $v) {
                    $row[$k] = $v;
            }
            if ($row) {
                $insert[] = $row;
            }
        }
        //缓存数据
        $excel_data=$insert;

        cache('excel_data',$excel_data);
        print_r($excel_data);
    } catch (Exception $exception) {
        $this->error($exception->getMessage());
    }
}

B、数据转存为xsl文件并下载

   public function out(){
            $xlsData=cache('arr');
            //实例化
            $objExcel = new \PHPExcel();
            //设置文档属性
            $objWriter = \PHPExcel_IOFactory::createWriter($objExcel, 'Excel2007');
            //设置内容
            $objActSheet = $objExcel->getActiveSheet();
            $key = ord("A");
            $letter = explode(',', "A,B,C,D,E,F,G,H,I,J");
            $arrHeader = array('券ID', '商业ID', '手机号', '券码类型', '券码编号','网点编号','网点名称','使用时间','核销状态','是否核对');
            //填充表头信息
            $lenth = count($arrHeader);
            for ($i = 0; $i < $lenth; $i++) {
                $objActSheet->setCellValue("$letter[$i]1", "$arrHeader[$i]");
            };
            //填充表格信息
            foreach ($xlsData as $k => $v) {
                $k += 2;
                //表格内容
                $objActSheet->setCellValue('A' . $k, $v['id']);
                $objActSheet->setCellValue('B' . $k, $v['businessid']);
                $objActSheet->setCellValue('C' . $k, $v['phone']);
                $objActSheet->setCellValue('D' . $k, $v['couponType']);
                $objActSheet->setCellValue('E' . $k, $v['couponNo']);
                $objActSheet->setCellValue('F' . $k, $v['storeOuCode']);
                $objActSheet->setCellValue('G' . $k, $v['storeOuName']);
                $objActSheet->setCellValue('H' . $k, $v['usedTime']);
                $objActSheet->setCellValue('I' . $k, $v['status']);
                $objActSheet->setCellValue('J' . $k, $v['is_check']);
                // 表格高度
                $objActSheet->getRowDimension($k)->setRowHeight(20);
            }

            $width = array(20, 20, 15, 10, 10, 30, 10, 15,20);
            //设置表格的宽度
            $objActSheet->getColumnDimension('A')->setWidth($width[5]);
            $objActSheet->getColumnDimension('B')->setWidth($width[1]);
            $objActSheet->getColumnDimension('C')->setWidth($width[0]);
            $objActSheet->getColumnDimension('D')->setWidth($width[5]);
            $objActSheet->getColumnDimension('E')->setWidth($width[5]);
            $objActSheet->getColumnDimension('F')->setWidth($width[5]);
            $objActSheet->getColumnDimension('G')->setWidth($width[5]);
            $objActSheet->getColumnDimension('H')->setWidth($width[5]);
            $objActSheet->getColumnDimension('I')->setWidth($width[5]);
            $objActSheet->getColumnDimension('J')->setWidth($width[5]);
            $outfile = md5("核对结果" . time()) . ".xlsx";
            ob_end_clean();
            header("Content-Type: application/force-download");
            header("Content-Type: application/octet-stream");
            header("Content-Type: application/download");
            header('Content-Disposition:inline;filename="' . $outfile . '"');
            header("Content-Transfer-Encoding: binary");
            header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
            header("Pragma: no-cache");
            $objWriter->save('php://output');

}

今天bower install前端依赖时候出现错误

Additional error details:
fatal: unable to access 'https://github.com/ivaynberg/select2.git/': OpenSSL SSL_read: Connection was reset, errno 10054

怀疑是默认开启https访问

git config --global http.sslVerify "false"

在git客户端输入即可!
3.png