本文实例讲述了PHP使用Face++接口开发微信公众平台人脸识别系统的方法。分享给大家供大家参考。具体如下:
效果图如下:
具体步骤如下:
首先,先登录Face++的官网注册账号:官网链接 注册之后会获取到api_secret和api_key,这些在调用接口的时候需要用到。 然后接下来的就是使用PHP脚本调用API了。 在使用PHP开发微信公共平台的时候,推荐使用Github上的一款不错的框架:wechat-PHP-sdk 对于微信的常用接口做了一些封装,核心文件wechat.class.PHP如下:
/**
- 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,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,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验证方法,暂时仅用于菜单更新操作
- @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;
}
/** - 删除验证数据
- @param string $appid
*/
public function resetAuth($appid=''){
$this->access_token = '';
//TODO: remove cache
return true;
}
/** - 微信api不支持中文转义的json结构
- @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
}
/** - 创建菜单
- @param array $data 菜单数组数据
- 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;
}
/** - 根据媒体文件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;
}
/** - 创建二维码ticket
- @param int $scene_id 自定义追踪id
- @param int $type 0:临时二维码;1:永久二维码(此时expire参数无效)
- @param int $expire 临时二维码有效期,最大为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,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参数
- @return string url 返回http地址
*/
public function getQRUrl($ticket) {
return self::QRCODE_IMG_URL.$ticket;
}
/** - 批量获取关注用户列表
- @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;
}
/** - 获取关注者详细信息
- @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,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,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,true);
if (!$json || !empty($json['errcode'])) {
$this->errCode = $json['errcode'];
$this->errMsg = $json['errmsg'];
return false;
}
return $json;
}
return false;
}
/** - 发送客服消息
- @param array $data 消息结构{"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,true);
if (!$json || !empty($json['errcode'])) {
$this->errCode = $json['errcode'];
$this->errMsg = $json['errmsg'];
return false;
}
return $json;
}
return false;
}
/** - oauth 授权跳转接口
- @param string $callback 回调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并续期
- @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;
}
/** - 获取授权后的用户资料
- @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;
}
}
接下来就是接口对应的index.PHP文件,处理微信服务器发送来的信息。 因为是工作室的微信公共账号,所以未做任何修改源码搬上来,截取有用的部分即可:
*/
include "wechat.class.PHP";
$options = array
(
'token'=>'weego','debug'=>true,'logcallback'=>'logdebug'
);
$weObj = new Wechat($options);
// 验证
$weObj->valid();
// 获取内容
$weObj->getRev();
// 获取用户的OpenID
$fromUsername = $weObj->getRevFrom();
// 获取接受信息的类型
$type = $weObj->getRev()->getRevType();
//**关注操作则写入数据库**/
if($weObj->getRevSubscribe())
{
// 获取用户OPENID并写入数据库
$MysqL = new SAEMysqL();
$sql = "INSERT INTO users
(wxid
) VALUES ('" . $fromUsername . "');";
$MysqL->runsql($sql);
$MysqL->closeDb();
// 获得信息的类型
$news = array
(
array
(
'Title'=>'欢迎关注WeeGo工作室','Description'=>'发送任意内容查看最新开发进展','PicUrl'=>'http://233.weego.sinaapp.com/images/weego_400_200.png',)
);
$weObj->news($news)->reply();
}
//**取消关注操作则删除数据库**/
if($weObj->getRevUnsubscribe())
{
// 获取用户OPENID并从数据库删除
$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工作室",//'Url'=>'http://233.weego.sinaapp.com/web/home.PHP?wxid='.$fromUsername
),array
(
'Title'=>"功能1:发送图片可以查询照片中人脸的年龄和性别信息哦",'PicUrl'=>'http://233.weego.sinaapp.com/images/face.jpg',array
(
'Title'=>"功能2:发送一张两人合影的照片可以计算两人的相似程度",'PicUrl'=>'http://233.weego.sinaapp.com/images/mask.png',array
(
'Title'=>"功能3:山东大学绩点查询签到等功能正在开发中敬请期待",'PicUrl'=>'http://233.weego.sinaapp.com/images/sdu.jpg',//'Url'=>'http://233.weego.sinaapp.com/web/home.PHP?wxid='.$fromUsername
)
);
// 开发人员通道
if($weObj->getRev()->getRevContent() === "why"){
$news = array
(
array
(
'Title'=>'开发人员通道','Description'=>'开发人员通道','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();
}
// 调用人脸识别的API返回识别结果
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'};
// 年龄:包含年龄分析结果
// value的值为一个非负整数表示估计的年龄,range表示估计年龄的正负区间
$tempAge = $tempAttr->{'age'};
// 性别:包含性别分析结果
// value的值为Male/Female,confidence表示置信度
$tempGenger = $tempAttr->{'gender'};
// 种族:包含人种分析结果
// value的值为Asian/White/Black,confidence表示置信度
$tempRace = $tempAttr->{'race'};
// 微笑:包含微笑程度分析结果
//value的值为0-100的实数,越大表示微笑程度越高
$tempSmiling = $tempAttr->{'smiling'};
// 眼镜:包含眼镜佩戴分析结果
// value的值为None/Dark/Normal,confidence表示置信度
$tempGlass = $tempAttr->{'glass'};
// 造型:包含脸部姿势分析结果
// 包括pitch_angle,roll_angle,yaw_angle
// 分别对应抬头,旋转(平面旋转),摇头
// 单位为角度。
$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 .= "性别:男\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++ <a href="/tag/lianjie/" target="_blank" class="keywords">链接</a>
$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;
};
// 写入本地日志文件的函数
function logdebug($text)
{
file_put_contents('log.txt',$text."\n",FILE_APPEND);
};
希望本文所述对大家基于PHP的微信公众平台开发有所帮助。