微信第三方平台授权实现公众号与粉丝交互

 public function __construct()
	{
		$param = model('parameter')->getval();
		$this->grant = new grant($param->token, $param->encodingAesKey, $param->appid, $param->appsecret);
		$this->redis = new redisChat();
		$this->clientkefu = new ClientKefu();
		$this->Gateway = new chat();
	}

    //微信公众平台URL以响应微信发送的Token验证
    public function wxOp()
    {
        $token = 'we*****';	//创建平台时填写的公众号消息校验Token
        $appId = '******';  //第三方平台appid
        $encodingAesKey = '*******';	//创建平台时填写的公众号消息加解密Key
		//写记事本
        $year = date('Y');
        $month = date('m');
        $day = date('d');
        $time = date('H:i:s');
        $route = dirname(dirname(dirname(__FILE__)));
        $path = "$route/notify/$year/$month";
		// 获取xml
        $xml = file_get_contents('php://input', 'r');
        libxml_disable_entity_loader(true);//转成php数组 禁止引用外部xml实体
        $data = json_encode(simplexml_load_string($xml, 'SimpleXMLElement', LIBXML_NOCDATA));
		//获取几个基本参数
        $timeStamp = empty($_GET['timestamp']) ? "" : trim($_GET['timestamp']);
        $nonce = empty($_GET['nonce']) ? "" : trim($_GET['nonce']);
        $msg_sign = empty($_GET['msg_signature']) ? "" : trim($_GET['msg_signature']);
		//接收XML数据
        $encryptMsg = file_get_contents('php://input');
        $pc = new wxBizMsgCrypt($token, $encodingAesKey, $appId);
        $xml_tree = new \DOMDocument();
        $xml_tree->loadXML($encryptMsg);
        $array_e = $xml_tree->getElementsByTagName('Encrypt');
        $encrypt = $array_e->item(0)->nodeValue;
        $format = "<xml><ToUserName><![CDATA[toUser]]></ToUserName><Encrypt><![CDATA[%s]]></Encrypt></xml>";
        $from_xml = sprintf($format, $encrypt);
			//利用微信官方给的方法解密,$msg就是解密后的值
        $msg = '';
        $errCode = $pc->decryptMsg($msg_sign, $timeStamp, $nonce, $from_xml, $msg);
        $component_verify_ticket = "";
			//解密成功
        if ($errCode == 0) {
			//print("解密后: " . $msg . "\n");
            $xml = new \DOMDocument();
            $xml->loadXML($msg);
            $array_e = $xml->getElementsByTagName('ComponentVerifyTicket');
            $component_verify_ticket = $array_e->item(0)->nodeValue;
           	model('parameter')->saveval(['ticket' => $component_verify_ticket,'titime' => time()]);
        } else {			//解密失败
        }
        if (!file_exists($path)) {
            mkdir($path, 0777, true);
            $data = '04:' . date('Y-m-d H:i:s') . ':' . $errCode . ':' . $component_verify_ticket;
            file_put_contents("$path/$day.txt", "$data\r\n", FILE_APPEND);
        } else {
            $data = '04:' . date('Y-m-d H:i:s') . ':' . $errCode . ':' . $component_verify_ticket;
            file_put_contents("$path/$day.txt", "$data\r\n", FILE_APPEND);
        }
    }




    public function problemsOp()
    {
        $url = 'https://chat.wenidc.com/notify/wechat/problems';	//获取url
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_HEADER, 0);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $array);
        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
                    //超时时间
        curl_setopt($ch, CURLOPT_TIMEOUT, 1800);//在成功连接服务器前等待多久
                    //忽略证书
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);//输出方式
        $data = curl_exec($ch);//返回值赋值给$data
        curl_close($ch);
        return;
        $path = dirname(dirname(dirname(__FILE__))) . '/notify/' . date('Y') . '/' . date('m');
        if (request()->ispost()) {
            $array = input('post.');
            $arr = json_encode($array);
            file_put_contents($path . '/' . date('d') . ".txt", "$arr\r\n", FILE_APPEND);
            $userid = model('wx_token')->where(['to_user_name' => $array['ToUserName']])->value('uid');
            $tongxingma = model('user')->where(['numid' => $userid])->value('token');
            $row = model('client')->where(['uid' => $array['FromUserName'], 'rulerid' => $userid])->find();
            file_put_contents($path . '/' . date('d') . ".txt", "查询数据库判断是否有值值为:\r\n", FILE_APPEND);
            $component_access_token = model('parameter')->getctoken();
            if ($array['MsgType'] == 'image') {
                $access_token = $this->grant->gettoken($array['ToUserName'], $component_access_token, $userid);
                $filename = $this->grant->getmedia($access_token, $array['MediaId'], UPLOADS_PATH); //获取接受到图片并下载下来,返回图片名
                file_put_contents($path . '/' . date('d') . ".txt", "下载的文件名$filename\r\n", FILE_APPEND);
                $array['message'] = $filename;
                if ($row != null && $row['status'] != 0) {
                    $this->sendMssage($row, $array, $tongxingma, 2);
                } else {
                    $this->addClient($component_access_token, $array, 2, $userid, $tongxingma);
                }
            } else if ($array['MsgType'] == 'text') {
                $message = $array['Content'];
                file_put_contents($path . '/' . date('d') . ".txt", "接受文本消息:$message\r\n", FILE_APPEND);
                $array['message'] = $array['Content'];
                if ($row != null && $row['status'] != 0) {
                    file_put_contents($path . '/' . date('d') . ".txt", "已接待后的消息\r\n", FILE_APPEND);
                    $this->sendMssage($row, $array, $tongxingma);
                } else {
                    file_put_contents($path . '/' . date('d') . ".txt", "未接待后的消息\r\n", FILE_APPEND);
                    $this->addClient($component_access_token, $array, 1, $userid, $tongxingma);
                }
            }
            if ($row != null && $row['server'] != null) {
                $this->clientkefu->horn($array['FromUserName'], $row['server'], $type = 3); //小喇叭
            } else {
                $this->clientkefu->horn($array['FromUserName'], '', $type = 3); //小喇叭
            }

        }
    }




	//通过该URL接收公众号或小程序消息和事件推送,该参数按规则填写(需包含/$APPID$,如www.abc.com/$APPID$/callback),实际接收消息时$APPID$将被替换为公众号或小程序AppId
    public function receiveOp()
    {
        $component_access_token = model('parameter')->getctoken();
        $param = model('parameter')->getval();
        $msgSignature = $_GET['msg_signature'];
        $timestamp = $_GET['timestamp'];
        $nonce = $_GET['nonce'];
        $xml = file_get_contents('php://input');
        $path = dirname(dirname(dirname(__FILE__))) . '/notify/' . date('Y') . '/' . date('m');
        file_put_contents($path . '/' . date('d') . ".txt", "b\r\n", FILE_APPEND);
        $pc = new wxBizMsgCrypt($param->token, $param->encodingAesKey, $param->appid);
        $msg = '';
        $errCode = $pc->decryptMsg($msgSignature, $timestamp, $nonce, $xml, $msg);
        if ($errCode == 0) {
            $postObj = simplexml_load_string($msg, 'SimpleXMLElement', LIBXML_NOCDATA);
            $postObj = json_encode($postObj, JSON_UNESCAPED_UNICODE);
            file_put_contents($path . '/' . date('d') . ".txt", "$postObj\r\n", FILE_APPEND);
            $array = json_decode($postObj, true);
            $userid = model('wx_token')->where(['to_user_name' => $array['ToUserName']])->value('uid');
            $tongxingma = model('user')->where(['numid' => $userid])->value('token');
            $row = model('client')->where(['uid' => $array['FromUserName'], 'rulerid' => $userid])->find();
            file_put_contents($path . '/' . date('d') . ".txt", "查询数据库判断是否有值值为:\r\n", FILE_APPEND);
            if ($array['MsgType'] == 'image') {
                $access_token = $this->grant->gettoken($array['ToUserName'], $component_access_token, $userid);
                $filename = $this->grant->getmedia($access_token, $array['MediaId'], UPLOADS_PATH); //获取接受到图片并下载下来,返回图片名
                file_put_contents($path . '/' . date('d') . ".txt", "下载的文件名$filename\r\n", FILE_APPEND);
                $array['message'] = $filename;
                if ($row != null && $row['status'] != 0) {
                    $this->sendMssage($row, $array, $tongxingma, 2);
                } else {
                    $this->addClient($component_access_token, $array, 2, $userid, $tongxingma);
                }
            } else if ($array['MsgType'] == 'text') {
                $message = $array['Content'];
                file_put_contents($path . '/' . date('d') . ".txt", "接受文本消息:$message\r\n", FILE_APPEND);
                $array['message'] = $array['Content'];
                if ($row != null && $row['status'] != 0) {
                    file_put_contents($path . '/' . date('d') . ".txt", "已接待后的消息\r\n", FILE_APPEND);
                    $this->sendMssage($row, $array, $tongxingma);
                } else {
                    file_put_contents($path . '/' . date('d') . ".txt", "未接待后的消息\r\n", FILE_APPEND);
                    $this->addClient($component_access_token, $array, 1, $userid, $tongxingma);
                }
            }
        }
        if ($row != null && $row['server'] != null) {
            $this->clientkefu->horn($array['FromUserName'], $row['server'], $type = 3); //小喇叭
        } else {
            $this->clientkefu->horn($array['FromUserName'], '', $type = 3); //小喇叭
        }
        return 'success';
    }

    //通过该URL接收公众号或小程序消息和事件推送,该参数按规则填写(需包含/$APPID$,如www.abc.com/$APPID$/callback),实际接收消息时$APPID$将被替换为公众号或小程序AppId
    public function receiveOp()
    {
        $component_access_token = model('parameter')->getctoken();
        $param = model('parameter')->getval();
        $msgSignature = $_GET['msg_signature'];
        $timestamp = $_GET['timestamp'];
        $nonce = $_GET['nonce'];
        $xml = file_get_contents('php://input');
        $path = dirname(dirname(dirname(__FILE__))) . '/notify/' . date('Y') . '/' . date('m');
        $pc = new wxBizMsgCrypt($param->token, $param->encodingAesKey, $param->appid);
        $msg = '';
        $errCode = $pc->decryptMsg($msgSignature, $timestamp, $nonce, $xml, $msg);
        if ($errCode == 0) {
            $postObj = simplexml_load_string($msg, 'SimpleXMLElement', LIBXML_NOCDATA);
            $data = json_encode($postObj, JSON_UNESCAPED_UNICODE);
            file_put_contents($path . '/' . date('d') . ".txt", "收到消息" . $data . "\r\n", FILE_APPEND);
            $array = json_decode($data, true);
            $url = 'https://chat.wenidc.com/notify/wechat/problems';	//获取url
            $ch = curl_init();
            curl_setopt($ch, CURLOPT_HEADER, 0);
            curl_setopt($ch, CURLOPT_POST, 1);
            curl_setopt($ch, CURLOPT_POSTFIELDS, $array);
            curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
                    //超时时间
            curl_setopt($ch, CURLOPT_TIMEOUT, 1800);//在成功连接服务器前等待多久
                    //忽略证书
            curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
            curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
            curl_setopt($ch, CURLOPT_URL, $url);
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);//输出方式
            $data = curl_exec($ch);//返回值赋值给$data
            curl_close($ch);
            return;
        }
        return 'success';
    }

   //给客服发送消息
    public function sendMssage($row, $array, $tongxingma, $type = 1)
    {
        $path = dirname(dirname(dirname(__FILE__))) . '/notify/' . date('Y') . '/' . date('m');
        if ($row['mark'] == $array['MsgId']) {
            return 'success';
        }
        if ($row['mark']) {
            model('client')->allowField(true)->isUpdate(true)->save(['numid' => $row['numid'], 'mark' => $array['MsgId']]);
        } else {
            model('client')->allowField(true)->isUpdate(false)->save($data);
        }
        $this->Gateway->sendToUid(['uid' => $row['server'], 'message' => json_encode(array(
            'type' => 'acceptance',
            'sign' => 'old',
            'username' => $row['username'],
            'client_uid' => $array['FromUserName'],
            'binddate' => $array['CreateTime'],
            'lastmsg' => '',
            'lastservice' => '',
            'clientid' => $array['FromUserName'],
            'speaker' => $array['FromUserName'],
            'listener' => '',
            'speakername' =>  $row['username'],
            'message' => $array['message'],
            'order' => $type
        ))]);

        $this->redis->checkUserReadable == true; //设在线参数
        if ($type == 2) {
            $data = [
                'speech' => $array['message'],
                'speaker' => $row['uid'],
                'listener' => $row['server'],
                'type' => 2,
                'tongxingma' => $tongxingma,
                'speakername' => $row['username']
            ];
        } else {
            $data = [
                'speakername' => $row['username'],
                'speech' => $array['message'],
                'type' => 1,
            ];
        }
        $data['listenername'] = model('server')->get_username($row['server']);
        if (strpos($array['FromUserName'], '_') !== false) {
            $fromid = explode('_', $array['FromUserName']);
            $fromid = $fromid[1];
        } else {
            $fromid = $array['FromUserName'];
        }
       $rslist = $this->redis->setChatRecord($fromid, $row['server'], $data); //存redis
        $this->redis->setHisRecord($fromid, $row['server'], $data);//存历史记录
    }

     //curl 获取文件数据
    public function curl_file($url)
    {
        $ch = curl_init($url);
        curl_setopt($ch, CURLOPT_HEADER, 0);
        curl_setopt($ch, CURLOPT_NOBODY, 0);//只取body头
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);//curl_exec执行成功后返回执行的结果;不设置的话,curl_exec执行成功则返回true
        $output = curl_exec($ch);
        curl_close($ch);
        return $output;
    }




   //微信粉丝未被接待发送的消息
    public function addClient($component_access_token, $array, $type, $userid, $tongxingma)
    {
        $path = dirname(dirname(dirname(__FILE__))) . '/notify/' . date('Y') . '/' . date('m');
        file_put_contents($path . '/' . date('d') . ".txt", $array['message'], FILE_APPEND);
        $ToUserName = $array['ToUserName'];
        $FromUserName = $array['FromUserName'];
        $access_token = $this->grant->gettoken($ToUserName, $component_access_token, $userid);
        $result = json_decode($this->grant->getinfo($access_token, $FromUserName), true);
        if (array_key_exists("errcode", $result)){
            return 'success';
        }

        $data = [
            'username' => '微信(' . $result['nickname'] . ')',
            'clientid' => $array['ToUserName'],
            'mark' => $array['MsgId'],
            'uid' => $array['FromUserName'],
            'status' => 0,
            'img' => $result['headimgurl'],
            'ip' => '',
            'binddate' => $array['CreateTime'],
            'groupid' => '',
            'rulerid' => $userid,
            'type' => 1,
        ];
        $row = model('client')->where(['uid' => $array['FromUserName'], 'rulerid' => $userid])->find();
        file_put_contents($path . '/' . date('d') . ".txt", "$id\r\n", FILE_APPEND);
        if (!$row) {
            model('client')->allowField(true)->isUpdate(false)->save($data);
        } else {
            // file_put_contents($path . '/' . date('d') . ".txt", "qq", FILE_APPEND);
            // $row = model('client')->where(['uid' => $array['FromUserName'], 'rulerid' => $userid])->field('mark,numid');
            // file_put_contents($path . '/' . date('d') . ".txt", "qq", FILE_APPEND);
            if ($row['mark'] == $array['MsgId']) {
                return 'success';
            } else {
                model('client')->allowField(true)->isUpdate(true)->save(['numid' => $row['numid'], 'mark' => $array['MsgId']]);
            }
        }
        $data = [
            'client_id' => $array['MsgId'],
            'uid' => $array['FromUserName']
        ];
        $this->Gateway->bindUid($data);
        $Server_group = 'Server' . $tongxingma;
        $this->Gateway->sendToGroup(['group' => $Server_group, 'message' => json_encode(array(
            'type' => 'acceptance',
            'sign' => 'new',
            'username' => "微信(" . $result['nickname'] . ")",
            'client_uid' => $array['FromUserName'],
            'binddate' => datetime(time()),
            'lastmsg' => '',
            'lastservice' => '',
            'clientid' => $array['FromUserName'],
            'speaker' => $array['FromUserName'],
            'listener' => '',
            'speakername' => $result['nickname'],
            'message' => $array['message'],
            'order' => $type
        ))]);
        //存游客未接待历史记录
        $redisData = [
            'speakername' => "微信(" . $result['nickname'] . ")",
            'speech' => $array['message'],
            'type' => $type,
            'wx_chat' => 1,  //判断是否是微信的消息
            'clientid' => $array['FromUserName'],  //存下clientid
        ];
        $fromid = $this->redis->division($array['FromUserName']);
        $data = $this->redis->setYoukeRecord($fromid, $redisData, $userid); //未绑定客服   存游客redis
    }


    private function https_request($url, $data = null)
    {

        $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)) {
            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 wechatOp()

{

$this->assign('url', url('user/test/componentloginpage'));

return $this->fetch();

}

     //唤起扫码页面

public function componentloginpageOp()

{

$param = model('parameter')->getval();

$this->grant = new grant($param->token, $param->encodingAesKey, $param->appid, $param->appsecret);

return $this->redirect($this->grant->rqcode()); //重定向

}



 

    //回调页面

public function callbackOp()

{

$param = model('parameter')->getval();

$this->grant = new grant($param->token, $param->encodingAesKey, $param->appid, $param->appsecret);

$auth_code = input('auth_code'); //微信授权码

$component_access_token = model('parameter')->getctoken();

        //4,使用授权码换取公众号或小程序的接口调用凭据和授权信息

$authInfo = $this->grant->apiQueryAuth($component_access_token, $auth_code);

if (!array_key_exists('authorization_info', $authInfo)) {

return '使用授权码换取公众号信息失败';

}

$authInfo = $authInfo['authorization_info'];

//6 .获取授权方的帐号基本信息

$account_information = $this->grant->apiGetAuthorizerInfo($component_access_token, $authInfo);

$authorizer_info = $account_information['authorizer_info'];

$authorization_info = $account_information['authorization_info'];

$id = model('wx_authorization_information')->where(['authorizer_appid' => $authorization_info['authorizer_appid'], 'uid' => $this->userinfo['uid'], 'user_name' => $authorizer_info['user_name']])->value('id');

foreach ($authorization_info['func_info'] as $k => $v) {

$func_info[] = $v['funcscope_category']['id'];

}

$data = [

'authorizer_appid' => $authorization_info['authorizer_appid'],

'nick_name' => $authorizer_info['nick_name'],

'uid' => $this->userinfo['uid'],

'kefuid' => $this->userinfo['rulerid'],

'head_img' => $authorizer_info['head_img'],

'user_name' => $authorizer_info['user_name'],//原始id

'service_type_info' => $authorizer_info['service_type_info']['id'], //授权方公众号类型

'verify_type_info' => $authorizer_info['verify_type_info']['id'],//授权方认证类型

'business_info' => json_encode($authorizer_info['business_info']),

'func_info' => json_encode($func_info)

];

if ($id == null) {

$type = false;

} else {

$type = true;

$data['id'] = $id;

}

$result = model('wx_authorization_information')->allowField(true)->isUpdate($type)->save($data);

$authInfo['to_user_name'] = $authorizer_info['user_name'];

        //5.获取(刷新)授权公众号或小程序的接口调用凭据(令牌)

$tokenArr = $this->grant->apiAuthorizerToken($component_access_token, $authInfo, $this->userinfo['uid']);

//7.获取授权方的选项设置信息

$option_gettings_information = $this->grant->apiGetAuthorizerOption($component_access_token, $account_information);

  // 8、设置授权方的选项信息

$option_settings_information = $this->grant->apiSetAuthorizerOption($component_access_token, $option_gettings_information);

//

return $this->redirect("/user/kefu/toGrant"); //重定向

//令牌未缓存。

}


 

//删除授权者的信息

public function delTokenOp()

{

if (request()->isAjax() && request()->isPost()) {

$to_user_name = input('to_user_name');

$wx_authorization_information = model('wx_authorization_information')->where(['user_name' => $to_user_name, 'uid' => $this->userinfo['uid']])->delete();

$wx_token = model('wx_token')->where(['to_user_name' => $to_user_name, 'uid' => $this->userinfo['uid']])->delete();

if ($wx_token && $wx_authorization_information) {

return ['code' => 'success', 'msg' => '删除成功'];

} else {

return ['code' => 'error', 'msg' => '删除失败'];

}

}

}

自己封装的微信方法一个类

<?php
namespace chatAPI\wxauthorized;

class grant {
	private $token;
	private $encodingAesKey;
	private $appid;
	private $appsecret;
	/**
	 * 构造函数
	 * @param $token string 公众平台上,开发者设置的token
	 * @param $encodingAesKey string 公众平台上,开发者设置的EncodingAESKey
	 * @param $appId string 公众平台的appId
	 */
	public function __construct($token, $encodingAesKey, $appid, $appsecret)
	{
		$this->token = $token;
		$this->encodingAesKey = $encodingAesKey;
		$this->appid = $appid;
		$this->appsecret = $appsecret;
	}
	public function rqcode()
	{
	    $preAuthCode = $this->preAuthCode(model('parameter')->getctoken());
		$redirect_uri = "http://chat.wenidc.com/user/test/callback";    //回调地址
		$url = "https://mp.weixin.qq.com/cgi-bin/componentloginpage?component_appid=$this->appid&pre_auth_code=${preAuthCode}&redirect_uri=${redirect_uri}";
		return $url;

	}
	//2,获取第三方平台component_access_token
	public function componentAccessToken($component_verify_ticket)
	{
		$url = "https://api.weixin.qq.com/cgi-bin/component/api_component_token";
		$data = array(
			"component_appid" => $this->appid,
			"component_appsecret" => $this->appsecret,
			"component_verify_ticket" => $component_verify_ticket
		);
		$send_result = json_decode($this->https_request($url, json_encode($data)), true);
		if ($send_result) {
			return $send_result['component_access_token'];
		} else {
			return $send_result;
		}

	}
	//3,获取预授权码pre_auth_code
	private function preAuthCode($component_access_token)
	{
		$url = "https://api.weixin.qq.com/cgi-bin/component/api_create_preauthcode?component_access_token=$component_access_token";
		$data = array(
			"component_appid" => $this->appid,
		);
		$send_result = $this->https_request($url, json_encode($data));
		$send_result = json_decode($send_result, true);
		if ($send_result) {
			return $send_result['pre_auth_code'];// 微信预授权码
		} else {
			return $send_result;
		}
	}
	//4,使用授权码换取公众号或小程序的接口调用凭据和授权信息
	private function apiQueryAuth($component_access_token, $auth_code)
	{
		$url = "https://api.weixin.qq.com/cgi-bin/component/api_query_auth?component_access_token=$component_access_token";
		$data = array(
			"component_appid" => $this->appid,
			"authorization_code" => $auth_code,
		);
		$send_result = json_decode($this->https_request($url, json_encode($data)), true);
		return $send_result;
	}
    //获取授权公众号或小程序的接口调用凭据(令牌)
	public function gettoken($tousername, $component_access_token,$userid)
	{
		$result = model('wx_token')->where(['uid' => $userid, 'to_user_name' => $tousername])->find();
		$datetime = $result['datatime'] + $result['expires_in'];
		if (time() > $datetime) {
			$apiAuthorizerToken = $this->apiAuthorizerToken($component_access_token, $result, $userid);
			if (!$apiAuthorizerToken) {
				return false;
			}
			return $apiAuthorizerToken['authorizer_access_token'];
		}
		return $result['authorizer_access_token'];
	}
	 //5.获取(刷新)授权公众号或小程序的接口调用凭据(令牌)
	private function apiAuthorizerToken($component_access_token, $authInfo,$userid)
	{
		$url = "https://api.weixin.qq.com/cgi-bin/component/api_authorizer_token?component_access_token=$component_access_token";
		$data = array(
			"component_appid" => $this->appid,
			"authorizer_appid" => $authInfo['authorizer_appid'],
			"authorizer_refresh_token" => $authInfo['authorizer_refresh_token'],
		);
		$send_result = $this->https_request($url, json_encode($data));
		$result = json_decode($send_result, true);
		if ($result) {
			$data = [
				'authorizer_appid' => $authInfo['authorizer_appid'],
				'authorizer_access_token' => $result['authorizer_access_token'],
				'authorizer_refresh_token' => $result['authorizer_refresh_token'],
				'expires_in' => $result['expires_in'],
				'datatime' => time(),

			];
			$isupdate = array_key_exists('id', $authInfo);
			if ($isupdate) {
				$data['id'] = $authInfo['id'];
				model('wx_token')->allowField(true)->isUpdate(true)->save($data);
			} else {
				$id = model('wx_token')->where(['uid' => $userid, 'to_user_name' => $authInfo['to_user_name']])->value('id');
				if ($id) {
					$data['id'] = $id;
					model('wx_token')->allowField(true)->isUpdate(true)->save($data);
				} else {
					$data['uid'] = $userid;
					$data['to_user_name'] = $authInfo['to_user_name'];
					model('wx_token')->allowField(true)->isUpdate(false)->save($data);
				}
			}

		}
		return $result;
	}
    //6 .获取授权方的帐号基本信息
	private function apiGetAuthorizerInfo($component_access_token, $authInfo)
	{

		$url = "https://api.weixin.qq.com/cgi-bin/component/api_get_authorizer_info?component_access_token=$component_access_token";
		$data = array(
			'component_appid' => $this->appid,
			'authorizer_appid' => $authInfo['authorizer_appid'],
		);
		$account_information = $this->https_request($url, json_encode($data));  //授权方的帐号基本信息
		return json_decode($account_information, true);
	}
    //7.获取授权方的选项设置信息
	private function apiGetAuthorizerOption($component_access_token, $account_information)
	{
		if (!array_key_exists('authorizer_info', $account_information)) {
			return '使用授权码换取公众号信息失败';
		}
		$authorizer_info = $account_information['authorizer_info'];
		$account_information = $account_information['authorization_info'];
		$url = "https://api.weixin.qq.com/cgi-bin/component/api_get_authorizer_option?component_access_token=$component_access_token";
		$data = array(
			'component_appid' => $this->appid,
			'authorizer_appid' => $account_information['authorizer_appid'], //授权公众号或小程序的appid
			'option_name' => 'voice_recognize',     //选项名称
		);
		$option_settings_information = $this->https_request($url, json_encode($data));  //获取授权方的选项设置信息
		return json_decode($option_settings_information, true);
	}

	// 8、设置授权方的选项信息
	private function apiSetAuthorizerOption($component_access_token, $option_gettings_information)
	{
		$url = "https://api.weixin.qq.com/cgi-bin/component/api_set_authorizer_option?component_access_token=$component_access_token";
		$data = array(
			"component_appid" => $this->appid,
			"authorizer_appid" => $option_gettings_information['authorizer_appid'],
			"option_name" => $option_gettings_information['option_name'],
			"option_value" => $option_gettings_information['option_value'],
		);
		$apiSetAuthorizerOption = $this->https_request($url, json_encode($data));  //获取授权方的选项设置信息
		return json_decode($apiSetAuthorizerOption, true);
	}
	private function https_request($url, $data = null)
	{

		$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)) {
			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 send_message($userinfo,$data, $to_user_name, $component_access_token){
		$access_token = $this->gettoken($to_user_name, $component_access_token, $userinfo['uid']);
		$url = "https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token=$access_token";
		$resultData = $this->https_request($url, json_encode($data,JSON_UNESCAPED_UNICODE));
		return $resultData;
	}


	 //curl 获取文件数据
	public function curl_file($url)
	{
		$ch = curl_init($url);
		curl_setopt($ch, CURLOPT_HEADER, 0);
		curl_setopt($ch, CURLOPT_NOBODY, 0);//只取body头
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);//curl_exec执行成功后返回执行的结果;不设置的话,curl_exec执行成功则返回true
		$output = curl_exec($ch);
		curl_close($ch);
		return $output;
	}

	//下载素材
	public function getmedia($access_token, $media_id, $foldername)
	{
		$url = "https://api.weixin.qq.com/cgi-bin/media/get?access_token=$access_token&media_id=$media_id";
		$files = $this->curl_file($url);
		if (!file_exists($foldername)) {
			mkdir($foldername, 0777, true);
		}
		$filename = uniqid('chat_img_' . false) . '.jpg'; //拼接文件名
		$targetName = $foldername . '/' . $filename;
		$saveName = $foldername . $filename;
		$newFile = fopen($targetName, 'w'); // 打开写入
		fwrite($newFile, $files); //写入二进制流到文件
		fclose($newFile);
		return $filename;
	}
  	//获取发送人的信息
	public function getinfo($access_token, $openid, $lang = 'zh_CN')
	{
		$url = "https://api.weixin.qq.com/cgi-bin/user/info?access_token=$access_token&openid=$openid&lang=$lang";
		$result = $this->https_request($url);
		return $result;
	}
}

未经允许禁止转发

猜你喜欢

转载自blog.csdn.net/joker6295/article/details/88075523