微信模板消息接口、微信客服接口

客服接口:http://mp.weixin.qq.com/wiki/1/70a29afed17f56d537c833f89be979c9.html

模板消息接口:http://mp.weixin.qq.com/wiki/5/6dde9eaa909f83354e0094dc3ad99e05.html

 

一、运行代码

<?php
namespace ThinkPHP\Library\Vendor;
class Wechat{
    private $appid ;
    private $appsecret;
    private $data;
    private $url;
    private $topcolor;
    public function __construct($data=‘‘,$url=‘‘,$openid=‘‘,$template_id=‘‘) {
        /* 读取站点配置 */
        $m_config = M(‘Config‘,‘ot_‘,DB_GOODS);
        $WX_APPID=$m_config ->where("name=‘WX_APPID‘")-> getField("value");
        $WX_SECRET=$m_config ->where("name=‘WX_SECRET‘")-> getField("value");
        $this ->appid           = $WX_APPID;
        $this ->appsecret       = $WX_SECRET;
        $this ->data            = $data;
        $this ->url             = $url;
        $this ->openid          = $openid;
        $this ->template_id   = $template_id;
        $this ->topcolor      = ‘#743A3A‘;
        if( ! is_dir( $this->json_dir) ) {
            mkdir($this->json_dir ,0777 ,true) ;
        }
      }

    protected function getToken() {
        $m_appact = M(‘Appact‘,‘ot_‘,DB_GOODS);
        $data = $m_appact -> where(array(‘appid‘=> $this ->appid)) -> field(‘access_token,expire_time‘) -> find();
        if ($data[‘expire_time‘] < time()) {
            // 如果是企业号用以下URL获取access_token
            // $url = "https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid=$this->appId&corpsecret=$this->appSecret";
            $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=$this->appid&secret=$this->appsecret";
            $res = json_decode($this->httpGet($url));
            $access_token = $res->access_token;
            if ($access_token) {
                $data[‘expire_time‘] = time() + 7000;
                $data[‘access_token‘] = $access_token;
                $r = $m_appact -> where(array(‘appid‘=> $this->appid)) -> find();
                $save_arr = array(‘access_token‘=> $data[‘access_token‘],‘expire_time‘=> $data[‘expire_time‘]);
                $add_arr  = array(‘appid‘=>$this->appid,‘access_token‘=> $data[‘access_token‘],‘expire_time‘=> $data[‘expire_time‘]);
                $r ? $m_appact -> where(array(‘appid‘=> $this->appid)) -> save($save_arr) : $m_appact -> add($add_arr);
            }
        } else {
            $access_token = $data[‘access_token‘];
        }
        return $access_token;
    }

     /**
     * 发送自定义的模板消息
     * @param $touser
     * @param $template_id
     * @param $url
     * @param $data
     * @param string $topcolor
     * @return bool
     * $touser, $template_id, $url, $data, $topcolor = ‘#7B68EE‘,$accessToken
     */
    public function doSend() {
        /*
         * data=>array(
         ‘first‘=>array(‘value‘=>urlencode("您好,您已购买成功"),‘color‘=>"#743A3A"),
         ‘name‘=>array(‘value‘=>urlencode("商品信息:微时代电影票"),‘color‘=>‘#EEEEEE‘),
         ‘remark‘=>array(‘value‘=>urlencode(‘永久有效!密码为:1231313‘),‘color‘=>‘#FFFFFF‘),
         )
         */
        $template = array(‘touser‘ => $this->openid, ‘template_id‘ => $this->template_id, ‘url‘ => $this->url, ‘topcolor‘ => $this->topcolor, ‘data‘ => $this->data);
        // dump($template);
        $json_template = json_encode($template);
        $accessToken = $this -> getToken();
        $url = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=" . $accessToken;
        $dataRes = $this -> do_post_request($url, urldecode($json_template));
        //$dataRes[‘errcode‘] == 0 是正确的
        return $dataRes[‘errcode‘];
        
    }
    
    /***********************
     * 客服发送消息
     ***********************/
    function reply_customer($touser,$content){
        $ACC_TOKEN = $this -> getToken();
        $data = ‘{
            "touser":"‘.$touser.‘",
            "msgtype":"text",
            "text":
            {
                 "content":"‘.$content.‘"
            }
        };
        $url = "https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token=".$ACC_TOKEN;
        $result = $this -> do_post_request($url,$data);
        $final = json_decode($result);
        return $final;
    }

    private function httpGet($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;
    }
    // 远程请求方法
    function do_post_request($url, $data, $optional_headers = null){
         $params = array(
            ‘http‘ => array(
            ‘method‘ => ‘POST‘,
            ‘content‘ => $data
         ));
         if ($optional_headers !== null) {
            $params[‘http‘][‘header‘] = $optional_headers;
         }
         $ctx = stream_context_create($params);
         $fp = @fopen($url, ‘rb‘, false, $ctx);
         if (!$fp) {
            exit(‘-1000‘);
         }
         $response = @stream_get_contents($fp);
         if ($response === false) {
            exit(‘-1001‘);
         }
         return $response;
    }

}

 

二、模板消息调用

$import_rtn = vendor(‘Wechat‘);
$openid = D("Openid")->where(array(‘uid‘=>$v[‘uid‘]))->getfield(‘open_id‘);
$template_id = ‘Tk1EFMv91*******0tcjVpHxNTkhm4r-mk64AluM‘;
$data = array(
            ‘first‘=>array(‘value‘=>urlencode("主播开播提示"),‘color‘=>"#000"),
            ‘keyword1‘=>array(‘value‘=>urlencode($info_title),‘color‘=>‘#000‘),
            ‘keyword2‘=>array(‘value‘=>urlencode(‘您所关注的‘.$info_title.‘正在直播,点击详情进入吧‘),‘color‘=>‘#000‘),
            ‘remark‘=>array(‘value‘=>urlencode(""),‘color‘=>‘#000‘),
        );
$url = get_config_t(‘HOOTS_URL_H‘).‘/Mob/Chat/index_o/gid/‘.$gid;
if(!empty($openid) && $import_rtn){ $wechat = new \ThinkPHP\Library\Vendor\Wechat($data,$url,$openid,$template_id); $res = $wechat->doSend(); if($res == 0){ return 1;} }

 

三、客服消息调用

    $openid = "*******************";
    $content = ‘消息消息‘;
    $import_rtn = vendor(‘Wechat‘);
    if(!empty($openid) && $import_rtn){
        $wechat = new \ThinkPHP\Library\Vendor\Wechat();
        $res  = $wechat->reply_customer($openid,$content);
        if($res){ return 1;}
    }

 

微信模板消息接口、微信客服接口

上一篇:Android笔记(六十九) 仿微信界面(一)


下一篇:微信access_token