PHP封裝的微信公眾平臺接口開發(fā)操作類完整示例
本文實(shí)例講述了PHP封裝的微信公眾平臺接口開發(fā)操作類。分享給大家供大家參考,具體如下:
示例調(diào)用 index.php
<?php
/**
* Author: 惹妹子生氣了
* Date: 2017-08-10
*/
class MpWeixin
{
public $config;
public $class_obj;
public $is_check_signature = false;
public function __construct()
{
//獲取配置
$this->config = array('appid'=>'dfdfdfdfdf', 'secret'=>'343434343434');
$echostr = isset($_GET['echostr']) ? $_GET['echostr'] : ''; // 是否來自于微信的服務(wù)器配置驗(yàn)證
if ($echostr) {
$this->is_check_signature = true;
}else{
$this->is_check_signature = false;
include_once "mpweixin.class.php";
$this->class_obj = new mpweixin($this->config); //實(shí)例化對應(yīng)的插件
}
}
/**
* 服務(wù)器地址(用戶消息和開發(fā)者需要的事件推送,會被轉(zhuǎn)發(fā)到該URL中)
*/
public function index()
{
if ($this->is_check_signature) {
$this->valid();
}else{
$this->class_obj->responseMsg();
}
}
/**
* 開發(fā)者對簽名(即signature)的效驗(yàn),來判斷此條消息的真實(shí)性
*/
public function valid()
{
$echoStr = $this->checkSignature();
if($echoStr){
header('content-type:text');
exit($echoStr);
}
}
/**
* 驗(yàn)證是否來自于微信
* @return [type] [description]
*/
public function checkSignature()
{
//微信會發(fā)送4個參數(shù)到我們的服務(wù)器后臺 簽名 時間戳 隨機(jī)字符串 隨機(jī)數(shù)
$signature = $_GET['signature']; // 簽名
$timestamp = $_GET['timestamp']; // 時間戳
$echoStr = $_GET['echostr']; // 隨機(jī)字符串
$nonce = $_GET['nonce']; // 隨機(jī)數(shù)
if ($signature && $timestamp && $echoStr && $nonce) {
// 微信公眾號基本配置中的token
$token = TOKEN;
//將token、timestamp、nonce按字典序排序
$tmpArr = array($token, $timestamp, $nonce);
sort($tmpArr, SORT_STRING);
// 將三個參數(shù)字符串拼接成一個字符串進(jìn)行sha1加密
$tmpStr = implode($tmpArr);
$tmpStr = sha1($tmpStr);
// 開發(fā)者獲得加密后的字符串可與signature對比,標(biāo)識該請求來源于微信
if($tmpStr == $signature){
return $echoStr;
} else {
return false;
}
}
}
}
?>
PHP類文件 mpweixin.class.php
<?php
/*
* 微信公眾號插件
* 開發(fā)者模式,請先注冊微信開放平臺賬號,然后啟動開發(fā)模式
*/
class mpweixin{
public $appid;
public $secret;
public function __construct($config){
$this->appid = $config['appid'];
$this->secret = $config['secret'];
}
/* ----------------------------------響應(yīng)----------------------------- */
/**
* 響應(yīng)消息
*/
public function responseMsg()
{
$postStr = file_get_contents("php://input");
if (!empty($postStr)){
$this->logger("R \r\n".$postStr);
$postObj = simplexml_load_string($postStr, 'SimpleXMLElement', LIBXML_NOCDATA);
$RX_TYPE = trim($postObj->MsgType);
switch ($RX_TYPE)
{
// 事件
case "event":
$result = $this->receiveEvent($postObj);
break;
// 文本
case "text":
if (strstr($postObj->Content, "第三方")){
$result = $this->relayPart3("http://www.fangbei.org/test.php".'?'.$_SERVER['UERY_STRING';], $postStr);
}else{
$result = $this->receiveText($postObj);
}
break;
// 圖片
case "image":
$result = $this->receiveImage($postObj);
break;
// 地理位置
case "location":
$result = $this->receiveLocation($postObj);
break;
// 語音
case "voice":
$result = $this->receiveVoice($postObj);
break;
// 視頻
case "video":
$result = $this->receiveVideo($postObj);
break;
// 鏈接
case "link":
$result = $this->receiveLink($postObj);
break;
default:
$result = "unknown msg type: ".$RX_TYPE;
break;
}
$this->logger("T \r\n".$result);
echo $result;
}else {
echo "";
exit;
}
}
/* ----------------------------------接收----------------------------- */
/**
* 接收事件消息
*/
private function receiveEvent($object)
{
$content = "";
switch ($object->Event)
{
// 關(guān)注時的事件推送
case "subscribe":
$content = "歡迎關(guān)注方倍工作室";
$content .= (!empty($object->EventKey)) ? ("\n來自二維碼場景".str_replace("qrscene_","",$object->EventKey)) : "";
break;
// 取消關(guān)注事件
case "unsubscribe":
$content = "取消關(guān)注";
break;
// 點(diǎn)擊菜單拉取消息時的事件推送
case "CLICK":
switch ($object->EventKey)
{
case "COMPANY":
$content = array();
$content[] = array("Title"=>"方倍工作室", "Description"=>"", "PicUrl"=>"http://discuz.comli.com/weixin/weather/icon/cartoon.jpg";, "Url" =>"http://m.cnblogs.com/?u=txw1958";);
break;
default:
$content = "點(diǎn)擊菜單:".$object->EventKey;
break;
}
break;
// 點(diǎn)擊菜單跳轉(zhuǎn)鏈接時的事件推送
case "VIEW":
$content = "跳轉(zhuǎn)鏈接 ".$object->EventKey;
break;
// 掃描帶參數(shù)二維碼場景,用戶已關(guān)注時的事件推送
case "SCAN":
$content = "掃描場景 ".$object->EventKey;
break;
// 上報地理位置事件
case "LOCATION":
$content = "上傳位置:緯度 ".$object->Latitude.";經(jīng)度 ".$object->Longitude;
break;
// 掃碼推事件且彈出“消息接收中”提示框的事件推送
case "scancode_waitmsg":
if ($object->ScanCodeInfo->ScanType == "qrcode"){
$content = "掃碼帶提示:類型 二維碼 結(jié)果:".$object->ScanCodeInfo->ScanResult;
}else if ($object->ScanCodeInfo->ScanType == "barcode"){
$codeinfo = explode(",",strval($object->ScanCodeInfo->ScanResult));
$codeValue = $codeinfo[1];
$content = "掃碼帶提示:類型 條形碼 結(jié)果:".$codeValue;
}else{
$content = "掃碼帶提示:類型 ".$object->ScanCodeInfo->ScanType." 結(jié)果:".$object->ScanCodeInfo->ScanResult;
}
break;
// 掃碼推事件的事件推送
case "scancode_push":
$content = "掃碼推事件";
break;
// 彈出系統(tǒng)拍照發(fā)圖的事件推送
case "pic_sysphoto":
$content = "系統(tǒng)拍照";
break;
// 彈出微信相冊發(fā)圖器的事件推送
case "pic_weixin":
$content = "相冊發(fā)圖:數(shù)量 ".$object->SendPicsInfo->Count;
break;
// 彈出拍照或者相冊發(fā)圖的事件推送
case "pic_photo_or_album":
$content = "拍照或者相冊:數(shù)量 ".$object->SendPicsInfo->Count;
break;
// 彈出地理位置選擇器的事件推送
case "location_select":
$content = "發(fā)送位置:標(biāo)簽 ".$object->SendLocationInfo->Label;
break;
default:
$content = "receive a new event: ".$object->Event;
break;
}
if(is_array($content)){
if (isset($content[0]['PicUrl'])){
$result = $this->transmitNews($object, $content);
}else if (isset($content['MusicUrl'])){
$result = $this->transmitMusic($object, $content);
}
}else{
$result = $this->transmitText($object, $content);
}
return $result;
}
/**
* 接收文本消息
*/
private function receiveText($object)
{
$keyword = trim($object->Content);
//多客服人工回復(fù)模式
if (strstr($keyword, "請問在嗎") || strstr($keyword, "在線客服")){
$result = $this->transmitService($object);
return $result;
}
//自動回復(fù)模式
if (strstr($keyword, "文本")){
$content = "這是個文本消息";
}else if (strstr($keyword, "表情")){
$content = "中國:".$this->bytes_to_emoji(0x1F1E8).$this->bytes_to_emoji(0x1F1F3)."\n仙人掌:".$this->bytes_to_emoji(0x1F335);
}else if (strstr($keyword, "單圖文")){
$content = array();
$content[] = array("Title"=>"單圖文標(biāo)題", "Description"=>"單圖文內(nèi)容", "PicUrl"=>"http://discuz.comli.com/weixin/weather/icon/cartoon.jpg";, "Url" =>"http://m.cnblogs.com/?u=txw1958";);
}else if (strstr($keyword, "圖文") || strstr($keyword, "多圖文")){
$content = array();
$content[] = array("Title"=>"多圖文1標(biāo)題", "Description"=>"", "PicUrl"=>"http://discuz.comli.com/weixin/weather/icon/cartoon.jpg";, "Url" =>"http://m.cnblogs.com/?u=txw1958";);
$content[] = array("Title"=>"多圖文2標(biāo)題", "Description"=>"", "PicUrl"=>"http://d.hiphotos.bdimg.com/wisegame/pic/item/f3529822720e0cf3ac9f1ada0846f21fbe09aaa3.jpg";, "Url" =>"http://m.cnblogs.com/?u=txw1958";);
$content[] = array("Title"=>"多圖文3標(biāo)題", "Description"=>"", "PicUrl"=>"http://g.hiphotos.bdimg.com/wisegame/pic/item/18cb0a46f21fbe090d338acc6a600c338644adfd.jpg";, "Url" =>"http://m.cnblogs.com/?u=txw1958";);
}else if (strstr($keyword, "音樂")){
$content = array();
$content = array("Title"=>"最炫民族風(fēng)", "Description"=>"歌手:鳳凰傳奇", "MusicUrl"=>"http://121.199.4.61/music/zxmzf.mp3";, "HQMusicUrl"=>"http://121.199.4.61/music/zxmzf.mp3";);
}else{
$content = date("Y-m-d H:i:s",time())."\nOpenID:".$object->FromUserName."\n技術(shù)支持 方倍工作室";
}
if(is_array($content)){
if (isset($content[0])){
$result = $this->transmitNews($object, $content);
}else if (isset($content['MusicUrl'])){
$result = $this->transmitMusic($object, $content);
}
}else{
$result = $this->transmitText($object, $content);
}
return $result;
}
/**
* 接收圖片消息
*/
private function receiveImage($object)
{
$content = array("MediaId"=>$object->MediaId);
$result = $this->transmitImage($object, $content);
return $result;
}
/**
* 接收位置消息
*/
private function receiveLocation($object)
{
$content = "你發(fā)送的是位置,經(jīng)度為:".$object->Location_Y.";緯度為:".$object->Location_X.";縮放級別為:".$object->Scale.";位置為:".$object->Label;
$result = $this->transmitText($object, $content);
return $result;
}
/**
* 接收語音消息
*/
private function receiveVoice($object)
{
if (isset($object->Recognition) && !empty($object->Recognition)){
$content = "你剛才說的是:".$object->Recognition;
$result = $this->transmitText($object, $content);
}else{
$content = array("MediaId"=>$object->MediaId);
$result = $this->transmitVoice($object, $content);
}
return $result;
}
/**
* 接收視頻消息
*/
private function receiveVideo($object)
{
$content = array("MediaId"=>$object->MediaId, "ThumbMediaId"=>$object->ThumbMediaId, "Title"=>"", "Description"=>"");
$result = $this->transmitVideo($object, $content);
return $result;
}
/**
* 接收鏈接消息
*/
private function receiveLink($object)
{
$content = "你發(fā)送的是鏈接,標(biāo)題為:".$object->Title.";內(nèi)容為:".$object->Description.";鏈接地址為:".$object->Url;
$result = $this->transmitText($object, $content);
return $result;
}
/* ----------------------------------回復(fù)----------------------------- */
/**
* 回復(fù)文本消息
*/
private function transmitText($object, $content)
{
if (!isset($content) || empty($content)){
return "";
}
$xmlTpl = "<xml>
<ToUserName><![CDATA[%s]]></ToUserName>
<FromUserName><![CDATA[%s]]></FromUserName>
<CreateTime>%s</CreateTime>
<MsgType><![CDATA[text]]></MsgType>
<Content><![CDATA[%s]]></Content>
</xml>";
$result = sprintf($xmlTpl, $object->FromUserName, $object->ToUserName, time(), $content);
return $result;
}
/**
* 回復(fù)多客服消息
*/
private function transmitService($object)
{
$xmlTpl = "<xml>
<ToUserName><![CDATA[%s]]></ToUserName>
<FromUserName><![CDATA[%s]]></FromUserName>
<CreateTime>%s</CreateTime>
<MsgType><![CDATA[transfer_customer_service]]></MsgType>
</xml>";
$result = sprintf($xmlTpl, $object->FromUserName, $object->ToUserName, time());
return $result;
}
/**
* 回復(fù)圖文消息
*/
private function transmitNews($object, $newsArray)
{
if(!is_array($newsArray)){
return "";
}
$itemTpl = "<item>
<Title><![CDATA[%s]]></Title>
<Description><![CDATA[%s]]></Description>
<PicUrl><![CDATA[%s]]></PicUrl>
<Url><![CDATA[%s]]></Url>
</item>";
$item_str = "";
foreach ($newsArray as $item){
$item_str .= sprintf($itemTpl, $item['Title'], $item['Description'], $item['PicUrl'], $item['Url']);
}
$xmlTpl = "<xml>
<ToUserName><![CDATA[%s]]></ToUserName>
<FromUserName><![CDATA[%s]]></FromUserName>
<CreateTime>%s</CreateTime>
<MsgType><![CDATA[news]]></MsgType>
<ArticleCount>%s</ArticleCount>
<Articles>$item_str</Articles>
</xml>";
$result = sprintf($xmlTpl, $object->FromUserName, $object->ToUserName, time(), count($newsArray));
return $result;
}
/**
* 回復(fù)音樂消息
*/
private function transmitMusic($object, $musicArray)
{
if(!is_array($musicArray)){
return "";
}
$itemTpl = "<Music>
<Title><![CDATA[%s]]></Title>
<Description><![CDATA[%s]]></Description>
<MusicUrl><![CDATA[%s]]></MusicUrl>
<HQMusicUrl><![CDATA[%s]]></HQMusicUrl>
</Music>";
$item_str = sprintf($itemTpl, $musicArray['Title'], $musicArray['Description'], $musicArray['MusicUrl'], $musicArray['HQMusicUrl']);
$xmlTpl = "<xml>
<ToUserName><![CDATA[%s]]></ToUserName>
<FromUserName><![CDATA[%s]]></FromUserName>
<CreateTime>%s</CreateTime>
<MsgType><![CDATA[music]]></MsgType>
$item_str
</xml>";
$result = sprintf($xmlTpl, $object->FromUserName, $object->ToUserName, time());
return $result;
}
/**
* 回復(fù)圖片消息
*/
private function transmitImage($object, $imageArray)
{
$itemTpl = "<Image>
<MediaId><![CDATA[%s]]></MediaId>
</Image>";
$item_str = sprintf($itemTpl, $imageArray['MediaId']);
$xmlTpl = "<xml>
<ToUserName><![CDATA[%s]]></ToUserName>
<FromUserName><![CDATA[%s]]></FromUserName>
<CreateTime>%s</CreateTime>
<MsgType><![CDATA[image]]></MsgType>
$item_str
</xml>";
$result = sprintf($xmlTpl, $object->FromUserName, $object->ToUserName, time());
return $result;
}
/**
* 回復(fù)語音消息
*/
private function transmitVoice($object, $voiceArray)
{
$itemTpl = "<Voice>
<MediaId><![CDATA[%s]]></MediaId>
</Voice>";
$item_str = sprintf($itemTpl, $voiceArray['MediaId']);
$xmlTpl = "<xml>
<ToUserName><![CDATA[%s]]></ToUserName>
<FromUserName><![CDATA[%s]]></FromUserName>
<CreateTime>%s</CreateTime>
<MsgType><![CDATA[voice]]></MsgType>
$item_str
</xml>";
$result = sprintf($xmlTpl, $object->FromUserName, $object->ToUserName, time());
return $result;
}
/**
* 回復(fù)視頻消息
*/
private 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']);
$xmlTpl = "<xml>
<ToUserName><![CDATA[%s]]></ToUserName>
<FromUserName><![CDATA[%s]]></FromUserName>
<CreateTime>%s</CreateTime>
<MsgType><![CDATA[video]]></MsgType>
$item_str
</xml>";
$result = sprintf($xmlTpl, $object->FromUserName, $object->ToUserName, time());
return $result;
}
/* ----------------------------------通用----------------------------- */
/**
* 回復(fù)第三方接口消息
*/
private function relayPart3($url, $rawData)
{
$headers = array("Content-Type: text/xml; charset=utf-8");
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $rawData);
$output = curl_exec($ch);
curl_close($ch);
return $output;
}
/**
* 字節(jié)轉(zhuǎn)Emoji表情
*/
function bytes_to_emoji($cp)
{
if ($cp > 0x10000){ # 4 bytes
return chr(0xF0 | (($cp & 0x1C0000) >> 18)).chr(0x80 | (($cp & 0x3F000) >> 12)).chr(0x80 | (($cp & 0xFC0) >> 6)).chr(0x80 | ($cp & 0x3F));
}else if ($cp > 0x800){ # 3 bytes
return chr(0xE0 | (($cp & 0xF000) >> 12)).chr(0x80 | (($cp & 0xFC0) >> 6)).chr(0x80 | ($cp & 0x3F));
}else if ($cp > 0x80){ # 2 bytes
return chr(0xC0 | (($cp & 0x7C0) >> 6)).chr(0x80 | ($cp & 0x3F));
}else{ # 1 byte
return chr($cp);
}
}
/**
* 日志記錄
*/
private function logger($log_content)
{
if (isset($_SERVER['HTTP_APPNAME'])) { //SAE
sae_set_display_errors(false);
sae_debug($log_content);
sae_set_display_errors(true);
} else if ($_SERVER['REMOTE_ADDR'] != "127.0.0.1") { //LOCAL
$max_size = 1000000;
$log_filename = "mpweixin.log.xml";
if (file_exists($log_filename) and (abs(filesize($log_filename)) > $max_size)) {
unlink($log_filename);
}
file_put_contents($log_filename, date('Y-m-d H:i:s')." ".$log_content."\r\n", FILE_APPEND);
}
}
/**
* 獲取access_token
*/
private function getAccessToken()
{
$token_url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid="; . $this->appid . "&secret=" . $this->secret;
$response = $this->get_contents($token_url);
$params = array();
$params = json_decode($response,true);
if (isset($params['errcode']))
{
echo "<h3>error:</h3>" . $params['errcode'];
echo "<h3>msg :</h3>" . $params['errmsg'];
exit;
}
return $params['access_token'];
}
public function get_contents($url){
$ch = curl_init();
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($ch, CURLOPT_URL, $url);
$response = curl_exec($ch);
curl_close($ch);
//-------請求為空
if(empty($response)){
exit("50001");
}
return $response;
}
}
?>
更多關(guān)于PHP相關(guān)內(nèi)容感興趣的讀者可查看本站專題:《PHP微信開發(fā)技巧匯總》、《PHP編碼與轉(zhuǎn)碼操作技巧匯總》、《PHP網(wǎng)絡(luò)編程技巧總結(jié)》、《php字符串(string)用法總結(jié)》、《PHP中json格式數(shù)據(jù)操作技巧匯總》及《PHP針對XML文件操作技巧總結(jié)》
希望本文所述對大家PHP程序設(shè)計有所幫助。
- 微信小程序開發(fā)之獲取用戶手機(jī)號碼(php接口解密)
- ThinkPHP框架實(shí)現(xiàn)的微信支付接口開發(fā)完整示例
- php獲取微信基礎(chǔ)接口憑證Access_token
- thinkPHP微信分享接口JSSDK用法實(shí)例
- 詳解使用php調(diào)用微信接口上傳永久素材
- PHP實(shí)現(xiàn)微信JS-SDK接口選擇相冊及拍照并上傳的方法
- php微信高級接口調(diào)用方法(自定義菜單接口、客服接口、二維碼)
- PHP配合微信小程序?qū)崿F(xiàn)獲取手機(jī)號碼詳解
- 微信小程序結(jié)合ThinkPHP5授權(quán)登陸后獲取手機(jī)號
- PHP請求微信接口獲取用戶電話號功能示例
相關(guān)文章
php中對xml讀取的相關(guān)函數(shù)的介紹一
php中對xml讀取的相關(guān)函數(shù)的介紹整理如下2008-06-06
PHP中對用戶身份認(rèn)證實(shí)現(xiàn)兩種方法
用戶在設(shè)計和維護(hù)站點(diǎn)的時候,經(jīng)常需要限制對某些重要文件或信息的訪問。通常,我們可以采用內(nèi)置于WEB服務(wù)器的基于HTTP協(xié)議的用戶身份驗(yàn)證機(jī)制。2011-06-06
Linux下實(shí)現(xiàn)PHP多進(jìn)程的方法分享
PHP多進(jìn)程:使用PHP的Process Control Functions(PCNTL/線程控制函數(shù)),需要的朋友可以參考下2012-08-08
PHP JSON格式數(shù)據(jù)交互實(shí)例代碼詳解
此前我寫了不少在PHP網(wǎng)站開發(fā)中應(yīng)用XML進(jìn)行數(shù)據(jù)交互的實(shí)例,這兩天通過PHP解析JSON并進(jìn)行交互的實(shí)例學(xué)習(xí)和了解了JSON在PHP中的應(yīng)用,感覺非常方便。2011-01-01

