微信公众号php api

<?php
namespace Common\Controller;


use Think\Controller;
/**
 * 前台公共控制器
 * 为防止多分组Controller名称冲突,公共Controller名称统一使用分组名称
 */
class WechatbaseController extends Controller {


//微信appid
public $appid = '';

//微信secret
public $secret = '';


/*空操作*/
public function _empty($name){       
 
$this->display($name);
}


public function getOpenid () {
$this->getWeChat();
        if (is_null($_GET['openid']) && !is_null($_GET['code'])) {
            $info_array = get_user_info($this->appid , $this->secret , $_GET['code']);
            $_GET['openid'] = $info_array['openid'];
        }
}


protected function checkUser () {
$where['openid'] = array('eq' , cookie('openid') );
$jumin = M('Juming')->where($where)->find();
$where['delete'] = array('eq' , 0);
$xugly  = M('ProjectManagement')->where($where)->find();


if (empty($jumin) && empty($xugly)) {
return false;
}else {
return true;
}


}




//获取微信公众号信息
public function getWeChat() {

$wechat = M('wechat');

$wechat_array = $wechat->find();

$this->appid = $wechat_array['appid'];
$this->secret = $wechat_array['secret'];


}

   public function _initialize () {
        $this->getWechat();


        $signPackage = $this->getSignPackage ();

        $this->assign ( 'signPackage', $signPackage );

cookie('openid','pengking<411913023@qq.com');
$redirecturl =  $_SERVER['REQUEST_SCHEME'] .'://'.$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'];

$this->assign('redirecturl' , $redirecturl);
        if (empty(cookie('openid'))) {
            //没有code
            if (empty($_GET['code'])) {


                $redirect_url = $_SERVER['REQUEST_SCHEME'] .'://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
                cookie('redirect_url', $redirect_url , 24 * 3600);
                //$this->redirect('Index/index');
                $redirect_url = urlencode( $redirect_url  );
                header('location:' . 'https://open.weixin.qq.com/connect/oauth2/authorize?appid='.$this->appid.'&redirect_uri='.$redirect_url.'&response_type=code&scope=snsapi_userinfo&state=123#wechat_redirect');
                exit();


            }else {


$info_array = get_user_info($this->appid , $this->secret , $_GET['code']);
cookie('openid' , $info_array['openid']);
cookie('nickname' , $info_array['nickname']);
cookie('headimgurl' , $info_array['headimgurl']);
$this->addUser($info_array);
cookie('wxinfo' , $info_array);
            }
                      
        }


        


    }


/**
* addUser 添加关注用户
* @param string $openid 微信openid
*/
protected function addUser ($data = null) {
$this->getWeChat();
if(!empty($data['openid'])){
if (!M('WechatUser')->where(array('openid' => $data['openid']))->find()) {
$data['add_time'] = NOW_TIME;
M('WechatUser')->add($data);
return true;
}


}

return true;


}

protected function deleteUser ($openid = '') {
$map['openid'] = array('eq' , "$openid");


return M('Jumin')->where($map)->delete();
}



public function valid()
{
$echoStr = $_GET["echostr"];

//valid signature , option
if($this->checkSignature()){
echo $echoStr;
exit;
}
}


public function checkSignature()
{
$signature = $_GET["signature"];
$timestamp = $_GET["timestamp"];
$nonce = $_GET["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;
}
}




//回复文本消息
public function transmitText($object,$content = ''){

$result = '';
if (!empty($content)) {

$textTpl = "<xml>
<ToUserName><![CDATA[%s]]></ToUserName>
<FromUserName><![CDATA[%s]]></FromUserName>
<CreateTime>%s</CreateTime>
<MsgType><![CDATA[text]]></MsgType>
<Content><![CDATA[%s]]></Content>
</xml>";

$result = sprintf($textTpl, $object->FromUserName, $object->ToUserName, time(), $content);

}


return $result;
}

//回复图文消息
public function transmitNews($object,$content){

if (!is_array($content)){
return ;
}
$itemTpl = "<item>
<Title><![CDATA[%s]]></Title>
<Description><![CDATA[%s]]></Description>
<PicUrl><![CDATA[%s]]></PicUrl>
<Url><![CDATA[%s]]></Url>
</item>";

$itemStr = '';
foreach ($content as $item){
$itemStr .= sprintf($itemTpl , $item['Title'] , $item['Description'] , $item['PicUrl'] , $item['Url']);
}

$newsTpl = "<xml>
<ToUserName><![CDATA[%s]]></ToUserName>
<FromUserName><![CDATA[%s]]></FromUserName>
<CreateTime>%s</CreateTime>
<MsgType><![CDATA[news]]></MsgType>
<ArticleCount>%s</ArticleCount>
<Articles>
$itemStr
</Articles>
</xml> ";

$result = sprintf ($newsTpl , $object->FromUserName, $object->ToUserName, time(), count($content));

return $result;
}

//回复音乐消息
public function transmitMusic($object , $content){

$itemTpl ="<Music>
<Title><![CDATA[%s]]></Title>
<Description><![CDATA[%s]]></Description>
<MusicUrl><![CDATA[%s]]></MusicUrl>
<HQMusicUrl><![CDATA[%s]]></HQMusicUrl>
</Music>";
$itemStr = sprintf($itemTpl , $content['Title'],$content['Description'], $content['MusicUrl'] , $content['HQMusicUrl']);

$musicTpl ="<xml>
<ToUserName><![CDATA[%s]]></ToUserName>
<FromUserName><![CDATA[%s]]></FromUserName>
<CreateTime>%s</CreateTime>
<MsgType><![CDATA[music]]></MsgType>
$itemStr
</xml>";

$result = sprintf($musicTpl, $object->FromUserName, $object->ToUserName, time());
return $result;
}

//回复图片消息
public function transmitImage($object , $content){
$imageTpl ="<xml>
<ToUserName><![CDATA[%s]]></ToUserName>
<FromUserName><![CDATA[%s]]></FromUserName>
<CreateTime>%s</CreateTime>
<MsgType><![CDATA[image]]></MsgType>
<Image>
<MediaId><![CDATA[%s]]></MediaId>
</Image>
</xml>";

$result = sprintf($imageTpl , $object->FromUserName, $object->ToUserName, time() , $content['MediaId']);

return $result;
}

//回复语音消息
public function transmitVoice($object , $content){

$voiceTpl = "<xml>
<ToUserName><![CDATA[%s]]></ToUserName>
<FromUserName><![CDATA[%s]]></FromUserName>
<CreateTime>%s</CreateTime>
<MsgType><![CDATA[voice]]></MsgType>
<Voice>
<MediaId><![CDATA[%s]]></MediaId>
</Voice>
</xml>";

$result = sprintf ($voiceTpl , $object->FromUserName, $object->ToUserName, time() , $content['MediaId']);

return $result;

}

//回复视频消息
public function transmitVideo($object, $videoArray)
{
$itemTpl = "<Video>
<MediaId><![CDATA[%s]]></MediaId>
<ThumbMediaId><![CDATA[%s]]></ThumbMediaId>
<Title><![CDATA[%s]]></Title>
<Description><![CDATA[%s]]></Description>
</Video>";

        $item_str = sprintf($itemTpl, $videoArray['MediaId'], $videoArray['ThumbMediaId'], $videoArray['Title'], $videoArray['Description']);

        $textTpl = "<xml>
        <ToUserName><![CDATA[%s]]></ToUserName>
        <FromUserName><![CDATA[%s]]></FromUserName>
        <CreateTime>%s</CreateTime>
        <MsgType><![CDATA[video]]></MsgType>
        $item_str
        </xml>";

        $result = sprintf($textTpl, $object->FromUserName, $object->ToUserName, time());
        return $result;
}

回复多客服消息
public function transmitService($object) {


$textTpl = "<xml>
<ToUserName><![CDATA[%s]]></ToUserName>
<FromUserName><![CDATA[%s]]></FromUserName>
<CreateTime>%s</CreateTime>
<MsgType><![CDATA[transfer_customer_service]]></MsgType>
</xml>";
$result = sprintf($textTpl, $object->FromUserName, $object->ToUserName, time());
return $result;
}

回复多客服消息(给指定客服)
public function transmitSpecifyService($object , $user) {


$textTpl = "<xml>
<ToUserName><![CDATA[%s]]></ToUserName>
<FromUserName><![CDATA[%s]]></FromUserName>
<CreateTime>%s</CreateTime>
<MsgType><![CDATA[transfer_customer_service]]></MsgType>
<TransInfo>
       <KfAccount>%s</KfAccount>
   </TransInfo>
</xml>";
$result = sprintf($textTpl, $object->FromUserName, $object->ToUserName, time(),$user);
return $result;
}

public function transmitServiceText($openid , $content) {

$data = '{
   "touser":"'.$openid.'",
   "msgtype":"text",
   "text":
   {
        "content":"'.$content.'"
   }
}';

$access_token = get_access_token($this->appid  , $this->secret);

$url = 'https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token='.$access_token;

http_request($url,$data);
}




public function getSignPackage() {
   $jsapiTicket = $this->getJsApiTicket();
//dump($jsapiTicket);
   // 注意 URL 一定要动态获取,不能 hardcode.
   $protocol = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off' || $_SERVER['SERVER_PORT'] == 443) ? "https://" : "http://";
   $url = "$protocol$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";


   $timestamp = time();
   $nonceStr = $this->createNonceStr();


   // 这里参数的顺序要按照 key 值 ASCII 码升序排序
   $string = "jsapi_ticket=$jsapiTicket&noncestr=$nonceStr&timestamp=$timestamp&url=$url";

   $signature = sha1($string);


   $signPackage = array(
     "appId"     => $this->appid,
     "nonceStr"  => $nonceStr,
     "timestamp" => $timestamp,
     "url"       => $url,
     "signature" => $signature,
     "rawString" => $string
   );
   
   return $signPackage; 
 }


 protected function createNonceStr($length = 16) {
   $chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
   $str = "";
   for ($i = 0; $i < $length; $i++) {
     $str .= substr($chars, mt_rand(0, strlen($chars) - 1), 1);
   }
   return $str;
 }


 private function getJsApiTicket() {
   // jsapi_ticket 应该全局存储与更新,以下代码以写入到文件中做示例
   $data = json_decode(S($appid . '_jsapi_ticket'));

   if ($data->expire_time < time()) {
     $accessToken = $this->getAccessToken();
     // 如果是企业号用以下 URL 获取 ticket
     // $url = "https://qyapi.weixin.qq.com/cgi-bin/get_jsapi_ticket?access_token=$accessToken";
     $url = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?type=jsapi&access_token=$accessToken";
     $res = json_decode($this->httpGet($url));
     $ticket = $res->ticket;
     if ($ticket) {
       S($appid . '_jsapi_ticket' , $ticket , 7000);
     }
   } else {
     $ticket = $data->jsapi_ticket;
   }


   return $ticket;
 }


 private function getAccessToken() {
   
$this->getWeChat();
   return get_access_token($this->appid,$this->secret);

 }


 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;
 }  


}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值