关注公众号并登录

admin6个月前Laravel163
 /* * 服务端生成带唯一标识二维码并将唯一标识返回给前端 */ 
 public function wx_code()
 {
     $scene_str = $this->get_order_sn() . rand(10000, 99999);
     $result = json_decode($this->getQrcodeByStr($scene_str), true);
     $qrcode = $this->generateQrcode($result['ticket']);
     $data['qr_code_url'] = $qrcode;
     $data['scene_value'] = $scene_str;
     $this->success('ok', $data);
 }


public function user_info()
{
    $key = request()->param('key'); if (!$key) {
        $this->error('请输入Key');
    }
    $user = Db::name('user')->where(array('EventKey' => $key))->find(); if ($user) {
        $user['token'] = JWT::encode(['uid' => $user['id'], 'expired_time' => time() + 1800], self::$tokenKey);
        $user['avatar'] = request()->domain() . $user['avatar'];
        $this->success('ok', $user);
    } else {
        $this->error('登录中');
    }
}


    public function callback()
    { // 首次验证微信接口  if (request()->param('echostr')) {
            $data = request()->param();
            $token = 'khePcWQZudbbvnKBoJbZfWrHjne1'; if (empty($data['signature']) || empty($data['timestamp']) || empty($data['nonce']) || empty($data['echostr'])) { return -1;
            }
            $signature = $data['signature'];
            $timestamp = $data['timestamp'];
            $nonce = $data['nonce'];
            $echostr = $data['echostr'];
            $tmpArr = array($token, $timestamp, $nonce); sort($tmpArr, SORT_STRING);
            $tmpStr = implode($tmpArr);
            $tmpStr = sha1($tmpStr); if ($tmpStr == $signature) { return $echostr;
            } else { return -1;
            }
        }

        $wxData = file_get_contents("php://input"); //        file_put_contents('log1.txt', $wxData);  $dataje = json_encode(simplexml_load_string($wxData, 'SimpleXMLElement', LIBXML_NOCDATA)); //将返回的xml转为数组  $data = json_decode($dataje, true); //将返回的xml转为数组   switch ($data['MsgType']) { case 'event': // 事件处理  $this->handleEvent($data); break; case 'text'://文本消息   break; case 'image'://图片消息   break; case 'voice'://语音消息   break; case 'video'://视频消息   break; case 'shortvideo'://短视频消息   break; case 'location'://位置消息   break; case 'link'://链接消息   break;
        }
    }
public function handleEvent($val)
    {
        $user = Db::name('user')->where(array('openid' => $val['FromUserName'], 'status' => 'normal'))->find(); if ($user) { //            $data['nickname'] = $user['nickname']; //            $data['mobile'] = $user['mobile']; //            $data['avatar'] = $user['avatar']; //            $data['vip'] = $user['vip']; //            $data['token'] = JWT::encode(['uid' => $user['id'], 'expired_time' => time() + 1800], self::$tokenKey);  Db::startTrans(); try {
                $val['EventKey'] = str_replace('qrscene_', '', $val['EventKey']); Db::name('user')->where(array('id' => $user['id']))->update(['EventKey' => $val['EventKey']]); Db::commit();
                $fromUserName = $val['ToUserName'];
                $toUserName = $val['FromUserName'];
                $replyMsg = "<xml>  <ToUserName><![CDATA[" . $toUserName . "]]></ToUserName>  <FromUserName><![CDATA[" . $fromUserName . "]]></FromUserName>  <CreateTime>" . time() . "</CreateTime>  <MsgType><![CDATA[text]]></MsgType>  <Content><![CDATA[登录成功]]></Content>  </xml>"; echo $replyMsg; exit;
            } catch (Exception $e) {
                $this->error('登录失败'); Db::rollback();
            }
        } else {
            $ip = request()->ip();
            $time = time();
            $val['EventKey'] = str_replace('qrscene_', '', $val['EventKey']);
            $data = [ 'openid' => $val['FromUserName'], 'nickname' => '用戶' . rand(10000, 99999), 'avatar' => '/avatar.jpg', 'salt' => Random::alnum(), 'jointime' => $time, 'joinip' => $ip, 'logintime' => $time, 'loginip' => $ip, 'prevtime' => $time, 'status' => 'normal', 'level' => 0, 'gender' => 0, 'gem' => 0, 'diamond' => 0, 'real_diamond' => 0, 'vip' => 0, 'EventKey' => $val['EventKey'],
            ]; Db::startTrans(); try {
                $msg = Db::name('user')->insertGetId($data); //                $data['token'] = JWT::encode(['uid' => $msg, 'expired_time' => time() + 1800], self::$tokenKey);  Db::commit();
                $fromUserName = $val['ToUserName'];
                $toUserName = $val['FromUserName'];
                $replyMsg = "<xml>  <ToUserName><![CDATA[" . $toUserName . "]]></ToUserName>  <FromUserName><![CDATA[" . $fromUserName . "]]></FromUserName>  <CreateTime>" . time() . "</CreateTime>  <MsgType><![CDATA[text]]></MsgType>  <Content><![CDATA[登录成功]]></Content>  </xml>"; echo $replyMsg; exit;
            } catch (Exception $e) {
                $this->error('登录失败'); Db::rollback();
            }
        }
    }
     /***  * 通过openId获取用户信息  * @openId  * @return  **/  public function getUserInfo($openId)
    {
        $url = "https://api.weixin.qq.com/cgi-bin/user/info?access_token=" . $this->accessToken() . "&openid=" . $openId . "&lang=zh_CN";
        $data = $this->httpRequest($url); return $data;
    } public function getQrcodeByStr($scene_str)
    {
        $url = "https://api.weixin.qq.com/cgi-bin/qrcode/create?access_token=" . $this->accessToken();
        $data = array( "expire_seconds" => 3600, //二维码的有效时间(1小时)  "action_name" => "QR_STR_SCENE", "action_info" => array("scene" => array("scene_str" => $scene_str))
        );
        $result = $this->httpRequest($url, json_encode($data)); return $result;
    } /**  * 换取二维码  * @ticket  * @return  */  public function generateQrcode($ticket)
    { return "https://mp.weixin.qq.com/cgi-bin/showqrcode?ticket=" . $ticket;
    } public function accessToken()
    {
        $this->path = __DIR__ . '/'; // access_token 应该全局存储与更新,以下代码以写入到文件中做示例  $msg = json_decode($this->get_php_file($this->path . "access_token.php")); if ($msg->expire_time < time()) {
            $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" . $this->appid . "&secret=" . $this->secret;
            $res = json_decode($this->httpRequest($url), true);
            $access_token = $res['access_token']; if ($access_token) {
                $msg->expire_time = time() + 7000;
                $msg->access_token = $access_token;
                $this->set_php_file($this->path . "access_token.php", json_encode($msg));
            }
        } else {
            $access_token = $msg->access_token;
        } return $access_token;
    } private function httpRequest($url, $data = "")
    {
        $curl = curl_init(); curl_setopt($curl, CURLOPT_URL, $url); curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE); curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE); if (!empty($data)) { //判断是否为POST请求  curl_setopt($curl, CURLOPT_POST, 1); curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
        } curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        $output = curl_exec($curl); curl_close($curl); return $output;
    } public function get_php_file($filename)
    { return trim(substr(file_get_contents($filename), 15));
    } public function set_php_file($filename, $content)
    {
        $fp = fopen($filename, "w"); fwrite($fp, "<?php exit();?>" . $content); fclose($fp);
    }



                                            

相关文章

base64 处理图片

public function images(){    $image = request()->input('image');    i...

PHP 严格类型

只需在 PHP 代码文件的开头加上declare(strict_types = 1);这一行魔法代码,就能开启严格类型检查之旅。...

抖音小程序码

public function dyqrcode($uid){    $url = "https://open.douyin.com/api/apps/v1/qrcode...

excel 导出

header("Content-Type: application/vnd.ms-excel; name='excel'"); header("Content-Disposition:atta...

微信支付V2

   public static function unifiedorder($openid, $out_trade_no, $total_fee, $notify)...

抖音小程序登录

$code = request()->input('code');$nickname = request()->input('nickName');$ava...