本文实例讲述了php使用face++接口开发微信公众平台人脸识别系统的方法。分享给大家供大家参考。具体如下:
效果图如下:
具体步骤如下:
首先,先登录face++的官网注册账号:官网链接
注册之后会获取到api_secret和api_key,这些在调用接口的时候需要用到。
然后接下来的就是使用php脚本调用api了。
在使用php开发微信公共平台的时候,推荐使用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', //填写你设定的key
* 'appid'=>'wxdk1234567890', //填写高级调用功能的app id
* 'appsecret'=>'xxxxxxxxxxxxxxxxxxx', //填写高级调用功能的密钥
* );
* $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();
* //设置菜单
* $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;
}
/**
* 设置发送消息
* @param array $msg 消息数组
* @param bool $append 是否在原消息数组追加
*/
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);
}
}
/**
* 获取微信服务器发来的信息
*/
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;
}
/**
* 获取微信服务器发来的信息
*/
public function getrevdata()
{
return $this->_receive;
}
/**
* 获取消息发送者
*/
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;
}
/**
* 获取消息发送时间
*/
public function getrevctime() {
if (isset($this->_receive['createtime']))
return $this->_receive['createtime'];
else
return false;
}
/**
* 获取接收消息内容正文
*/
public function getrevcontent(){
if (isset($this->_receive['content']))
return $this->_receive['content'];
else if (isset($this->_receive['recognition'])) //获取语音识别文字内容,需申请开通
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).']]>';
}
/**
* 数据xml编码
* @param mixed $data 数据
* @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 数据
* @param string $root 根节点名
* @param string $item 数字索引的子节点名
* @param string $attr 根节点属性
* @param string $id 数字索引子节点key转换的属性名
* @param string $encoding 数据编码
* @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;
}
/**
* 设置回复消息
* 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;
}
/**
* 设置回复音乐
* @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;
}
/**
* 设置回复图文
* @param array $newsdata
* 数组结构:
* 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;
}
/**
*
* 回复微信服务器, 此函数支持链式操作
* @example $this->text('msg tips')->reply();
* @param string $msg 要发送的信息, 默认取$this->_msg
* @param bool $return 是否返回信息而不抛出到浏览器 默认:否
*/
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验证方法,暂时仅用于菜单更新操作
* @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,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参数
* @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,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;
}
/**
* 发送客服消息
* @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,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 授权跳转接口
* @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文件,处理微信服务器发送来的信息。
因为是工作室的微信公共账号,所以未做任何修改源码搬上来,截取有用的部分即可:
<?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);
// 验证
$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工作室",
'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:发送图片可以查询照片中人脸的年龄和性别信息哦",
'picurl'=>'http://233.weego.sinaapp.com/images/face.jpg',
//'url'=>'http://233.weego.sinaapp.com/web/home.php?wxid='.$fromusername
),
array
(
'title'=>"功能2:发送一张两人合影的照片可以计算两人的相似程度",
'picurl'=>'http://233.weego.sinaapp.com/images/mask.png',
//'url'=>'http://233.weego.sinaapp.com/web/home.php?wxid='.$fromusername
),
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'=>'开发人员通道',
'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();
}
// 调用人脸识别的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++ 链接
$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的微信公众平台开发有所帮助。
【说明】:本文章由站长整理发布,文章内容不代表本站观点,如文中有侵权行为,请与本站客服联系(QQ:)!