weixin sdk

<?php
/**
 *    微信公众平台PHP-SDK, 官方API部分
 *  @author  bobcms <www.bobcms.net>

 *  @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->lasttime = 1410241562;
        $this->access_token = "";
        $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;
        $this->access_token =$this->getAccessToken();
/*          if (time() > ($this->lasttime + 7200)){
             $this->access_token =$this->checkAuth();
             $this->lasttime = time();
        } */
    }

    public function backaccess_token(){
        //return $this->access_token;
    }

    /**
     * 微信服务器验证
     * @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;
    }

    /**
     * For 微信服务器验证方法
     */
    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;
        }
    }

    /**
     * 获取微信服务器发来的信息
     */
    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;
    }

/**
 * 转发给多客服
 */
public function dkf()
    {
        $FuncFlag = $this->_funcflag ? 1 : 0;
        $msg = array(
            ‘ToUserName‘ => $this->getRevFrom(),
            ‘FromUserName‘=>$this->getRevTo(),
            ‘MsgType‘=>"transfer_customer_service",
            ‘CreateTime‘=>time(),
        );
        $this->Message($msg);
        return $this;
    }

    /*
     * 给用户发消息
     *
     */

    public function text_to_member($text=‘‘,$openid)
    {
        $FuncFlag = $this->_funcflag ? 1 : 0;
        $msg = array(
            ‘ToUserName‘ =>$openid,
            ‘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;
    }

    /**
     * 设置发送消息
     * @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);
        }
    }

    /**
     * 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;
        }
    }

    /*
     * 获取access_token by memcache
    */
    private function getAccessToken() {
        $memcache_obj = memcache_connect("localhost", 11211);
        $access_token=$memcache_obj->get(‘access_token‘);
        if($access_token){
            return $access_token;
        }else{
            $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=$this->appid&secret=$this->appsecret";
            $res = json_decode($this->http_get($url));
            $access_token = $res->access_token;
            if ($access_token) {
                $memcache_obj->set(‘access_token‘, $access_token, false, 7000);
                return $access_token;
            }else{
                return false;
            }
        }
    }

    /**
     * 获取 access_token
     * @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;
    }    

    /**
     * 获取二维码图片
     * @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){

        $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;
    }

    /**
     * 创建二维码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) {    echo "access_token 不存在";exit();}

        $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 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;
    }

    /**    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?‘;

     * 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=‘.$this->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;
    }

        //https请求(支持GET和POST)
    protected function https_request($url, $data = null)
    {
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);
        if (!empty($data)){
            curl_setopt($curl, CURLOPT_POST, 1);
            curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
        }
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        $output = curl_exec($curl);
        curl_close($curl);
        return $output;
    }
}
时间: 2024-08-08 10:19:48

weixin sdk的相关文章

【重要更新】Senparc.Weixin SDK v6.5 升级说明

Senparc.Weixin SDK v6.5 将微信消息上下文进行了大幅度的重构,支持了使用分布式缓存存储上下文信息,这意味着在分布式系统中,现在 Senparc.Weixin SDK 也能提供跨服务器的上下文消息共享. 当前的分布式上下文支持依赖了 NeuChar 提供的跨平台消息上下文解决方案,因此在公众号.小程序.企业微信中都已经默认支持此功能(开放平台接收的是系统推送,暂时没有必要支持). 本次升级对应 Senparc.Weixin.dll:v6.5.0,Senparc.Weixin.

【重要更新】Senparc.Weixin SDK v4.3.3升级说明

为了更好地适应微信越来越快的API更新速度和越来越多的API数量,本次Senparc.Weixin.dll v4.3.3对一些通用功能进行了深度的重构. 本次更新同时影响以下所有Senparc.Weixin相关版本的dll: Senparc.Weixin.dll 升级到 v4.3.3 Senparc.Weixin.MP.dll 升级到 v13.3.0(重要) Senparc.Weixin.MP.MvcExtension.dll 升级到 v1.4.1 Senparc.Weixin.Open 升级到

【重要更新】Senparc.Weixin SDK v4.4 升级说明

本次更新同时影响以下所有Senparc.Weixin相关版本的dll: Senparc.Weixin.dll 升级到 v4.4.2(重要) Senparc.Weixin.MP.dll 升级到 v13.4.0(重要) Senparc.Weixin.MP.MvcExtension.dll 无需升级 Senparc.Weixin.Open 升级到 v1.5.3(重要) Senparc.Weixin.QY.dll 升级到 v3.2.0(重要) 源代码:https://github.com/Jeffrey

微信公众平台C# SDK:Senparc.Weixin.MP.dll

https://github.com/Senparc/WeiXinMPSDK [转] http://www.cnblogs.com/szw/archive/2013/01/13/senparc-weixin-mp-sdk.html 微信公众账号 Senparc.Weixin.MP SDK 开发教程 索引 Senparc.Weixin.MP SDK从一开始就坚持开源的状态,这个过程中得到了许多朋友的认可和支持. 目前SDK已经达到比较稳定的版本,这个过程中我觉得有必要整理一些思路和经验,和大家一起

.NET平台下的微信SDK(Rabbit.WeiXin)开源发布

在上一篇文章<RabbitHub开源情况及计划>上有提及到了一个新的开源项目--微信SDK,经过几天的努力现在开源发布Beta1版本. 目录 前言 特点 功能 支持的消息类型 请求消息 事件消息 响应消息 消息处理中间件 支持的API 暂不支持的API 关于性能 关于易扩展性 关于易使用性 关于架构 消息处理 请求消息 事件消息 响应消息 消息格式化器 开源信息 交流方式 写在最后 前言 在某一个傍晚,与头为产品"雨后春笋"历经一个下午的讨论的结束而得出一个新的idea,架

Senparc.Weixin.MP SDK 微信公众平台开发教程(二十一):在小程序中使用 WebSocket (.NET Core)

本文将介绍如何在 .NET Core 环境下,借助 SignalR 在小程序内使用 WebSocket.关于 WebSocket 和 SignalR 的基础理论知识不在这里展开,已经有足够的参考资料,例如参考 SignalR 的官方教程:https://docs.microsoft.com/zh-cn/aspnet/core/signalr/introduction?view=aspnetcore-2.1 我们先看一下完成本教程内容后,在小程序内实现的 WebSocket 效果: 私有及群发消息

基于.NET的轻量级微信SDK

一.前言 特别不喜欢麻烦的一个人,最近碰到了微信开发.下载下来了一些其他人写的微信开发“框架”,但是被恶心到了,实现的太臃肿啦. 最不喜欢的就是把微信返回的xml消息在组装成实体类,所以会比较臃肿,现在都提倡轻量级,所以有什么办法可以避免大量实体类的存在呢. 当然,还有包装的比较繁杂,看完官方API后,再看"框架",让人感觉一头雾水,不够清晰.明了. 二.我的实现思路 我的微信SDK(不敢自称框架),最重要的实现2个目标: 1.轻量级,就是要摒弃实体类,尽量少的申明Entity,减少S

超级懒汉编写的基于.NET的微信SDK

一.前言 特别不喜欢麻烦的一个人,最近碰到了微信开发.下载下来了一些其他人写的微信开发"框架",但是被恶心到了,实现的太臃肿啦. 最不喜欢的就是把微信返回的xml消息在组装成实体类,所以会比较臃肿,现在都提倡轻量级,所以有什么办法可以避免大量实体类的存在呢. 当然,还有包装的比较繁杂,看完官方API后,再看"框架",让人感觉一头雾水,不够清晰.明了. 二.我的实现思路 我的微信SDK(不敢自称框架),最重要的实现2个目标: 1.轻量级,就是要摒弃实体类,尽量少的申明

微信 js sdk C# 版 invalid signature 问题解决

采用Senparc.Weixin SDK 服务器端代码: using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using Senparc.Weixin.MP.CommonAPIs; using Senparc.Weixin.MP.Helpers; using Senparc