PHP使用Face++接口開發(fā)微信公眾平臺人臉識別系統(tǒng)的方法
本文實(shí)例講述了PHP使用Face++接口開發(fā)微信公眾平臺人臉識別系統(tǒng)的方法。分享給大家供大家參考。具體如下:
效果圖如下:


具體步驟如下:
首先,先登錄Face++的官網(wǎng)注冊賬號:官網(wǎng)鏈接
注冊之后會獲取到api_secret和api_key,這些在調(diào)用接口的時(shí)候需要用到。
然后接下來的就是使用PHP腳本調(diào)用API了。
在使用PHP開發(fā)微信公共平臺的時(shí)候,推薦使用Github上的一款不錯的框架:wechat-php-sdk
對于微信的常用接口做了一些封裝,核心文件wechat.class.php如下:
<?php
/**
* 微信公眾平臺PHP-SDK, 官方API部分
* @author dodge <dodgepudding@gmail.com>
* @link https://github.com/dodgepudding/wechat-php-sdk
* @version 1.2
* usage:
* $options = array(
* 'token'=>'tokenaccesskey', //填寫你設(shè)定的key
* 'appid'=>'wxdk1234567890', //填寫高級調(diào)用功能的app id
* 'appsecret'=>'xxxxxxxxxxxxxxxxxxx', //填寫高級調(diào)用功能的密鑰
* );
* $weObj = new Wechat($options);
* $weObj->valid();
* $type = $weObj->getRev()->getRevType();
* switch($type) {
* case Wechat::MSGTYPE_TEXT:
* $weObj->text("hello, I'm wechat")->reply();
* exit;
* break;
* case Wechat::MSGTYPE_EVENT:
* ....
* break;
* case Wechat::MSGTYPE_IMAGE:
* ...
* break;
* default:
* $weObj->text("help info")->reply();
* }
* //獲取菜單操作:
* $menu = $weObj->getMenu();
* //設(shè)置菜單
* $newmenu = array(
* "button"=>
* array(
* array('type'=>'click','name'=>'最新消息','key'=>'MENU_KEY_NEWS'),
* array('type'=>'view','name'=>'我要搜索','url'=>'http://www.baidu.com'),
* )
* );
* $result = $weObj->createMenu($newmenu);
*/
class Wechat
{
const MSGTYPE_TEXT = 'text';
const MSGTYPE_IMAGE = 'image';
const MSGTYPE_LOCATION = 'location';
const MSGTYPE_LINK = 'link';
const MSGTYPE_EVENT = 'event';
const MSGTYPE_MUSIC = 'music';
const MSGTYPE_NEWS = 'news';
const MSGTYPE_VOICE = 'voice';
const MSGTYPE_VIDEO = 'video';
const API_URL_PREFIX = 'https://api.weixin.qq.com/cgi-bin';
const AUTH_URL = '/token?grant_type=client_credential&';
const MENU_CREATE_URL = '/menu/create?';
const MENU_GET_URL = '/menu/get?';
const MENU_DELETE_URL = '/menu/delete?';
const MEDIA_GET_URL = '/media/get?';
const QRCODE_CREATE_URL='/qrcode/create?';
const QR_SCENE = 0;
const QR_LIMIT_SCENE = 1;
const QRCODE_IMG_URL='https://mp.weixin.qq.com/cgi-bin/showqrcode?ticket=';
const USER_GET_URL='/user/get?';
const USER_INFO_URL='/user/info?';
const GROUP_GET_URL='/groups/get?';
const GROUP_CREATE_URL='/groups/create?';
const GROUP_UPDATE_URL='/groups/update?';
const GROUP_MEMBER_UPDATE_URL='/groups/members/update?';
const CUSTOM_SEND_URL='/message/custom/send?';
const OAUTH_PREFIX = 'https://open.weixin.qq.com/connect/oauth2';
const OAUTH_AUTHORIZE_URL = '/authorize?';
const OAUTH_TOKEN_PREFIX = 'https://api.weixin.qq.com/sns/oauth2';
const OAUTH_TOKEN_URL = '/access_token?';
const OAUTH_REFRESH_URL = '/refresh_token?';
const OAUTH_USERINFO_URL = 'https://api.weixin.qq.com/sns/userinfo?';
private $token;
private $appid;
private $appsecret;
private $access_token;
private $user_token;
private $_msg;
private $_funcflag = false;
private $_receive;
public $debug = false;
public $errCode = 40001;
public $errMsg = "no access";
private $_logcallback;
public function __construct($options)
{
$this->token = isset($options['token'])?$options['token']:'';
$this->appid = isset($options['appid'])?$options['appid']:'';
$this->appsecret = isset($options['appsecret'])?$options['appsecret']:'';
$this->debug = isset($options['debug'])?$options['debug']:false;
$this->_logcallback = isset($options['logcallback'])?$options['logcallback']:false;
}
/**
* For weixin server validation
*/
private function checkSignature()
{
$signature = isset($_GET["signature"])?$_GET["signature"]:'';
$timestamp = isset($_GET["timestamp"])?$_GET["timestamp"]:'';
$nonce = isset($_GET["nonce"])?$_GET["nonce"]:'';
$token = $this->token;
$tmpArr = array($token, $timestamp, $nonce);
sort($tmpArr, SORT_STRING);
$tmpStr = implode( $tmpArr );
$tmpStr = sha1( $tmpStr );
if( $tmpStr == $signature ){
return true;
}else{
return false;
}
}
/**
* For weixin server validation
* @param bool $return 是否返回
*/
public function valid($return=false)
{
$echoStr = isset($_GET["echostr"]) ? $_GET["echostr"]: '';
if ($return) {
if ($echoStr) {
if ($this->checkSignature())
return $echoStr;
else
return false;
} else
return $this->checkSignature();
} else {
if ($echoStr) {
if ($this->checkSignature())
die($echoStr);
else
die('no access');
} else {
if ($this->checkSignature())
return true;
else
die('no access');
}
}
return false;
}
/**
* 設(shè)置發(fā)送消息
* @param array $msg 消息數(shù)組
* @param bool $append 是否在原消息數(shù)組追加
*/
public function Message($msg = '',$append = false){
if (is_null($msg)) {
$this->_msg =array();
}elseif (is_array($msg)) {
if ($append)
$this->_msg = array_merge($this->_msg,$msg);
else
$this->_msg = $msg;
return $this->_msg;
} else {
return $this->_msg;
}
}
public function setFuncFlag($flag) {
$this->_funcflag = $flag;
return $this;
}
private function log($log){
if ($this->debug && function_exists($this->_logcallback)) {
if (is_array($log)) $log = print_r($log,true);
return call_user_func($this->_logcallback,$log);
}
}
/**
* 獲取微信服務(wù)器發(fā)來的信息
*/
public function getRev()
{
if ($this->_receive) return $this;
$postStr = file_get_contents("php://input");
$this->log($postStr);
if (!empty($postStr)) {
$this->_receive = (array)simplexml_load_string($postStr, 'SimpleXMLElement', LIBXML_NOCDATA);
}
return $this;
}
/**
* 獲取微信服務(wù)器發(fā)來的信息
*/
public function getRevData()
{
return $this->_receive;
}
/**
* 獲取消息發(fā)送者
*/
public function getRevFrom() {
if (isset($this->_receive['FromUserName']))
return $this->_receive['FromUserName'];
else
return false;
}
/**
* 獲取消息接受者
*/
public function getRevTo() {
if (isset($this->_receive['ToUserName']))
return $this->_receive['ToUserName'];
else
return false;
}
/**
* 獲取接收消息的類型
*/
public function getRevType() {
if (isset($this->_receive['MsgType']))
return $this->_receive['MsgType'];
else
return false;
}
/**
* 獲取消息ID
*/
public function getRevID() {
if (isset($this->_receive['MsgId']))
return $this->_receive['MsgId'];
else
return false;
}
/**
* 獲取消息發(fā)送時(shí)間
*/
public function getRevCtime() {
if (isset($this->_receive['CreateTime']))
return $this->_receive['CreateTime'];
else
return false;
}
/**
* 獲取接收消息內(nèi)容正文
*/
public function getRevContent(){
if (isset($this->_receive['Content']))
return $this->_receive['Content'];
else if (isset($this->_receive['Recognition'])) //獲取語音識別文字內(nèi)容,需申請開通
return $this->_receive['Recognition'];
else
return false;
}
/**
* 獲取接收消息圖片
*/
public function getRevPic(){
if (isset($this->_receive['PicUrl']))
return $this->_receive['PicUrl'];
else
return false;
}
/**
* 獲取接收消息鏈接
*/
public function getRevLink(){
if (isset($this->_receive['Url'])){
return array(
'url'=>$this->_receive['Url'],
'title'=>$this->_receive['Title'],
'description'=>$this->_receive['Description']
);
} else
return false;
}
/**
* 獲取接收地理位置
*/
public function getRevGeo(){
if (isset($this->_receive['Location_X'])){
return array(
'x'=>$this->_receive['Location_X'],
'y'=>$this->_receive['Location_Y'],
'scale'=>$this->_receive['Scale'],
'label'=>$this->_receive['Label']
);
} else
return false;
}
/**
* 獲取接收事件推送
*/
public function getRevEvent(){
if (isset($this->_receive['Event'])){
return array(
'event'=>$this->_receive['Event'],
'key'=>$this->_receive['EventKey'],
);
} else
return false;
}
/**
* 獲取接收語言推送
*/
public function getRevVoice(){
if (isset($this->_receive['MediaId'])){
return array(
'mediaid'=>$this->_receive['MediaId'],
'format'=>$this->_receive['Format'],
);
} else
return false;
}
/**
* 獲取接收視頻推送
*/
public function getRevVideo(){
if (isset($this->_receive['MediaId'])){
return array(
'mediaid'=>$this->_receive['MediaId'],
'thumbmediaid'=>$this->_receive['ThumbMediaId']
);
} else
return false;
}
/**
* 獲取接收TICKET
*/
public function getRevTicket(){
if (isset($this->_receive['Ticket'])){
return $this->_receive['Ticket'];
} else
return false;
}
/**
* 獲取二維碼的場景值
*/
public function getRevSceneId (){
if (isset($this->_receive['EventKey'])){
return str_replace('qrscene_','',$this->_receive['EventKey']);
} else{
return false;
}
}
public static function xmlSafeStr($str)
{
return '<![CDATA['.preg_replace("/[\\x00-\\x08\\x0b-\\x0c\\x0e-\\x1f]/",'',$str).']]>';
}
/**
* 數(shù)據(jù)XML編碼
* @param mixed $data 數(shù)據(jù)
* @return string
*/
public static function data_to_xml($data) {
$xml = '';
foreach ($data as $key => $val) {
is_numeric($key) && $key = "item id=\"$key\"";
$xml .= "<$key>";
$xml .= ( is_array($val) || is_object($val)) ? self::data_to_xml($val) : self::xmlSafeStr($val);
list($key, ) = explode(' ', $key);
$xml .= "</$key>";
}
return $xml;
}
/**
* XML編碼
* @param mixed $data 數(shù)據(jù)
* @param string $root 根節(jié)點(diǎn)名
* @param string $item 數(shù)字索引的子節(jié)點(diǎn)名
* @param string $attr 根節(jié)點(diǎn)屬性
* @param string $id 數(shù)字索引子節(jié)點(diǎn)key轉(zhuǎn)換的屬性名
* @param string $encoding 數(shù)據(jù)編碼
* @return string
*/
public function xml_encode($data, $root='xml', $item='item', $attr='', $id='id', $encoding='utf-8') {
if(is_array($attr)){
$_attr = array();
foreach ($attr as $key => $value) {
$_attr[] = "{$key}=\"{$value}\"";
}
$attr = implode(' ', $_attr);
}
$attr = trim($attr);
$attr = empty($attr) ? '' : " {$attr}";
$xml = "<{$root}{$attr}>";
$xml .= self::data_to_xml($data, $item, $id);
$xml .= "</{$root}>";
return $xml;
}
/**
* 設(shè)置回復(fù)消息
* Examle: $obj->text('hello')->reply();
* @param string $text
*/
public function text($text='')
{
$FuncFlag = $this->_funcflag ? 1 : 0;
$msg = array(
'ToUserName' => $this->getRevFrom(),
'FromUserName'=>$this->getRevTo(),
'MsgType'=>self::MSGTYPE_TEXT,
'Content'=>$text,
'CreateTime'=>time(),
'FuncFlag'=>$FuncFlag
);
$this->Message($msg);
return $this;
}
/**
* 設(shè)置回復(fù)音樂
* @param string $title
* @param string $desc
* @param string $musicurl
* @param string $hgmusicurl
*/
public function music($title,$desc,$musicurl,$hgmusicurl='') {
$FuncFlag = $this->_funcflag ? 1 : 0;
$msg = array(
'ToUserName' => $this->getRevFrom(),
'FromUserName'=>$this->getRevTo(),
'CreateTime'=>time(),
'MsgType'=>self::MSGTYPE_MUSIC,
'Music'=>array(
'Title'=>$title,
'Description'=>$desc,
'MusicUrl'=>$musicurl,
'HQMusicUrl'=>$hgmusicurl
),
'FuncFlag'=>$FuncFlag
);
$this->Message($msg);
return $this;
}
/**
* 設(shè)置回復(fù)圖文
* @param array $newsData
* 數(shù)組結(jié)構(gòu):
* array(
* [0]=>array(
* 'Title'=>'msg title',
* 'Description'=>'summary text',
* 'PicUrl'=>'http://www.domain.com/1.jpg',
* 'Url'=>'http://www.domain.com/1.html'
* ),
* [1]=>....
* )
*/
public function news($newsData=array())
{
$FuncFlag = $this->_funcflag ? 1 : 0;
$count = count($newsData);
$msg = array(
'ToUserName' => $this->getRevFrom(),
'FromUserName'=>$this->getRevTo(),
'MsgType'=>self::MSGTYPE_NEWS,
'CreateTime'=>time(),
'ArticleCount'=>$count,
'Articles'=>$newsData,
'FuncFlag'=>$FuncFlag
);
$this->Message($msg);
return $this;
}
/**
*
* 回復(fù)微信服務(wù)器, 此函數(shù)支持鏈?zhǔn)讲僮?
* @example $this->text('msg tips')->reply();
* @param string $msg 要發(fā)送的信息, 默認(rèn)取$this->_msg
* @param bool $return 是否返回信息而不拋出到瀏覽器 默認(rèn):否
*/
public function reply($msg=array(),$return = false)
{
if (empty($msg))
$msg = $this->_msg;
$xmldata= $this->xml_encode($msg);
$this->log($xmldata);
if ($return)
return $xmldata;
else
echo $xmldata;
}
/**
* GET 請求
* @param string $url
*/
private function http_get($url){
$oCurl = curl_init();
if(stripos($url,"https://")!==FALSE){
curl_setopt($oCurl, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($oCurl, CURLOPT_SSL_VERIFYHOST, FALSE);
}
curl_setopt($oCurl, CURLOPT_URL, $url);
curl_setopt($oCurl, CURLOPT_RETURNTRANSFER, 1 );
$sContent = curl_exec($oCurl);
$aStatus = curl_getinfo($oCurl);
curl_close($oCurl);
if(intval($aStatus["http_code"])==200){
return $sContent;
}else{
return false;
}
}
/**
* POST 請求
* @param string $url
* @param array $param
* @return string content
*/
private function http_post($url,$param){
$oCurl = curl_init();
if(stripos($url,"https://")!==FALSE){
curl_setopt($oCurl, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($oCurl, CURLOPT_SSL_VERIFYHOST, false);
}
if (is_string($param)) {
$strPOST = $param;
} else {
$aPOST = array();
foreach($param as $key=>$val){
$aPOST[] = $key."=".urlencode($val);
}
$strPOST = join("&", $aPOST);
}
curl_setopt($oCurl, CURLOPT_URL, $url);
curl_setopt($oCurl, CURLOPT_RETURNTRANSFER, 1 );
curl_setopt($oCurl, CURLOPT_POST,true);
curl_setopt($oCurl, CURLOPT_POSTFIELDS,$strPOST);
$sContent = curl_exec($oCurl);
$aStatus = curl_getinfo($oCurl);
curl_close($oCurl);
if(intval($aStatus["http_code"])==200){
return $sContent;
}else{
return false;
}
}
/**
* 通用auth驗(yàn)證方法,暫時(shí)僅用于菜單更新操作
* @param string $appid
* @param string $appsecret
*/
public function checkAuth($appid='',$appsecret=''){
if (!$appid || !$appsecret) {
$appid = $this->appid;
$appsecret = $this->appsecret;
}
//TODO: get the cache access_token
$result = $this->http_get(self::API_URL_PREFIX.self::AUTH_URL.'appid='.$appid.'&secret='.$appsecret);
if ($result)
{
$json = json_decode($result,true);
if (!$json || isset($json['errcode'])) {
$this->errCode = $json['errcode'];
$this->errMsg = $json['errmsg'];
return false;
}
$this->access_token = $json['access_token'];
$expire = $json['expires_in'] ? intval($json['expires_in'])-100 : 3600;
//TODO: cache access_token
return $this->access_token;
}
return false;
}
/**
* 刪除驗(yàn)證數(shù)據(jù)
* @param string $appid
*/
public function resetAuth($appid=''){
$this->access_token = '';
//TODO: remove cache
return true;
}
/**
* 微信api不支持中文轉(zhuǎn)義的json結(jié)構(gòu)
* @param array $arr
*/
static function json_encode($arr) {
$parts = array ();
$is_list = false;
//Find out if the given array is a numerical array
$keys = array_keys ( $arr );
$max_length = count ( $arr ) - 1;
if (($keys [0] === 0) && ($keys [$max_length] === $max_length )) { //See if the first key is 0 and last key is length - 1
$is_list = true;
for($i = 0; $i < count ( $keys ); $i ++) { //See if each key correspondes to its position
if ($i != $keys [$i]) { //A key fails at position check.
$is_list = false; //It is an associative array.
break;
}
}
}
foreach ( $arr as $key => $value ) {
if (is_array ( $value )) { //Custom handling for arrays
if ($is_list)
$parts [] = self::json_encode ( $value ); /* :RECURSION: */
else
$parts [] = '"' . $key . '":' . self::json_encode ( $value ); /* :RECURSION: */
} else {
$str = '';
if (! $is_list)
$str = '"' . $key . '":';
//Custom handling for multiple data types
if (is_numeric ( $value ) && $value<2000000000)
$str .= $value; //Numbers
elseif ($value === false)
$str .= 'false'; //The booleans
elseif ($value === true)
$str .= 'true';
else
$str .= '"' . addslashes ( $value ) . '"'; //All other things
// :TODO: Is there any more datatype we should be in the lookout for? (Object?)
$parts [] = $str;
}
}
$json = implode ( ',', $parts );
if ($is_list)
return '[' . $json . ']'; //Return numerical JSON
return '{' . $json . '}'; //Return associative JSON
}
/**
* 創(chuàng)建菜單
* @param array $data 菜單數(shù)組數(shù)據(jù)
* example:
{
"button":[
{
"type":"click",
"name":"今日歌曲",
"key":"MENU_KEY_MUSIC"
},
{
"type":"view",
"name":"歌手簡介",
"url":"http://www.qq.com/"
},
{
"name":"菜單",
"sub_button":[
{
"type":"click",
"name":"hello word",
"key":"MENU_KEY_MENU"
},
{
"type":"click",
"name":"贊一下我們",
"key":"MENU_KEY_GOOD"
}]
}]
}
*/
public function createMenu($data){
if (!$this->access_token && !$this->checkAuth()) return false;
$result = $this->http_post(self::API_URL_PREFIX.self::MENU_CREATE_URL.'access_token='.$this->access_token,self::json_encode($data));
if ($result)
{
$json = json_decode($result,true);
if (!$json || !empty($json['errcode'])) {
$this->errCode = $json['errcode'];
$this->errMsg = $json['errmsg'];
return false;
}
return true;
}
return false;
}
/**
* 獲取菜單
* @return array('menu'=>array(....s))
*/
public function getMenu(){
if (!$this->access_token && !$this->checkAuth()) return false;
$result = $this->http_get(self::API_URL_PREFIX.self::MENU_GET_URL.'access_token='.$this->access_token);
if ($result)
{
$json = json_decode($result,true);
if (!$json || isset($json['errcode'])) {
$this->errCode = $json['errcode'];
$this->errMsg = $json['errmsg'];
return false;
}
return $json;
}
return false;
}
/**
* 刪除菜單
* @return boolean
*/
public function deleteMenu(){
if (!$this->access_token && !$this->checkAuth()) return false;
$result = $this->http_get(self::API_URL_PREFIX.self::MENU_DELETE_URL.'access_token='.$this->access_token);
if ($result)
{
$json = json_decode($result,true);
if (!$json || !empty($json['errcode'])) {
$this->errCode = $json['errcode'];
$this->errMsg = $json['errmsg'];
return false;
}
return true;
}
return false;
}
/**
* 根據(jù)媒體文件ID獲取媒體文件
* @param string $media_id 媒體文件id
* @return raw data
*/
public function getMedia($media_id){
if (!$this->access_token && !$this->checkAuth()) return false;
$result = $this->http_get(self::API_URL_PREFIX.self::MEDIA_GET_URL.'access_token='.$this->access_token.'&media_id='.$media_id);
if ($result)
{
$json = json_decode($result,true);
if (isset($json['errcode'])) {
$this->errCode = $json['errcode'];
$this->errMsg = $json['errmsg'];
return false;
}
return $json;
}
return false;
}
/**
* 創(chuàng)建二維碼ticket
* @param int $scene_id 自定義追蹤id
* @param int $type 0:臨時(shí)二維碼;1:永久二維碼(此時(shí)expire參數(shù)無效)
* @param int $expire 臨時(shí)二維碼有效期,最大為1800秒
* @return array('ticket'=>'qrcode字串','expire_seconds'=>1800)
*/
public function getQRCode($scene_id,$type=0,$expire=1800){
if (!$this->access_token && !$this->checkAuth()) return false;
$data = array(
'action_name'=>$type?"QR_LIMIT_SCENE":"QR_SCENE",
'expire_seconds'=>$expire,
'action_info'=>array('scene'=>array('scene_id'=>$scene_id))
);
if ($type == 1) {
unset($data['expire_seconds']);
}
$result = $this->http_post(self::API_URL_PREFIX.self::QRCODE_CREATE_URL.'access_token='.$this->access_token,self::json_encode($data));
if ($result)
{
$json = json_decode($result,true);
if (!$json || !empty($json['errcode'])) {
$this->errCode = $json['errcode'];
$this->errMsg = $json['errmsg'];
return false;
}
return $json;
}
return false;
}
/**
* 獲取二維碼圖片
* @param string $ticket 傳入由getQRCode方法生成的ticket參數(shù)
* @return string url 返回http地址
*/
public function getQRUrl($ticket) {
return self::QRCODE_IMG_URL.$ticket;
}
/**
* 批量獲取關(guān)注用戶列表
* @param unknown $next_openid
*/
public function getUserList($next_openid=''){
if (!$this->access_token && !$this->checkAuth()) return false;
$result = $this->http_get(self::API_URL_PREFIX.self::USER_GET_URL.'access_token='.$this->access_token.'&next_openid='.$next_openid);
if ($result)
{
$json = json_decode($result,true);
if (isset($json['errcode'])) {
$this->errCode = $json['errcode'];
$this->errMsg = $json['errmsg'];
return false;
}
return $json;
}
return false;
}
/**
* 獲取關(guān)注者詳細(xì)信息
* @param string $openid
* @return array
*/
public function getUserInfo($openid){
if (!$this->access_token && !$this->checkAuth()) return false;
$result = $this->http_get(self::API_URL_PREFIX.self::USER_INFO_URL.'access_token='.$this->access_token.'&openid='.$openid);
if ($result)
{
$json = json_decode($result,true);
if (isset($json['errcode'])) {
$this->errCode = $json['errcode'];
$this->errMsg = $json['errmsg'];
return false;
}
return $json;
}
return false;
}
/**
* 獲取用戶分組列表
* @return boolean|array
*/
public function getGroup(){
if (!$this->access_token && !$this->checkAuth()) return false;
$result = $this->http_get(self::API_URL_PREFIX.self::GROUP_GET_URL.'access_token='.$this->access_token);
if ($result)
{
$json = json_decode($result,true);
if (isset($json['errcode'])) {
$this->errCode = $json['errcode'];
$this->errMsg = $json['errmsg'];
return false;
}
return $json;
}
return false;
}
/**
* 新增自定分組
* @param string $name 分組名稱
* @return boolean|array
*/
public function createGroup($name){
if (!$this->access_token && !$this->checkAuth()) return false;
$data = array(
'group'=>array('name'=>$name)
);
$result = $this->http_post(self::API_URL_PREFIX.self::GROUP_CREATE_URL.'access_token='.$this->access_token,self::json_encode($data));
if ($result)
{
$json = json_decode($result,true);
if (!$json || !empty($json['errcode'])) {
$this->errCode = $json['errcode'];
$this->errMsg = $json['errmsg'];
return false;
}
return $json;
}
return false;
}
/**
* 更改分組名稱
* @param int $groupid 分組id
* @param string $name 分組名稱
* @return boolean|array
*/
public function updateGroup($groupid,$name){
if (!$this->access_token && !$this->checkAuth()) return false;
$data = array(
'group'=>array('id'=>$groupid,'name'=>$name)
);
$result = $this->http_post(self::API_URL_PREFIX.self::GROUP_UPDATE_URL.'access_token='.$this->access_token,self::json_encode($data));
if ($result)
{
$json = json_decode($result,true);
if (!$json || !empty($json['errcode'])) {
$this->errCode = $json['errcode'];
$this->errMsg = $json['errmsg'];
return false;
}
return $json;
}
return false;
}
/**
* 移動用戶分組
* @param int $groupid 分組id
* @param string $openid 用戶openid
* @return boolean|array
*/
public function updateGroupMembers($groupid,$openid){
if (!$this->access_token && !$this->checkAuth()) return false;
$data = array(
'openid'=>$openid,
'to_groupid'=>$groupid
);
$result = $this->http_post(self::API_URL_PREFIX.self::GROUP_MEMBER_UPDATE_URL.'access_token='.$this->access_token,self::json_encode($data));
if ($result)
{
$json = json_decode($result,true);
if (!$json || !empty($json['errcode'])) {
$this->errCode = $json['errcode'];
$this->errMsg = $json['errmsg'];
return false;
}
return $json;
}
return false;
}
/**
* 發(fā)送客服消息
* @param array $data 消息結(jié)構(gòu){"touser":"OPENID","msgtype":"news","news":{...}}
* @return boolean|array
*/
public function sendCustomMessage($data){
if (!$this->access_token && !$this->checkAuth()) return false;
$result = $this->http_post(self::API_URL_PREFIX.self::CUSTOM_SEND_URL.'access_token='.$this->access_token,self::json_encode($data));
if ($result)
{
$json = json_decode($result,true);
if (!$json || !empty($json['errcode'])) {
$this->errCode = $json['errcode'];
$this->errMsg = $json['errmsg'];
return false;
}
return $json;
}
return false;
}
/**
* oauth 授權(quán)跳轉(zhuǎn)接口
* @param string $callback 回調(diào)URI
* @return string
*/
public function getOauthRedirect($callback,$state='',$scope='snsapi_userinfo'){
return self::OAUTH_PREFIX.self::OAUTH_AUTHORIZE_URL.'appid='.$this->appid.'&redirect_uri='.urlencode($callback).'&response_type=code&scope='.$scope.'&state='.$state.'#wechat_redirect';
}
/*
* 通過code獲取Access Token
* @return array {access_token,expires_in,refresh_token,openid,scope}
*/
public function getOauthAccessToken(){
$code = isset($_GET['code'])?$_GET['code']:'';
if (!$code) return false;
$result = $this->http_get(self::OAUTH_TOKEN_PREFIX.self::OAUTH_TOKEN_URL.'appid='.$this->appid.'&secret='.$this->appsecret.'&code='.$code.'&grant_type=authorization_code');
if ($result)
{
$json = json_decode($result,true);
if (!$json || !empty($json['errcode'])) {
$this->errCode = $json['errcode'];
$this->errMsg = $json['errmsg'];
return false;
}
$this->user_token = $json['access_token'];
return $json;
}
return false;
}
/**
* 刷新access token并續(xù)期
* @param string $refresh_token
* @return boolean|mixed
*/
public function getOauthRefreshToken($refresh_token){
$result = $this->http_get(self::OAUTH_TOKEN_PREFIX.self::OAUTH_REFRESH_URL.'appid='.$this->appid.'&grant_type=refresh_token&refresh_token='.$refresh_token);
if ($result)
{
$json = json_decode($result,true);
if (!$json || !empty($json['errcode'])) {
$this->errCode = $json['errcode'];
$this->errMsg = $json['errmsg'];
return false;
}
$this->user_token = $json['access_token'];
return $json;
}
return false;
}
/**
* 獲取授權(quán)后的用戶資料
* @param string $access_token
* @param string $openid
* @return array {openid,nickname,sex,province,city,country,headimgurl,privilege}
*/
public function getOauthUserinfo($access_token,$openid){
$result = $this->http_get(self::OAUTH_USERINFO_URL.'access_token='.$access_token.'&openid='.$openid);
if ($result)
{
$json = json_decode($result,true);
if (!$json || !empty($json['errcode'])) {
$this->errCode = $json['errcode'];
$this->errMsg = $json['errmsg'];
return false;
}
return $json;
}
return false;
}
}
接下來就是接口對應(yīng)的index.php文件,處理微信服務(wù)器發(fā)送來的信息。
因?yàn)槭枪ぷ魇业奈⑿殴操~號,所以未做任何修改源碼搬上來,截取有用的部分即可:
<?php
/**
* WeeGo工作室微信公眾平臺接口源碼
* @author CallMeWhy <wanghaiyang@139.me>
* @version 1.0
*/
include "wechat.class.php";
$options = array
(
'token'=>'weego',
'debug'=>true,
'logcallback'=>'logdebug'
);
$weObj = new Wechat($options);
// 驗(yàn)證
$weObj->valid();
// 獲取內(nèi)容
$weObj->getRev();
// 獲取用戶的OpenID
$fromUsername = $weObj->getRevFrom();
// 獲取接受信息的類型
$type = $weObj->getRev()->getRevType();
//**********關(guān)注操作則寫入數(shù)據(jù)庫**********/
if($weObj->getRevSubscribe())
{
// 獲取用戶OPENID并寫入數(shù)據(jù)庫
$mysql = new SaeMysql();
$sql = "INSERT INTO `users` (`wxid`) VALUES ('" . $fromUsername . "');";
$mysql->runSql($sql);
$mysql->closeDb();
// 獲得信息的類型
$news = array
(
array
(
'Title'=>'歡迎關(guān)注WeeGo工作室',
'Description'=>'發(fā)送任意內(nèi)容查看最新開發(fā)進(jìn)展',
'PicUrl'=>'http://233.weego.sinaapp.com/images/weego_400_200.png',
)
);
$weObj->news($news)->reply();
}
//**********取消關(guān)注操作則刪除數(shù)據(jù)庫**********/
if($weObj->getRevUnsubscribe())
{
// 獲取用戶OPENID并從數(shù)據(jù)庫刪除
$mysql = new SaeMysql();
$sql = "DELETE FROM `users` WHERE `wxid` = '" . $fromUsername . "'";
$mysql->runSql($sql);
$mysql->closeDb();
}
switch($type) {
case Wechat::MSGTYPE_TEXT:
/**********文字信息**********/
$news = array
(
array
(
'Title'=>"歡迎光臨WeeGo工作室",
'PicUrl'=>'http://233.weego.sinaapp.com/images/weego_400_200.png',
//'Url'=>'http://233.weego.sinaapp.com/web/home.php?wxid='.$fromUsername
),
array
(
'Title'=>"功能1:發(fā)送圖片可以查詢照片中人臉的年齡和性別信息哦",
'PicUrl'=>'http://233.weego.sinaapp.com/images/face.jpg',
//'Url'=>'http://233.weego.sinaapp.com/web/home.php?wxid='.$fromUsername
),
array
(
'Title'=>"功能2:發(fā)送一張兩人合影的照片可以計(jì)算兩人的相似程度",
'PicUrl'=>'http://233.weego.sinaapp.com/images/mask.png',
//'Url'=>'http://233.weego.sinaapp.com/web/home.php?wxid='.$fromUsername
),
array
(
'Title'=>"功能3:山東大學(xué)績點(diǎn)查詢簽到等功能正在開發(fā)中敬請期待",
'PicUrl'=>'http://233.weego.sinaapp.com/images/sdu.jpg',
//'Url'=>'http://233.weego.sinaapp.com/web/home.php?wxid='.$fromUsername
)
);
// 開發(fā)人員通道
if($weObj->getRev()->getRevContent() === "why"){
$news = array
(
array
(
'Title'=>'開發(fā)人員通道',
'Description'=>'開發(fā)人員通道',
'PicUrl'=>'http://233.weego.sinaapp.com/images/weego_400_200.png',
'Url'=>'http://233.weego.sinaapp.com/web/home.php?wxid='.$fromUsername
)
);
}
$weObj->news($news)->reply();
exit;
break;
case Wechat::MSGTYPE_EVENT:
break;
case Wechat::MSGTYPE_IMAGE:
/**********圖片信息**********/
$imgUrl = $weObj->getRev()->getRevPic();
$resultStr = face($imgUrl);
$weObj->text($resultStr)->reply();
break;
default:
$weObj->text("Default")->reply();
}
// 調(diào)用人臉識別的API返回識別結(jié)果
function face($imgUrl)
{
// face++ 鏈接
$jsonStr =
file_get_contents("http://apicn.faceplusplus.com/v2/detection/detect?url=".$imgUrl."&api_key=5eb2c984ad24ffc08c352bdb53ee52f8&api_secret=ViX19uvxkT_A0a6d55Hb0Q0QGMTqZ95f&&attribute=glass,pose,gender,age,race,smiling");
$replyDic = json_decode($jsonStr);
$resultStr = "";
$faceArray = $replyDic->{'face'};
$resultStr .= "圖中共檢測到".count($faceArray)."張臉!\n";
for ($i= 0;$i< count($faceArray); $i++){
$resultStr .= "第".($i+1)."張臉\n";
$tempFace = $faceArray[$i];
// 獲取所有屬性
$tempAttr = $tempFace->{'attribute'};
// 年齡:包含年齡分析結(jié)果
// value的值為一個非負(fù)整數(shù)表示估計(jì)的年齡, range表示估計(jì)年齡的正負(fù)區(qū)間
$tempAge = $tempAttr->{'age'};
// 性別:包含性別分析結(jié)果
// value的值為Male/Female, confidence表示置信度
$tempGenger = $tempAttr->{'gender'};
// 種族:包含人種分析結(jié)果
// value的值為Asian/White/Black, confidence表示置信度
$tempRace = $tempAttr->{'race'};
// 微笑:包含微笑程度分析結(jié)果
//value的值為0-100的實(shí)數(shù),越大表示微笑程度越高
$tempSmiling = $tempAttr->{'smiling'};
// 眼鏡:包含眼鏡佩戴分析結(jié)果
// value的值為None/Dark/Normal, confidence表示置信度
$tempGlass = $tempAttr->{'glass'};
// 造型:包含臉部姿勢分析結(jié)果
// 包括pitch_angle, roll_angle, yaw_angle
// 分別對應(yīng)抬頭,旋轉(zhuǎn)(平面旋轉(zhuǎn)),搖頭
// 單位為角度。
$tempPose = $tempAttr->{'pose'};
//返回年齡
$minAge = $tempAge->{'value'} - $tempAge->{'range'};
$minAge = $minAge < 0 ? 0 : $minAge;
$maxAge = $tempAge->{'value'} + $tempAge->{'range'};
$resultStr .= "年齡:".$minAge."-".$maxAge."歲\n";
// 返回性別
if($tempGenger->{'value'} === "Male")
$resultStr .= "性別:男\(zhòng)n";
else if($tempGenger->{'value'} === "Female")
$resultStr .= "性別:女\n";
// 返回種族
if($tempRace->{'value'} === "Asian")
$resultStr .= "種族:黃種人\n";
else if($tempRace->{'value'} === "Male")
$resultStr .= "種族:白種人\n";
else if($tempRace->{'value'} === "Black")
$resultStr .= "種族:黑種人\n";
// 返回眼鏡
if($tempGlass->{'value'} === "None")
$resultStr .= "眼鏡:木有眼鏡\n";
else if($tempGlass->{'value'} === "Dark")
$resultStr .= "眼鏡:目測墨鏡\n";
else if($tempGlass->{'value'} === "Normal")
$resultStr .= "眼鏡:普通眼鏡\n";
//返回微笑
$resultStr .= "微笑:".round($tempSmiling->{'value'})."%\n";
}
if(count($faceArray) === 2){
// 獲取face_id
$tempFace = $faceArray[0];
$tempId1 = $tempFace->{'face_id'};
$tempFace = $faceArray[1];
$tempId2 = $tempFace->{'face_id'};
// face++ 鏈接
$jsonStr =
file_get_contents("https://apicn.faceplusplus.com/v2/recognition/compare?api_secret=ViX19uvxkT_A0a6d55Hb0Q0QGMTqZ95f&api_key=5eb2c984ad24ffc08c352bdb53ee52f8&face_id2=".$tempId2 ."&face_id1=".$tempId1);
$replyDic = json_decode($jsonStr);
//取出相似程度
$tempResult = $replyDic->{'similarity'};
$resultStr .= "相似程度:".round($tempResult)."%\n";
//具體分析相似處
$tempSimilarity = $replyDic->{'component_similarity'};
$tempEye = $tempSimilarity->{'eye'};
$tempEyebrow = $tempSimilarity->{'eyebrow'};
$tempMouth = $tempSimilarity->{'mouth'};
$tempNose = $tempSimilarity->{'nose'};
$resultStr .= "相似分析:\n";
$resultStr .= "眼睛:".round($tempEye)."%\n";
$resultStr .= "眉毛:".round($tempEyebrow)."%\n";
$resultStr .= "嘴巴:".round($tempMouth)."%\n";
$resultStr .= "鼻子:".round($tempNose)."%\n";
}
//如果沒有檢測到人臉
if($resultStr === "")
$resultStr = "照片中木有人臉=.=";
return $resultStr;
};
// 寫入本地日志文件的函數(shù)
function logdebug($text)
{
file_put_contents('log.txt', $text."\n", FILE_APPEND);
};
希望本文所述對大家基于php的微信公眾平臺開發(fā)有所幫助。
相關(guān)文章
解決laravel(5.5)訪問public報(bào)錯的問題
今天小編就為大家分享一篇解決laravel(5.5)訪問public報(bào)錯的問題,具有很好的參考價(jià)值,希望對大家有所幫助。一起跟隨小編過來看看吧2019-10-10
基于php(Thinkphp)+jquery 實(shí)現(xiàn)ajax多選反選不選刪除數(shù)據(jù)功能
這篇文章主要介紹了基于php(Thinkphp)+jquery 實(shí)現(xiàn)ajax多選反選不選刪除數(shù)據(jù)功能的相關(guān)資料,需要的朋友可以參考下2017-02-02
Laravel框架實(shí)現(xiàn)的rbac權(quán)限管理操作示例
這篇文章主要介紹了Laravel框架實(shí)現(xiàn)的rbac權(quán)限管理操作,結(jié)合實(shí)例形式分析了Laravel框架權(quán)限控制rbac相關(guān)數(shù)據(jù)庫創(chuàng)建、讀寫及權(quán)限判斷等操作技巧,需要的朋友可以參考下2019-01-01
thinkphp3查詢mssql數(shù)據(jù)庫亂碼解決方法分享
這篇文章主要介紹了thinkphp3查詢mssql數(shù)據(jù)庫亂碼解決方法,需要的朋友可以參考下2014-02-02
PHP實(shí)現(xiàn)騰訊與百度坐標(biāo)轉(zhuǎn)換
下面小編就為大家?guī)硪黄狿HP實(shí)現(xiàn)騰訊與百度坐標(biāo)轉(zhuǎn)換。小編覺得挺不錯的,現(xiàn)在就分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2017-08-08

