laravel 公众号开发自动回复记录

<?php

namespace App\Http\Controllers\Admin\Official;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\DB;

define('TOKEN', 'yunlive11');

class WxresponseMsg extends Controller
{
	protected $appid = 'wxecbfea5580fb894c';
    protected $secret = 'daabe60820d93278cd1988e796b16fa5a';

    /**
     * 自定义方法,用于微信访问验证开发者身份
     *
     * @param Request $request
     * @return array|null|string
     */
    public function wxtoken(Request $request)
    {
            // 验证消息来自微信服务器
        if($request->method()=='GET'){
	        $signature = $request->input('signature');
	        $timestamp = $request->input('timestamp');
	        $nonce = $request->input('nonce');
	        $echoStr = $request->input('echostr');
	        if ($this->checkSignature($signature, $timestamp, $nonce)) {
	        	ob_end_clean(); //必须清空缓冲区
	            return $echoStr;
	        } else {
	            return 'Token verification failed.';
	        }
        } elseif ($request->method()=='POST') {
            // 事件处理    关注/取消事件等
	        $postStr = isset($GLOBALS['HTTP_RAW_POST_DATA']) ? $GLOBALS['HTTP_RAW_POST_DATA'] : file_get_contents("php://input");
	        if (!empty($postStr)) {
	            $postObj = simplexml_load_string($postStr);
	            // 微信消息类型
	            $RX_TYPE = trim($postObj->MsgType);
	            switch ($RX_TYPE) {
	                case "text":
	                    // 文本消息
	                    $resultStr = $this->handleText($postObj);
	                    break;
	                case "event":
	                    // 事件推送
	                    $resultStr = $this->handleEvent($postObj);
	                    break;
	                default:
	                    $resultStr = "Unknow msg type: " . $RX_TYPE;
	                    break;
	            }
	            echo $resultStr;
	        } else {
	            echo "";
	            exit;
	        }

        }
    }

        /**
     * 微信文本消息
     * @param $postObj
     */
    public function handleText($postObj)
    {
        $fromUsername = $postObj->FromUserName;
        $toUsername = $postObj->ToUserName;
        $keyword = trim($postObj->Content);
        $time = time();
        $textTpl = "<xml>
                    <ToUserName><![CDATA[%s]]></ToUserName>
                    <FromUserName><![CDATA[%s]]></FromUserName>
                    <CreateTime>%s</CreateTime>
                    <MsgType><![CDATA[%s]]></MsgType>
                    <Content><![CDATA[%s]]></Content>
                    <FuncFlag>0</FuncFlag>
                    </xml>";
        if (!empty($keyword)) {
            $msgType = "text";
            $contentStr = "欢迎您关注".json_encode($object);
            $resultStr = sprintf($textTpl, $fromUsername, $toUsername, $time, $msgType, $contentStr);
            echo $resultStr;
        } else {
            echo "lalala";
        }
    }

        /**
     * 获取时间消息并解析相应参数
     * 提供数据简单推送(自动回复)
     * @param $object
     *
     * @return string
     */
    public function handleEvent($object)
    {
        $contentStr = "";
        	file_put_contents(ROOT_PATH.'acart111.txt', $object->Event, FILE_APPEND);
		$EventKey = explode('_', $object->EventKey); //事件KEY值,qrscene_为前缀,后面为二维码的参数值
		$Ticket   = $object->Ticket;   //二维码的ticket
        switch ($object->Event) {
            case "subscribe":
            	// 关注
			     if(!empty($EventKey[0]) || !empty($Ticket)){
			         // 扫描带参数二维码,未关注推送

					$toUser = $object->ToUserName;
					$foUser = (string)$object->FromUserName;   // 用户openid
					$msgType = 'news';
					$createTime = time();
					$content = '扫描带参数二维码,未关注推送'.$EventKey[0].'++'.$Ticket.'++'.$EventKey[1].'++'.$EventKey[2];
					// $temp = "<xml>
					// 	<ToUserName><![CDATA[%s]]></ToUserName>
					// 	<FromUserName><![CDATA[%s]]></FromUserName>
					// 	<CreateTime>%s</CreateTime>
					// 	<MsgType><![CDATA[%s]]></MsgType>
					// 	<Content><![CDATA[%s]]></Content>
					// 	</xml>";
			         $array = array(
			              array(
			                "title"=>"XXX",
			                "description"=>"XXXXXXX",
			                "picUrl"=>"https://s.yun-live.com/images/20200707/fc3bdd153e6136c058b0214fe8ab05d3.jpg",
			                "url"=>"httpsXXX.com/",
			              ),
			               array(
			                "title"=>"XXX",
			                "description"=>"XXXXXXX",
			                "picUrl"=>"https://s.yun-live.com/images/20200707/fc3bdd153e6136c058b0214fe8ab05d3.jpg",
			                "url"=>"httpsXXX.com/",
			              ),
			                array(
			                "title"=>"XXX",
			                "description"=>"XXXXXXX",
			                "picUrl"=>"https://s.yun-live.com/images/20200707/fc3bdd153e6136c058b0214fe8ab05d3.jpg",
			                "url"=>"httpsXXX.com/",
			              ),
			                 array(
			                "title"=>"XXX",
			                "description"=>"XXXXXXX",
			                "picUrl"=>"https://s.yun-live.com/images/20200707/fc3bdd153e6136c058b0214fe8ab05d3.jpg",
			                "url"=>"httpsXXX.com/",
			              ),
			                  array(
			                "title"=>"XXX",
			                "description"=>"XXXXXXX",
			                "picUrl"=>"https://s.yun-live.com/images/20200707/fc3bdd153e6136c058b0214fe8ab05d3.jpg",
			                "url"=>"httpsXXX.com/",
			              ),
			                   array(
			                "title"=>"XXX",
			                "description"=>"XXXXXXX",
			                "picUrl"=>"https://s.yun-live.com/images/20200707/fc3bdd153e6136c058b0214fe8ab05d3.jpg",
			                "url"=>"httpsXXX.com/",
			              ),
			                    array(
			                "title"=>"XXX",
			                "description"=>"XXXXXXX",
			                "picUrl"=>"https://s.yun-live.com/images/20200707/fc3bdd153e6136c058b0214fe8ab05d3.jpg",
			                "url"=>"httpsXXX.com/",
			              ),
			                     array(
			                "title"=>"XXX",
			                "description"=>"XXXXXXX",
			                "picUrl"=>"https://s.yun-live.com/images/20200707/fc3bdd153e6136c058b0214fe8ab05d3.jpg",
			                "url"=>"httpsXXX.com/",
			              ),
			          );

			          $template  =  "<xml>
			                        <ToUserName><![CDATA[%s]]></ToUserName>
			                        <FromUserName><![CDATA[%s]]></FromUserName>
			                        <CreateTime>%s</CreateTime>
			                        <MsgType><![CDATA[%s]]></MsgType>
			                        <ArticleCount>".count($array)."</ArticleCount>
			                        <Articles>";

			          foreach ($array as $key => $v) {
			              $template  .= "<item>
			                            <Title><![CDATA[".$v['title']."]]></Title>
			                            <Description><![CDATA[".$v['description']."]]></Description>
			                            <PicUrl><![CDATA[".$v['picUrl']."]]></PicUrl>
			                            <Url><![CDATA[".$v['url']."]]></Url>
			                            </item>";
			          }


			          $template.= "</Articles></xml>";

	                $temp = sprintf($template,$foUser,$toUser,$createTime,$msgType,$content);
	                echo $temp;
			     }else{
			         // 普通关注

					$toUser = $object->ToUserName;
					$foUser = (string)$object->FromUserName;   // 用户openid
					$msgType = 'text';
					$createTime = time();
					$content = '欢迎关注我的微信公众平台111'.$EventKey[0].'++'.$Ticket.'++'.$EventKey[1].'++'.$EventKey[2].json_encode($object);;
					$temp = "<xml>
						<ToUserName><![CDATA[%s]]></ToUserName>
						<FromUserName><![CDATA[%s]]></FromUserName>
						<CreateTime>%s</CreateTime>
						<MsgType><![CDATA[%s]]></MsgType>
						<Content><![CDATA[%s]]></Content>
						</xml>";
	                $temp = sprintf($temp,$foUser,$toUser,$createTime,$msgType,$content);
	                echo $temp;
			     }

                break;
            case "SCAN":
                // $contentStr = "您已关注过,谢谢!".$EventKey.'++'.$Ticket;
                // $openid = (string)$object->FromUserName; //数据类型转换为字符串,mmp这个问题找了好久
                // $refer_id = explode('_', $object->EventKey); //$object->EventKey返回的是qrsence_123这种类型
                // $this->createuserinfo($openid, $refer_id[0]);//获取用户信息
                $toUser = $object->ToUserName;
				$foUser = $object->FromUserName;   // 用户openid
				$msgType = 'text';
				$createTime = time();
				$content = '您已关注过,谢谢!'.json_encode($object);
				$temp = "<xml>
					<ToUserName><![CDATA[%s]]></ToUserName>
					<FromUserName><![CDATA[%s]]></FromUserName>
					<CreateTime>%s</CreateTime>
					<MsgType><![CDATA[%s]]></MsgType>
					<Content><![CDATA[%s]]></Content>
					</xml>";
                $temp = sprintf($temp,$foUser,$toUser,$createTime,$msgType,$content);
                echo $temp;
                break;
            case "unsubscribe": //取消订阅
                // $contentStr = "您已关注过,谢谢!".json_encode($object);
                // $openid = (string)$object->FromUserName; //数据类型转换为字符串,mmp这个问题找了好久
                // $refer_id = explode('_', $object->EventKey); //$object->EventKey返回的是qrsence_123这种类型
                // $this->createuserinfo($openid, $refer_id[0]);//获取用户信息
                $toUser = $object->ToUserName;
				$foUser = $object->FromUserName;   // 用户openid
				$msgType = 'text';
				$createTime = time();
				$content = '您已关注过,谢谢!'.json_encode($object);
				$temp = "<xml>
					<ToUserName><![CDATA[%s]]></ToUserName>
					<FromUserName><![CDATA[%s]]></FromUserName>
					<CreateTime>%s</CreateTime>
					<MsgType><![CDATA[%s]]></MsgType>
					<Content><![CDATA[%s]]></Content>
					</xml>";
                $temp = sprintf($temp,$foUser,$toUser,$createTime,$msgType,$content);
                echo $temp;
                break;
        }
        $resultStr = $this->responseText($object, $contentStr);
        return $resultStr;
    }

     /**
     * 消息回复模板
     * @param     $object
     * @param     $content
     * @param int $flag
     *
     * @return string
     */
    public function responseText($object, $content, $flag = 0)
    {
        $textTpl = "<xml>
                    <ToUserName><![CDATA[%s]]></ToUserName>
                    <FromUserName><![CDATA[%s]]></FromUserName>
                    <CreateTime>%s</CreateTime>
                    <MsgType><![CDATA[text]]></MsgType>
                    <Content><![CDATA[%s]]></Content>
                    <FuncFlag>%d</FuncFlag>
                    </xml>";
        $resultStr = sprintf($textTpl, $object->FromUserName, $object->ToUserName, time(), $content, $flag);
        return $resultStr;
    }

    /**
     * 微信官方提供的验签方法
     *
     * @param $signature
     * @param $timestamp
     * @param $nonce
     * @return bool
     */
    private function checkSignature($signature, $timestamp, $nonce)
    {
        $token = TOKEN;
        $tmpArr = array($token, $timestamp, $nonce);
        sort($tmpArr, SORT_STRING);
        $tmpStr = implode($tmpArr);
        $tmpStr = sha1($tmpStr);
 
        if ($tmpStr == $signature) {
            return true;
        } else {
            return false;
        }
    }

	 

   /**
     * 获取用户详细信息
     * @param $openid
     * @param $refer_id
     */
    public function createuserinfo($openid, $refer_id)
    {
        $url = "https://api.weixin.qq.com/cgi-bin/user/info?access_token=" . $this->getToken($this->appid, $this->secrect) . "&openid=" . $openid;
        $user = request_get($url);
        $user = json_decode($user, true);
        $users = array(
            'openid' => $openid,
            'nickname' => $user['nickname'],
            'avatar' => $user['headimgurl'],
            'sex' => $user['sex'],
            'unionid' => $user['unionid'],
            'status' => 1,
            'reg_time' => $user['subscribe_time'],//关注公众号的时间
            'bind_user' => $refer_id
        );
        $user_str = date('Y-m-d H:i:s') . "\t";
        foreach ($users as $key => $value) {
            $user_str .= $key . '=' . $value . "\t";
        }
        $user_str .= "\n";
        file_put_contents(LOG_PATH . "wx.log", $user_str, FILE_APPEND);
    }



    public function getdump($postStr)
    {
  
    	file_put_contents(ROOT_PATH.'acart.txt', $postStr, FILE_APPEND);

    	$user_str = date('Y-m-d H:i:s') . "\t";
        foreach ($users as $key => $value) {
            $user_str .= $key . '=' . $value . "\t";
        }
        $user_str .= "\n";
        file_put_contents(LOG_PATH . "wx.log", $user_str, FILE_APPEND);

    }


 //获取公众号access_token
    public function access_token(){
		$appid =$this->appid;
        $secret =$this->secret;
        $sta=Db::table('xcx_access_token')->where('id',2)->first();

        if(!empty($sta)){
            $ts=time()-$sta->time;
          
            if($ts>7200){

                // var_dump('超时,则重新请求',$ts);
                //如果超时,则重新请求
	            $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=".$appid."&secret=".$secret;
	         	$arr = json_decode($this->curlGet($url), true);
	         	if($arr['errcode']==40164){
	         		return '不在白名单提示中'.$arr['errmsg'];
	         	}
                $access_token=$arr['access_token'];
                $arrayName = array('access_token' =>$access_token ,'time'=>time());
                Db::table('xcx_access_token')->where('id',2)->update($arrayName);
         
            }else{

                $access_token=$sta->access_token;
                $URL = "https://api.weixin.qq.com/cgi-bin/getcallbackip?access_token=".$access_token;
                $apiData=file_get_contents($URL);
                $arr =json_decode($apiData,true);
               	if($arr['errcode']==40164){
	         		return '不在白名单提示中'.$arr['errmsg'];
	         	}
	         
                // 错误重新请求
                if(empty($arr['ip_list'])){
                		
                    // 无效重新请求
			            $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=".$appid."&secret=".$secret;
			         	$result  = json_decode($this->curlGet($url), true);
			         	if($result['errcode']==40164){
			         		return '不在白名单提示中'.$result['errmsg'];
			         	}
                        $access_token=$result ['access_token'];
                        $arrayName = array('access_token' =>$access_token ,'time'=>time());
                        Db::table('xcx_access_token')->where('id',2)->update($arrayName);
                }
            }
        }else{ //空重新获取
            //否则,输出保存的token值
            // 获取access_token

            $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=".$appid."&secret=".$secret;
         	$arr = json_decode($this->curlGet($url), true);
 	        if($arr['errcode']==40164){
 	        	var_dump($arr);exit;
         		return '不在白名单提示中'.$arr['errmsg'];
         	}         	
            $access_token=$arr['access_token'];
            $arrayName = array('access_token' =>$access_token ,'time'=>time());
            Db::table('xcx_access_token')->insert($arrayName);
            // echo $apiData;exit;
        }
        return $access_token;
    }

    protected function http_post_data($url, $data_string) {
 
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
        curl_setopt($ch, CURLOPT_HTTPHEADER, array(
                'Content-Type: application/json; charset=utf-8',
                'Content-Length: ' . strlen($data_string))
        );
        ob_start();
        curl_exec($ch);
        if (curl_errno($ch)) {
            $this->ErrorLogger('curl falied. Error Info: '.curl_error($ch));
        }
        $return_content = ob_get_contents();
        ob_end_clean();
        $return_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        return array($return_code, $return_content);
    }

    public function curlGet($url)
    {
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($curl, CURLOPT_TIMEOUT, 500);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
        curl_setopt($curl, CURLOPT_URL, $url);
        $res = curl_exec($curl);
        curl_close($curl);
        return $res;

    }

    public function httpPost($url, $data)
    {
        $ch = curl_init();
        if (class_exists('\CURLFile')) {
            curl_setopt($ch, CURLOPT_SAFE_UPLOAD, true);
            $data = array('media' => new \CURLFile($data));//>=5.5
        } else {
            if (defined('CURLOPT_SAFE_UPLOAD')) {
                curl_setopt($ch, CURLOPT_SAFE_UPLOAD, false);
            }
            $data = array('media' => '@' . realpath($data));//<=5.5
        }
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_USERAGENT, "TEST");
        $result = curl_exec($ch);
        curl_close($ch);
        return $result;
    }

        //https请求(支持GET和POST)
 	public	function https_post($url, $post_data = null)
        {
            $ch = curl_init();
            curl_setopt($ch, CURLOPT_URL, $url);
            curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
            curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
            // post数据
            curl_setopt($ch, CURLOPT_POST, 1);
            // post的变量
            curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);
            $output = curl_exec($ch);
            curl_close($ch);
            return $output;
        }


}
<?php

namespace App\Http\Controllers\Admin\Official;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\DB;




class OfficialController extends Controller
{
	protected $appid = 'wxecbfea5580fb894c';
    protected $secret = 'daabe60820d93278cd1988e796b16fa5a';

    // protected $appid = 'wxffbc0e6245dcd42b';
    // protected $secret = '998e91fa7fe9f5e43257ce2cb3d91cdf';

	// 新增永久素材
	public function official_add()
	{
		$accesstoken = $this->access_token();
		$img=file_get_contents("https://s.yun-live.com/images/20200703/5ddaee820294c320e2ed471815a200d3.jpg");

		$url = "https://api.weixin.qq.com/cgi-bin/material/add_material?access_token={$accesstoken}&type=image";
		// 创建存储图片
        $dir ="/official_img/";

        !file_exists(".".$dir) && mkdir(".".$dir, 0777, true);

        $fileName = time().rand(10000,999999);

        // // 将二维码写入图片
        file_put_contents("." .$dir.$fileName . ".jpg", $img);
        $filename = realpath('official_img/'.$fileName.".jpg");
        // 传入公众号 新增永久图片
        $result = $this->httpPost($url, $filename);

        unlink($filename); //删除服务器的图片
        $std=json_decode($result);

        if(empty($std->media_id)){
        	echo "图片上传失败,无法获取图片id";exit;
        }
             // echo "<pre>";
        var_dump($std->media_id);
        //新增永久图文素材
        $url = "https://api.weixin.qq.com/cgi-bin/material/add_news?access_token=$accesstoken";
        $arr = array();
			$arr["title"] = "这是个测试ffffff2";
			$arr["thumb_media_id"] ="lyNi35Z9oAwi9iLfxN3-RkRVZmbYbd5Fsdybrz6NWKY";
			$arr["author"] = 'jh';
			$arr["digest"] =  'bbb';
			$arr["show_cover_pic"] = 1;
			$arr["content"] = "<p>22222222222222";
			$arr["content_source_url"] =  "https://blog.csdn.net/weixin_35746281/article/details/79178442";

		$arr1 = array();
			$arr1["title"] = "这是个测试ffffff2";
			$arr1["thumb_media_id"] ="lyNi35Z9oAwi9iLfxN3-RkRVZmbYbd5Fsdybrz6NWKY";
			$arr1["author"] = 'jh';
			$arr1["digest"] =  'bbb';
			$arr1["show_cover_pic"] = 1;
			$arr1["content"] = "<p>22222222222222";
			$arr1["content_source_url"] =  "https://blog.csdn.net/weixin_35746281/article/details/79178442";
		$arr2 = array();
			$arr2["title"] = "这是个测试ffffff2";
			$arr2["thumb_media_id"] ="lyNi35Z9oAwi9iLfxN3-RkRVZmbYbd5Fsdybrz6NWKY";
			$arr2["author"] = 'jh';
			$arr2["digest"] =  'bbb';
			$arr2["show_cover_pic"] = 1;
			$arr2["content"] = "<p>22222222222222";
			$arr2["content_source_url"] =  "https://blog.csdn.net/weixin_35746281/article/details/79178442";
		$arr3 = array();
			$arr3["title"] = "这是个测试ffffff2";
			$arr3["thumb_media_id"] ="lyNi35Z9oAwi9iLfxN3-RkRVZmbYbd5Fsdybrz6NWKY";
			$arr3["author"] = 'jh';
			$arr3["digest"] =  'bbb';
			$arr3["show_cover_pic"] = 1;
			$arr3["content"] = "<p>22222222222222";
			$arr3["content_source_url"] =  "https://blog.csdn.net/weixin_35746281/article/details/79178442";
		$arr4 = array();
			$arr4["title"] = "这是个测试ffffff2";
			$arr4["thumb_media_id"] ="lyNi35Z9oAwi9iLfxN3-RkRVZmbYbd5Fsdybrz6NWKY";
			$arr4["author"] = 'jh';
			$arr4["digest"] =  'bbb';
			$arr4["show_cover_pic"] = 1;
			$arr4["content"] = "<p>22222222222222";
			$arr4["content_source_url"] =  "https://blog.csdn.net/weixin_35746281/article/details/79178442";
		$data["articles"][0] = $arr;
		$data["articles"][1] = $arr1;
		$data["articles"][2] = $arr2;
		$data["articles"][3] = $arr3;
		$data["articles"][4] = $arr4;
		// print_r($data);
		// exit; 
		$data = json_encode($data,JSON_UNESCAPED_UNICODE);
		// // dump($data);
		// exit;


		// var_dump($data);exit;
  //        var_dump($data);
        $result = $this->https_post($url, $data);
        var_dump($result);exit;

   
        // var_dump($filename);exit;
        var_dump(json_decode($result));exit;
		 return view('admin.official.official_add',$data);
	}



	// 发送公众号
	public function official_get_push()
	{
		// $data = [
		// 	"touser" =>[
		//     'oEG8_w4TRGx1832QiRiUs0qRqLIQ',
		//     'oEG8_w2-pSuN4Xh3xShj9lD3V1pM',
		//     'oEG8_wxmcEDsq6dXtJdNLWbes4_0',
		//     'oEG8_w3V-ydXhPx0bk3flKMdNpBg'
		//    ],//预览用户的openid,测试号限制比较多,只能指定用户
		// 	'mpnews' => [
		// 		'media_id' => 'lyNi35Z9oAwi9iLfxN3-RlGCKS-LrkMUIFDsXjgFGV8',//我们已上传的图文素材id
		// 	],
		// 	'msgtype' => 'mpnews',
		// ];
		$data='
		{
		   "touser":[
		    "oEG8_w4TRGx1832QiRiUs0qRqLIQ",
		    "oEG8_wxmcEDsq6dXtJdNLWbes4_0",
		    "oEG8_w3V-ydXhPx0bk3flKMdNpBg",
		    "oEG8_w2-pSuN4Xh3xShj9lD3V1pM"
		   ],
		   "mpnews":{
		      "media_id":"lyNi35Z9oAwi9iLfxN3-Rm6RQXPwkqb75hI3bTml5gU"
		   },
		    "msgtype":"mpnews",
		    "send_ignore_reprint":0
		}';
		$url = 'https://api.weixin.qq.com/cgi-bin/message/mass/send?access_token='.$this->access_token();

		return  $this->https_post($url,$data);

	
	}


	  //修改永久图文素材
	  //单个图文修改是{} "index":0,
	  //多个图文修改是{[],[],[]} "index":k,
	  //       "articles": {
	  //           "title": "这是个标题ee",
	  //           "thumb_media_id":"RPHfU7CaPuLdH7iyCkZK0G06u3Cg4zY0mtCcXeYtCC4",
	  //           "show_cover_pic":"1",
	  //           "author":"作者",
	  //           "digest":"图文消息的摘要",
	  //           "content": "内容2222",
	  //           "content_source_url": "https://blog.csdn.net/weixin_35746281/article/details/79178442",
	 // }
    public function get_mediaupinfo()
    {
    	$media_id=request()->get('media_id'); //  //先上传在查询列表里面获取 
        $url = "https://api.weixin.qq.com/cgi-bin/material/update_news?access_token=".$this->access_token();
        $data =  '{
        	"media_id":"'.$media_id.'",
        	"index":0,
            "articles": {
	            "title": "这是个标题ee11",
	            "thumb_media_id":"lyNi35Z9oAwi9iLfxN3-RjYRqOjTEaKWyq3VftfJmxs",
	            "show_cover_pic":"1",
	            "author":"作者",
	            "digest":"图文消息的摘要",
	            "content": "内容2222",
	            "content_source_url": "https://blog.csdn.net/weixin_35746281/article/details/79178442",
			},
				"articles": {
		            "title": "2这是个测试ffffff2",
		            "thumb_media_id":"lyNi35Z9oAwi9iLfxN3-RkRVZmbYbd5Fsdybrz6NWKY",
		            "show_cover_pic":"1",
		              "author":"22222222222",
				  "digest":"",
			
		            "content": "测试内容",
		            "content_source_url": "https://blog.csdn.net/weixin_35746281/article/details/79178442",
					},
	
	            	"articles": {
		            "title": "3这是个测试ffffff2",
		            "thumb_media_id":"lyNi35Z9oAwi9iLfxN3-Rjp3ZSXGwV3YIRByXKPWr18",
		            "show_cover_pic":"1",
		                      "author":"22222222222",
				  "digest":"",
		            "content": "测试内容",
		            "content_source_url": "https://blog.csdn.net/weixin_35746281/article/details/79178442",
					},
       }';


        $result = $this->https_post($url,$data);
        $json = json_decode($result,true);
       return $json;

    }

    //获取素材总数
    public function official_add_materialcount()
    {

        $url = 'https://api.weixin.qq.com/cgi-bin/material/get_materialcount?access_token='.$this->access_token();
        $result = $this->curlGet($url);
        $res = json_decode($result, true);
        echo "<pre>";
        var_dump($res);exit;
    }

    //删除永久素材
	public function del_material(){
		$media_id=request()->get('media_id'); //  //先上传在查询列表里面获取 
		if (!$this->access_token()) return false;
		$curl = 'https://api.weixin.qq.com/cgi-bin/material/del_material?access_token='.$this->access_token();
		$data= array('media_id'=>$media_id);
		$result = $this->https_post($curl,json_encode($data));
		if ($result){
			$json = json_decode($result,true);
			
			 if($result['errcode']==0){
				return "素材删除成功";
			}elseif ($result['errcode']==40007) {
				return "素材ID不正确";
			}
		}
		return '素材删除失败';
	}

	//获取素材列表
	public function get_mediaList($offset=0,$count=20){
		$type=request()->get('type'); // 素材的类型,图片(image)、视频(video)、语音 (voice)、图文(news)
		if($type==1){
			$type="image";
		}else if($type==2){
			$type="news";
		}
		if (!$this->access_token()) return false;
		$data = array(
			'type'=>$type,
			'offset'=>$offset,
			'count'=>$count
		);
		$curl = 'https://api.weixin.qq.com/cgi-bin/material/batchget_material?access_token='.$this->access_token();
		$result = $this->https_post($curl,json_encode($data));
		if ($result){
			$json = json_decode($result,true);
			
			return $json;
		}
		return false;
	}


	//获取永久素材
	public function get_mediaInfo(){
		$media_id=request()->get('media_id'); //  //先上传在查询列表里面获取
		if (!$this->access_token()) return false;
		$curl = 'https://api.weixin.qq.com/cgi-bin/material/get_material?access_token='.$this->access_token();
		$data= array('media_id'=>$media_id);
		$result = $this->https_post($curl,json_encode($data));
		if ($result){
			$json = json_decode($result,true);
			
			return $json;
		}
		return false;
	}



	// 微信公众平台开发文档 用户分组管理
	// 创建分组
    public function official_AddUser_Group()
    {
    	$name=request()->get('name'); // 分组名字,UTF8编码
		if (!$this->access_token()) return false;
		$curl = 'https://api.weixin.qq.com/cgi-bin/groups/create?access_token='.$this->access_token();
		$data = array('group' =>['name'=>$name],);
		$data = json_encode($data,JSON_UNESCAPED_UNICODE);
		$result = $this->https_post($curl,$data);
		if ($result){
			$json = json_decode($result,true);
			
			return $json;
		}
		return false;
    }


    // 查询所有分组
    public function official_GetUser_Group()
    {
		if (!$this->access_token()) return false;
		$curl = 'https://api.weixin.qq.com/cgi-bin/groups/get?access_token='.$this->access_token();
		$result = $this->curlGet($curl,$data);
		if ($result){
			$json = json_decode($result,true);
			
			return $json;
		}
		return false;
    }


    // 查询用户所在分组
    public function official_GetUser_Group_GroupID()
    {
    	$openid=request()->get('openid'); // 用户的OpenID
		if (!$this->access_token()) return false;
		$curl = 'https://api.weixin.qq.com/cgi-bin/groups/getid?access_token='.$this->access_token();
		$data = array('group' =>['name'=>$openid]);
		$data = json_encode($data,JSON_UNESCAPED_UNICODE);
		$result = $this->https_post($curl,$data);
		if ($result){
			$json = json_decode($result,true);
			
			return $json;
		}
		return false;
    }


    // 修改分组名
    public function official_GetUser_Group_up()
    {
    	$name=request()->get('name'); //  分组名字(30个字符以内)
    	$id=request()->get('id'); //分组id,由微信分配
		if (!$this->access_token()) return false;
		$curl = 'https://api.weixin.qq.com/cgi-bin/groups/update?access_token='.$this->access_token();
		$data = array('group' =>['id'=>$id,'name'=>$name]);
		$data = json_encode($data,JSON_UNESCAPED_UNICODE);
		$result = $this->https_post($curl,$data);
		if ($result){
			$json = json_decode($result,true);
			
			return $json;
		}
		return false;
    }

    // 移动用户分组
    public function official_GetUser_Group_upOpenid()
    {
    	$openid=request()->get('openid'); //  用户唯一标识符
    	$to_groupid=request()->get('to_groupid'); // 	分组id
		if (!$this->access_token()) return false;
		$curl = 'https://api.weixin.qq.com/cgi-bin/groups/members/update?access_token='.$this->access_token();
		$data = array('openid'=>$openid,'to_groupid'=>$to_groupid);
		$data = json_encode($data,JSON_UNESCAPED_UNICODE);
		$result = $this->https_post($curl,$data);
		if ($result){
			$json = json_decode($result,true);
			
			return $json;
		}
		return false;
    }

        //生成二维码
    public function getWxQrcode($fqid,$type = 1){

        $url ='https://api.weixin.qq.com/cgi-bin/qrcode/create?access_token='.$this->access_token();
        if($type == 1){
            //生成永久二维码
            $qrcode= '{"action_name": "QR_LIMIT_STR_SCENE", "action_info": {"scene": {"scene_str":"1070_66"}}}';
        }else{
            //生成临时二维码 2505600==29天  2592000==30  604800==7天
            $qrcode = '{"expire_seconds": 604800, "action_name": "QR_STR_SCENE", "action_info": {"scene": {"scene_str":"1070_66"}}}';
        }
        $result = $this->http_post_data($url,$qrcode);
        $oo = json_decode($result[1]);
        if (empty($oo->ticket)){
            return false;
        }
        if(!$oo->ticket){
             var_dump('getQrcodeurl falied. Error Info: getQrcodeurl get failed');
            exit();
        }
        $url ='https://mp.weixin.qq.com/cgi-bin/showqrcode?ticket='.$oo->ticket.'';

        var_dump($url);
     echo "<img src=".$url."></img>";

    }




    //获取公众号access_token
    public function access_token(){
		$appid =$this->appid;
        $secret =$this->secret;
        $sta=Db::table('xcx_access_token')->where('id',2)->first();

        if(!empty($sta)){
            $ts=time()-$sta->time;
          
            if($ts>72){

                // var_dump('超时,则重新请求',$ts);
                //如果超时,则重新请求
	            $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=".$appid."&secret=".$secret;
	         	$arr = json_decode($this->curlGet($url), true);
	         	if($arr['errcode']==40164){
	         		return '不在白名单提示中'.$arr['errmsg'];
	         	}
                $access_token=$arr['access_token'];
                $arrayName = array('access_token' =>$access_token ,'time'=>time());
                Db::table('xcx_access_token')->where('id',2)->update($arrayName);
         
            }else{

                $access_token=$sta->access_token;
                $URL = "https://api.weixin.qq.com/cgi-bin/getcallbackip?access_token=".$access_token;
                $apiData=file_get_contents($URL);
                $arr =json_decode($apiData,true);
               	if($arr['errcode']==40164){
	         		return '不在白名单提示中'.$arr['errmsg'];
	         	}
	         
                // 错误重新请求
                if(empty($arr['ip_list'])){
                		
                    // 无效重新请求
			            $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=".$appid."&secret=".$secret;
			         	$result  = json_decode($this->curlGet($url), true);
			         	if($result['errcode']==40164){
			         		return '不在白名单提示中'.$result['errmsg'];
			         	}
                        $access_token=$result ['access_token'];
                        $arrayName = array('access_token' =>$access_token ,'time'=>time());
                        Db::table('xcx_access_token')->where('id',2)->update($arrayName);
                }
            }
        }else{ //空重新获取
            //否则,输出保存的token值
            // 获取access_token

            $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=".$appid."&secret=".$secret;
         	$arr = json_decode($this->curlGet($url), true);
 	        if($arr['errcode']==40164){
 	        	var_dump($arr);exit;
         		return '不在白名单提示中'.$arr['errmsg'];
         	}         	
            $access_token=$arr['access_token'];
            $arrayName = array('access_token' =>$access_token ,'time'=>time());
            Db::table('xcx_access_token')->insert($arrayName);
            // echo $apiData;exit;
        }
        return $access_token;
    }

    protected function http_post_data($url, $data_string) {
 
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
        curl_setopt($ch, CURLOPT_HTTPHEADER, array(
                'Content-Type: application/json; charset=utf-8',
                'Content-Length: ' . strlen($data_string))
        );
        ob_start();
        curl_exec($ch);
        if (curl_errno($ch)) {
            $this->ErrorLogger('curl falied. Error Info: '.curl_error($ch));
        }
        $return_content = ob_get_contents();
        ob_end_clean();
        $return_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        return array($return_code, $return_content);
    }

    public function curlGet($url)
    {
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($curl, CURLOPT_TIMEOUT, 500);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
        curl_setopt($curl, CURLOPT_URL, $url);
        $res = curl_exec($curl);
        curl_close($curl);
        return $res;

    }

    public function httpPost($url, $data)
    {
        $ch = curl_init();
        if (class_exists('\CURLFile')) {
            curl_setopt($ch, CURLOPT_SAFE_UPLOAD, true);
            $data = array('media' => new \CURLFile($data));//>=5.5
        } else {
            if (defined('CURLOPT_SAFE_UPLOAD')) {
                curl_setopt($ch, CURLOPT_SAFE_UPLOAD, false);
            }
            $data = array('media' => '@' . realpath($data));//<=5.5
        }
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_USERAGENT, "TEST");
        $result = curl_exec($ch);
        curl_close($ch);
        return $result;
    }

        //https请求(支持GET和POST)
 	public	function https_post($url, $post_data = null)
        {
            $ch = curl_init();
            curl_setopt($ch, CURLOPT_URL, $url);
            curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
            curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
            // post数据
            curl_setopt($ch, CURLOPT_POST, 1);
            // post的变量
            curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);
            $output = curl_exec($ch);
            curl_close($ch);
            return $output;
        }

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值