OpenServerController.php 7.4 KB
<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2019/1/19
 * Time: 11:32
 */

namespace app\portal\controller;


use cmf\controller\HomeBaseController;
use cmf\controller\WeChatBaseController;
use EasyWeChat\Foundation\Application;
use think\Db;

class OpenServerController extends HomeBaseController
{
    public function index(){
        if(!isset($_GET["echostr"])){
            $this->responseMsg();
        }else{
            $this->valid();
        }
    }

    public function valid()
    {
        $echoStr = $_GET["echostr"];
        echo $echoStr;
        exit;
    }
    public function test(){
//        dump(cache('referrer'));
        dump(cache('openid'));
        dump(cache('ccc'));
        dump(cache('admin_id'));
        dump(cache('user_data'));
        exit();
        dump(cache('result'));
        dump(cache('result1'));
        dump(cache('third_party_user'));
        dump(cache('user'));
    }
    public function responseMsg()
    {
        $conf = config('wechat_config');
        $app=new Application($conf);
        $server = $app->server;

        $server->setMessageHandler(function ($message) {
            switch ($message->MsgType) {
                case 'event':
                    switch ($message->Event) {
                        case 'subscribe':
                            if(empty($message->EventKey)){
                                return '您好,欢迎关注“学考无忧”公众号。
我们致力于打造一个为广大家长和同学们提升知识视野,提高学习成绩的优质服务号,这里有热门的教育资讯,海量的免费资源,优质的学习干货,会为大家提供教辅类以及课外阅读阅读书籍,帮助同学们提高学习成绩。
真正让家长省心,孩子无忧。感谢关注。';
                            }else{
                                //获取用户openid
                                $openid=$message->FromUserName;
                                cache('openid',$openid);
                                $param=substr($message->EventKey,8);
                                $data = explode("-",$param);
                                $my_user_id = $data[0];
                                $status = $data[1];
                                $third_party_user = Db::name('third_party_user')->where('openid',$openid)->find();
                                if(!$third_party_user){
                                    //获取用户信息
                                    $options=config('wechat_config');
                                    $app = new Application($options);
                                    $accessToken = $app->access_token; // EasyWeChat\Core\AccessToken 实例
                                    $token = $accessToken->getToken(false);
                                    $url = "https://api.weixin.qq.com/cgi-bin/user/info?access_token=$token&openid=$openid&lang=zh_CN";
                                    $user_data = json_decode($this->http_get($url),true);
                                    $user_id = $this->new_user($user_data,$openid,$options['app_id']);

                                }
//                                cache('third_party_user',$third_party_user);
//                                if(!empty($third_party_user)){
//                                    $user = Db::name('user')->where('id',$third_party_user['user_id'])->find();
//                                    cache('user',$user);
//                                    if($user['channel'] == 2){
//                                        $result1 = Db::name('user')->where('id',$user['id'])->update(['admin_id'=>$admin_id,'channel'=>1]);
//                                        cache('result1',$result1);
//                                    }
//                                }else{
//                                    //储存到推荐人推荐列表
//                                    $referrer = Db::name('referrer')->where(array('openid'=>$openid))->find();
//                                    cache('referrer',$referrer);
//                                    if(empty($referrer)){
//                                        $result = Db::name('referrer')->insert(array('admin_id'=>$admin_id,'openid'=>$openid,'create_time'=>time()));
//                                        cache('result',$result);
////                                return "推荐人关注!";
//                                    }else{
////                                return "已有推荐人!";
//                                    }
//                                }
                            }
                            break;

                        default:
//                            return '收到event消息';
                            break;
                    }
                    break;
                case 'text':
                    return '您好,欢迎关注“学考无忧”公众号。
我们致力于打造一个为广大家长和同学们提升知识视野,提高学习成绩的优质服务号,这里有热门的教育资讯,海量的免费资源,优质的学习干货,会为大家提供教辅类以及课外阅读阅读书籍,帮助同学们提高学习成绩。
真正让家长省心,孩子无忧。感谢关注。';
                    break;
                default:
//                    return '收到其它消息';
                    break;
            }
        });

        $response = $server->serve();

        $response->send();
    }

    private function check_signature()
    {
        $signature = $_GET["signature"];
        $timestamp = $_GET["timestamp"];
        $nonce = $_GET["nonce"];

        $token = TOKEN;
        $tmpArr = array($token, $timestamp, $nonce);
        sort($tmpArr);
        $tmpStr = implode( $tmpArr );
        $tmpStr = sha1( $tmpStr );

        if( $tmpStr == $signature ){
            return true;
        }else{
            return false;
        }
    }

    public function http_get($url){
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL,$url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER,true);
        $result = curl_exec($ch);
        // grab URL, and print
        if(curl_errno($ch)){
            print curl_error($ch);
        }
        curl_close($ch);
        return $result;
    }

    public function new_user($wechat_user,$openid,$appId) {
        $currentTime = time();
        $ip          = $this->request->ip(0, true);
        $userId = Db::name("user")->insertGetId([
            'create_time'     => $currentTime,
            'user_status'     => 1,
            'user_type'       => 2,
            'sex'             => $wechat_user['original']['sex'],
            'user_nickname'   => $wechat_user['nickname'],
            'avatar'          => $wechat_user['avatar'],
            'last_login_ip'   => $ip,
            'last_login_time' => $currentTime,
        ]);

        $row=Db::name("third_party_user")->insert([
            'openid'          => $openid,
            'user_id'         => $userId,
            'third_party'     => 'public',
            'nickname'        => $wechat_user['nickname'],
            'app_id'          => $appId,
            'last_login_ip'   => $ip,
            'union_id'        => '',
            'last_login_time' => $currentTime,
            'create_time'     => $currentTime,
            'login_times'     => 1,
            'status'          => 1,
            'more'            => json_encode($wechat_user)
        ]);
        return $userId;
    }
}