PHP 는 Face+인 터 페 이 스 를 이용 하여 위 챗 공식 플랫폼 의 얼굴 인식 시스템 을 개발 하 는 방법
46826 단어 PHP위 챗 공식 플랫폼식별
효과 도 는 다음 과 같다.
구체 적 인 절 차 는 다음 과 같다.
우선 페 이 스++홈 페이지 등록 계 정:홈 페이지 링크
등록 후 api 획득시 크 릿 과 apikey,인 터 페 이 스 를 호출 할 때 사용 해 야 합 니 다.
그리고 다음은 PHP 스 크 립 트 를 사용 하여 API 를 호출 하 는 것 입 니 다.
PHP 를 사용 하여 위 챗 공공 플랫폼 을 개발 할 때 Github 의 좋 은 프레임 워 크 를 사용 하 는 것 을 추천 합 니 다:wechat-phop-sdk
위 챗 의 상용 인터페이스 에 대해 봉 인 했 습 니 다.핵심 파일 인 wechat.class.php 는 다음 과 같 습 니 다.
<?php
/**
* PHP-SDK, API
* @author dodge <[email protected]>
* @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 <[email protected]>
* @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)." !
";
for ($i= 0;$i< count($faceArray); $i++){
$resultStr .= " ".($i+1)."
";
$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."
";
//
if($tempGenger->{'value'} === "Male")
$resultStr .= " :
";
else if($tempGenger->{'value'} === "Female")
$resultStr .= " :
";
//
if($tempRace->{'value'} === "Asian")
$resultStr .= " :
";
else if($tempRace->{'value'} === "Male")
$resultStr .= " :
";
else if($tempRace->{'value'} === "Black")
$resultStr .= " :
";
//
if($tempGlass->{'value'} === "None")
$resultStr .= " :
";
else if($tempGlass->{'value'} === "Dark")
$resultStr .= " :
";
else if($tempGlass->{'value'} === "Normal")
$resultStr .= " :
";
//
$resultStr .= " :".round($tempSmiling->{'value'})."%
";
}
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)."%
";
//
$tempSimilarity = $replyDic->{'component_similarity'};
$tempEye = $tempSimilarity->{'eye'};
$tempEyebrow = $tempSimilarity->{'eyebrow'};
$tempMouth = $tempSimilarity->{'mouth'};
$tempNose = $tempSimilarity->{'nose'};
$resultStr .= " :
";
$resultStr .= " :".round($tempEye)."%
";
$resultStr .= " :".round($tempEyebrow)."%
";
$resultStr .= " :".round($tempMouth)."%
";
$resultStr .= " :".round($tempNose)."%
";
}
//
if($resultStr === "")
$resultStr = " =.=";
return $resultStr;
};
//
function logdebug($text)
{
file_put_contents('log.txt', $text."
", FILE_APPEND);
};
본 고 에서 말 한 것 이 모두 가 php 를 바탕 으로 하 는 위 챗 공공 플랫폼 개발 에 도움 이 되 기 를 바 랍 니 다.
이 내용에 흥미가 있습니까?
현재 기사가 여러분의 문제를 해결하지 못하는 경우 AI 엔진은 머신러닝 분석(스마트 모델이 방금 만들어져 부정확한 경우가 있을 수 있음)을 통해 가장 유사한 기사를 추천합니다:
laravel에 yo에서 angularJs&coffeescript를 사용할 수 있도록 한다.먼저 yo 명령을 사용할 수 있어야하므로 아래에서 설치 global에 설치한 곳에서 laravel의 프로젝트 루트로 이동. 클라이언트 코드를 관리하는 디렉토리를 만들고 이동합니다. 클라이언트 환경 만들기 이것으로 히...
텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
CC BY-SA 2.5, CC BY-SA 3.0 및 CC BY-SA 4.0에 따라 라이센스가 부여됩니다.