微信公众号自动给头像加红旗代码


namespace app\index\controller;
use think\Db;
use think\Session;
use think\Controller;
use wechat\Wechat;
use wechat\WxJsApi;
use wechat\TPWechat;
use think\facade\Env;

class Api extends Controller
{
    private $options = array();
	
	public function initialize(){
        
		$this->options = array(
			'token'=>'', //填写你设定的key
			'encodingaeskey'=>'', //填写加密用的EncodingAESKey
			'appid'=>'', //填写高级调用功能的app id
			'appsecret'=>'', //填写高级调用功能的密钥
			'debug' => false,
		);
	}
	
    public function index(){
		
		$weObj = new TPWechat($this->options);
		$weObj->valid();
		$type = $weObj->getRev()->getRevType();
		switch($type) {
			case Wechat::MSGTYPE_TEXT:
                $this->_customReply($weObj);
                $weObj->text("您好,欢迎关注")->reply();
				break;
			case Wechat::MSGTYPE_EVENT:
				$this->handle($weObj);
                $weObj->text("您好,欢迎关注")->reply();
				break;
			default:
				$weObj->text("您好,欢迎关注")->reply();
		}
    }
    
    private function handle($weObj) {
        $rev = $weObj->getRevData();
        if($rev['Event']=='subscribe' && isset($rev['EventKey'])){
            $qrscene_id = str_replace('qrscene_','',$rev['EventKey']);
            $arr = [
                'qrscene_id' => $qrscene_id,
                'open_id' => $rev['FromUserName'],
                'type' => 1,
                'create_time'  => time(),
            ];
            $res = Db::name('qr_log')->insert($arr);
            Db::name('qr_list')->where(['qr_num'=>$qrscene_id])->update(['scan_num'=>0]);
            if($res){
                return true;
            }else{
                return false;
            }
            
        }elseif($rev['Event']=='SCAN' && isset($rev['EventKey'])){
            $qrscene_id = $rev['EventKey'];
            $arr = [
                'qrscene_id' => $qrscene_id,
                'open_id' => $rev['FromUserName'],
                'type' => 2,
                'create_time'  => time(),
            ];
            $res = Db::name('qr_log')->insert($arr);
            if($res){
                return true;
            }else{
                return false;
            }
        }
    }
    
    private function _customReply($weObj) {
		
		$text = $weObj->getRev()->getRevContent();
        if($text) {
            $text_array = [
                '给我一面小红旗吧',
                '我也想要小红旗',
                '小红旗',
                '请赐我一面小红旗吧',
                '别人都有小红旗,我也想要',
                '小红旗在哪里',
                '国旗',
                '给个小红旗',
                '我要个小红旗',
                '我想要不一样的小红旗',
                '红旗',
                '领红旗',
                '给我一面小红旗吧',
                '我想要一面小红旗。'
            ];
            $text_array1 = [
                '我想要不一样的小红旗',
                '换一个小红旗',
                '不一样的小红旗',
                '再来一个小红旗'
            ];
            if(in_array($text,$text_array) || in_array($text,$text_array1)){
                $rev = $weObj->getRevData();
                $open_id = $rev['FromUserName'];
                $user_info = $weObj->getUserInfo($open_id);
                if(substr($user_info['headimgurl'],-3)=='132'){
                    $user_info['headimgurl'] = substr($user_info['headimgurl'],0,-3).'0';
                }
                //$weObj->text('123')->reply();
                if(function_exists('fastcgi_finish_request')){
                    // 刷新buffer
                    ob_flush();
                    flush();
                    // 断开浏览器连接
                    fastcgi_finish_request();
                }
                $picname = md5(time()).$open_id;
                $picurl = 'public/guoqing/'.$picname.'.jpg';
                $url=$this->xiazai($user_info['headimgurl'],$picurl);
                $SUL=$this->scaleImg($url,$url);
                if(in_array($text,$text_array1)){
                    $img=$this->get_head_img1($SUL);
                }else{
                    $img=$this->get_head_img($SUL);
                }
                $data1 = array('media' => '@'.$img);
                $res=$weObj->uploadMedia($data1, 'image');
                if($res){
                    $data=array(
                        'touser'=>$open_id,
                        'msgtype'=>'image',
                        'image'=>array('media_id'=>$res['media_id'])
                    );
                    $weObj->sendCustomMessage($data);
                }
            }
        }
	}
    public function get_head_img1($headimgurl)
    {
        $background = imagecreatefromjpeg($headimgurl);//背景图
        $logo = imagecreatefrompng(Env::get('root_path').'public/guoqing/00'.rand(2,5).'.png');//底部logo
        imagecopyresampled($background,$logo, 0, 0, 0, 0, 640, 640, 640, 640);//底部logo
        //生成图片
        $picurl = $headimgurl;
        imagejpeg($background, $picurl,80);
        imagedestroy($background);
        imagedestroy($logo);
        return $picurl;
    }
    
    public function get_head_img($headimgurl)
    {
        $background = imagecreatefromjpeg($headimgurl);//背景图
        $logo = imagecreatefrompng(Env::get('root_path').'public/guoqing/001.png');//底部logo
        imagecopyresampled($background,$logo, 0, 0, 0, 0, 640, 640, 640, 640);//底部logo
        //生成图片
        $picurl = $headimgurl;
        imagejpeg($background, $picurl,80);
        imagedestroy($background);
        imagedestroy($logo);
        return $picurl;
    }
    public function xiazai($url, $saveFile) {
        $parse = parse_url($url);
        if (!isset($parse['host'])) {
            return false;
        }
        $file = Env::get('root_path') . $saveFile;
        $fp = fopen($file, 'wb');
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_FILE, $fp);
        curl_setopt($ch, CURLOPT_HEADER, 0);
        curl_setopt($ch, CURLOPT_HTTPHEADER, array(
            'User-Agent:Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/60.0.3100.0 Safari/537.36',
            'Host:' . $parse['host'],
        ));
        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
        curl_setopt($ch, CURLOPT_TIMEOUT, 180);
        $res = curl_exec($ch);
        curl_close($ch);
        fclose($fp);
        // 下载失败,则删除空文件
        if (filesize($file) <= 10) {
            @unlink($file);
            return false;
        }
        return $file;
    }
    public function scaleImg($picName,$savePath, $maxx = 800, $maxy = 640)
    {
        $info = getimageSize($picName);//获取图片的基本信息
        $w = $info[0];//获取宽度
        $h = $info[1];//获取高度

        if($w<=$maxx&&$h<=$maxy){
            return $picName;
        }
        //获取图片的类型并为此创建对应图片资源
        switch ($info[2]) {
            case 1://gif
                $im = imagecreatefromgif($picName);
                break;
            case 2://jpg
                $im = imagecreatefromjpeg($picName);
                break;
            case 3://png
                $im = imagecreatefrompng($picName);
                break;
            default:
                die("图像类型错误");
        }
        //计算缩放比例
        if (($maxx / $w) > ($maxy / $h)) {
            $b = $maxy / $h;
        } else {
            $b = $maxx / $w;
        }
        //计算出缩放后的尺寸
        $nw = floor($w * $b);
        $nh = floor($h * $b);
        //创建一个新的图像源(目标图像)
        $nim = imagecreatetruecolor($nw, $nh);

        //透明背景变黑处理
        //2.上色
        $color=imagecolorallocate($nim,255,255,255);
        //3.设置透明
        imagecolortransparent($nim,$color);
        imagefill($nim,0,0,$color);


        //执行等比缩放
        imagecopyresampled($nim, $im, 0, 0, 0, 0, $nw, $nh, $w, $h);
        //输出图像(根据源图像的类型,输出为对应的类型)
        switch ($info[2]) {
            case 1:
                imagegif($nim, $savePath);
                break;
            case 2:
                imagejpeg($nim, $savePath);
                break;
            case 3:
                imagepng($nim, $savePath);
                break;

        }
        //释放图片资源
        imagedestroy($im);
        imagedestroy($nim);
        //返回结果
        return $savePath;
    }

}

你可能感兴趣的:(php,微信)