tp5 微信授权

<?php
/**
 * Created by PhpStorm.
 * User: COLORFUL
 * Date: 2019/6/27
 * Time: 14:24
 */
namespace app\api\controller;
use app\admin\model\apps\Apps;
use Complex\Exception;
use think\Cache;
use think\Controller;
use think\Db;

class Wxcontroller extends Controller
{
    public function wxlogin(){

        $hash      = $this->request->header('hash');
        if (empty($hash)) {
            return json(['status' => -2000, 'message' => '缺少hash参数'])->send();
        }
        $get =$this->request->post();
        Vendor("wechat.wxbiz.wxBizDataCrypt");
        $config=Apps::where('hash', $hash)->find();
        $param['appid'] = $config['appid'];    //小程序id
        $param['secret'] = $config['appsecret'];    //小程序密钥
        $param['js_code'] = $this->define_str_replace($get['code']);
        $param['grant_type'] = 'authorization_code';
        $http_key = $this->httpCurl('https://api.weixin.qq.com/sns/jscode2session', $param, 'GET');
        $session_key = json_decode($http_key,true);
        if (!empty($session_key['session_key'])){
            Vendor("wechat.wxbiz.wxBizDataCrypt");
            $pc      = new \WXBizDataCrypt( $param['appid'], $session_key['session_key']);
                $errCode = $pc->decryptData($get['encryptedData'], $get['iv'], $data);
            if ($errCode == 0) {
                $arr = json_decode($data, true);
                $nickname = $arr['nickName'];
                $headimg = $arr['avatarUrl'];
                $gender = $arr['gender'];
                $data=[
                    'nickname'=>$nickname,
                    'avatar'=>$headimg,
                    'gender'=>$gender,
                    'address'=>$arr['province'].$arr['city']
                ];

            }else{
                return json_code(-200,'请求失败');
            }
            $data['openid'] = $session_key['openid'];
            //$data['app_id']=$config['id'];
            $data['createtime'] = time();
            $user=new \app\common\model\User();
            if (false == $user->where(['openid' => $data['openid']])->find()) {
              
                $users=$user->insertGetId($data);
            }else{
                $value = $user->where(['openid' => $data['openid']])->field('id,nickname,status')->find();
                $users=$value['id'];
               
            }

            session('home.uid',$users);

            return json_code(200,'授权成功',['sessionId'=>session_id(),'sessionKey'=>$session_key['session_key']]);
        }else{
            return json_code(-200,'授权失败');
        }
    }
   # 静默授权用户微信授权
    public function logins(){
        $hash      = $this->request->header('hash');
        if (empty($hash)) {
            return json(['status' => -2000, 'message' => '缺少hash参数'])->send();
        }
        $get =$this->request->post();
        Vendor("wechat.wxbiz.wxBizDataCrypt");
        $config=Apps::where('hash', $hash)->find();
        $param['appid'] = $config['appid'];    //小程序id
        $param['secret'] = $config['appsecret'];    //小程序密钥
        $param['js_code'] = $this->define_str_replace($get['code']);
        $param['grant_type'] = 'authorization_code';
        $http_key = $this->httpCurl('https://api.weixin.qq.com/sns/jscode2session', $param, 'GET');
        $session_key = json_decode($http_key,true);
        if (!empty($session_key['session_key'])){
            $data['openid'] = $session_key['openid'];
            $data['updatetime']=time();
            $res=\app\api\model\User::where(['id'=>$get['user_id']])->update($data);
            if($res)return json_code(200,'授权成功');
            return json_code(-200,'授权失败');

        }else{
            return json_code(-200,'授权失败');
        }
    }
  public  function httpCurl($url, $params, $method = 'POST', $header = array(), $multi = false)
    {
        date_default_timezone_set('PRC');
        $opts = array(
            CURLOPT_TIMEOUT => 30,
            CURLOPT_RETURNTRANSFER => 1,
            CURLOPT_SSL_VERIFYPEER => false,
            CURLOPT_SSL_VERIFYHOST => false,
            CURLOPT_HTTPHEADER => $header,
            CURLOPT_COOKIESESSION => true,
            CURLOPT_FOLLOWLOCATION => 1,
            CURLOPT_COOKIE => session_name() . '=' . session_id(),
        );
        /* 根据请求类型设置特定参数 */
        switch (strtoupper($method)) {
            case 'GET':
                // 链接后拼接参数  &  非?
                $opts[CURLOPT_URL] = $url . '?' . http_build_query($params);
                break;
            case 'POST':
                //判断是否传输文件
                $params = $multi ? $params : http_build_query($params);
                $opts[CURLOPT_URL] = $url;
                $opts[CURLOPT_POST] = 1;
                $opts[CURLOPT_POSTFIELDS] = $params;
                break;
            default:
                throw new Exception('不支持的请求方式!');
        }
        /* 初始化并执行curl请求 */
        $ch = curl_init();
        curl_setopt_array($ch, $opts);
        $data = curl_exec($ch);
        $error = curl_error($ch);
        curl_close($ch);
        if ($error) throw new Exception('请求发生错误:' . $error);
        return $data;
    }

   public function decryptData($appid, $sessionKey, $encryptedData, $iv)
    {
        $OK = 0;
        $IllegalAesKey = -41001;
        $IllegalIv = -41002;
        $IllegalBuffer = -41003;
        $DecodeBase64Error = -41004;

        if (strlen($sessionKey) != 24) {
            return $IllegalAesKey;
        }
        $aesKey = base64_decode($sessionKey);

        if (strlen($iv) != 24) {
            return $IllegalIv;
        }
        $aesIV = base64_decode($iv);

        $aesCipher = base64_decode($encryptedData);

        $result = openssl_decrypt($aesCipher, "AES-128-CBC", $aesKey, 1, $aesIV);
        $dataObj = json_decode($result);
        if ($dataObj == NULL) {
            return $IllegalBuffer;
        }
        if ($dataObj->watermark->appid != $appid) {
            return $DecodeBase64Error;
        }
        $data = json_decode($result, true);

        return $data;
    }
   public function define_str_replace($data)
    {
        return str_replace(' ','+',$data);
    }


}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值