<?php
/**
 * 微信开放平台
 * @Copyright (C) 2018 汉潮 All rights reserved.
 * @License http://www.hanchao9999.com
 * @Author xiaogg <xiaogg@sina.cn>
 */

namespace Common\Vendor;
class Weixinopen{
	private $config;
	public function __construct(){
	    if(empty($this->config)) {$this->config=S('wxconfig');}
        if(empty($this->config)) {
            $this->config = require(ROOT_PATH . '/wxconfig/config.php');
            S('wxconfig',$this->config);
        }
    }
    /**
     * 接受安全component_verify_ticket的方法
     */
    public function receive_ticket(){
        $streamData = file_get_contents('php://input');
        $data = (array)simplexml_load_string($streamData);
        $encrypt=implode(',',$data);
        $encrypt=substr($encrypt,19);
        $getdata=I('get.');
        $timeStamp  = empty($getdata['timestamp'])     ? ""    : trim($getdata['timestamp']) ; 
        $nonce      = empty($getdata['nonce'])     ? ""    : trim($getdata['nonce']) ;
        $msg_sign   = empty($getdata['msg_signature']) ? ""    : trim($getdata['msg_signature']) ;
        $this->resolve_xml($encrypt,$timeStamp,$nonce,$msg_sign);
    }
   /**
    * 解密 安全 component_verify_ticket
    */
   private function  resolve_xml($encrypt,$timeStamp,$nonce,$msg_sign){
       $encodingAesKey = $this->config['WX_ENCODINGAESKEY'];//公众号消息加解密Key
       $token = $this->config['WX_TOKEN']; //公众号消息校验Token 
       $appId = $this->config['WX_OPEN_APPID'];  //开放平台的appid
       $pc = new \Common\Vendor\Weixinopen\WXBizMsgCrypt($token, $encodingAesKey, $appId);
       $format = "<xml><ToUserName><![CDATA[".$appId."]]></ToUserName><Encrypt><![CDATA[%s]]></Encrypt></xml>";
       $from_xml = sprintf($format, $encrypt);
       $msg = '';
       /**      
        * 解密成功的方法返回值0的时候 解密成功
        */
       $errCode = $pc->DecryptMsg($msg_sign, $timeStamp, $nonce, $from_xml, $msg);
       if($errCode==0){
          $res=simplexml_load_string($msg,NULL,LIBXML_NOCDATA);
          $ComponentVerifyTicket=(string)$res->ComponentVerifyTicket;
          $InfoType=(string)$res->InfoType;
          if($ComponentVerifyTicket){//推送component_verify_ticket
              $array=array(
                'component_verify_ticket'=>$ComponentVerifyTicket,
                'addtime'=>NOW_TIME,
              );
              $this->wxcache('verify_ticket.php',$array);
          }
          if($InfoType){
               switch ($InfoType){
                   case 'authorized':
                           //此处为授权
        file_put_contents('uploads/PAYauthorized_'.time().'.txt',var_export($msg,1));
                   break;      
                   case 'unauthorized':
                          //此处为取消授权
        file_put_contents('uploads/PAYunauthorized_'.time().'.txt',var_export($msg,1));
                   default:
               }
          }
          echo "success";
       }else{
          echo  $errCode; //显示错误代码
       }
   }
   /**
    * 获取第三方平台令牌（component_access_token） 
    */
   public function get_component_access_token(){

       $component_appid=$this->config['WX_OPEN_APPID'];  //开放平台的appId
       $component_appsecret=$this->config['WX_OPEN_APPSECRET'];//开放平台的AppSecret
       $component_verify_ticket=$this->get_verify_ticket(); //最开始获取放到数据库中，十分钟更新一次。微信服务器每隔10分钟会向第三方的消息接收地址推送一次component_verify_ticket，用于获取第三方平台接口调用凭据
       $url="https://api.weixin.qq.com/cgi-bin/component/api_component_token";
       $vars='{
                "component_appid":"'.$component_appid.'" ,
                "component_appsecret": "'.$component_appsecret.'",
                "component_verify_ticket": "'.$component_verify_ticket.'" 
                }';
       $result=$this->curl_post_ssl($url,$vars);
       $result_json=json_decode($result);
       $component_access_token=(string)$result_json->component_access_token;
       return $component_access_token;
   }
   /**
    * 获取预授权码
    */   
   private function get_pre_auth_code(){
       $component_appid=$this->config['WX_OPEN_APPID'];       
       $component_access_token=$this->get_component_access_token();
       $url="https://api.weixin.qq.com/cgi-bin/component/api_create_preauthcode?component_access_token=".$component_access_token;
       $vars='{
                "component_appid":"'.$component_appid.'" 
                }';
       $result=$this->curl_post_ssl($url,$vars);
       $result_json=json_decode($result);
       $pre_auth_code=(string)$result_json->pre_auth_code;
       return $pre_auth_code;
   }
   /** 返回 绑定界面url*/
   public function get_bind_url($appid,$morecode=''){
       $return =array('status'=>0,'info'=>'');
       if(empty($appid)){$return['info']='站点ID错误';return $return;}
       $component_appid=$this->config['WX_OPEN_APPID'];// appid
       $pre_auth_code=$this->get_pre_auth_code();  //预授权码
       if(empty($morecode)){
           $redirect_uri=U('Saas/Weixin/callback',array('appid'=>$appid),true,true);
       }else{
           $redirect_uri=U('Saas/Weixin/callback',array('appid'=>$appid,'morecode'=>$morecode),true,true);
       }
       $url='https://mp.weixin.qq.com/cgi-bin/componentloginpage?component_appid='.$component_appid.'&pre_auth_code='.$pre_auth_code.'&redirect_uri='.$redirect_uri;
       if(I('auth_type'))$url.='&auth_type='.I('auth_type');
       $return['status']=1;
       $return['info']=$url;
       return $return;
   }
   /**
    * 使用授权码换取公众号或小程序的接口调用凭据和授权信息
    */
   public function authorization_code($get){   
       $component_appid=$this->config['WX_OPEN_APPID'];
       if(empty($get['auth_code']) || empty($get['appid']))return false;    
       $component_access_token=$this->get_component_access_token();
       $url="https://api.weixin.qq.com/cgi-bin/component/api_query_auth?component_access_token=".$component_access_token;
       $vars='{
                "component_appid":"'.$component_appid.'", 
                "authorization_code":"'.$get['auth_code'].'" 
                }';
       $result=$this->curl_post_ssl($url,$vars);
       $result_json=json_decode($result,1);
       if(empty($result_json) || !empty($result_json['errcode']))return $result_json;
       $result_json['shopid']=$get['appid'];
       $result_json['expires_time']=NOW_TIME+$result_json['authorization_info']['expires_in'];
       $wxconfig=$this->wxconfig($get['appid'],$result_json);
       return true;
   }
   /**
    * 为小程序或公众号创建开放平台
    * '{"open_appid":"wxbe8d530bcc1f8ef5","errcode":0,"errmsg":"ok"}'
    * '{"errcode":89000,"errmsg":"account has bound open hint: [Wl6PLa09983125]"}'
    * https://my.oschina.net/xiaogg/blog/1934116
    */
   public function open_create($appid='',$type=0){
       $component_appid=$this->config['WX_OPEN_APPID'];
       if(empty($appid))return false;    
       $component_access_token=$this->get_access_token($appid,$type);
       $url="https://api.weixin.qq.com/cgi-bin/open/create?access_token=".$component_access_token;
       $vars='{
                "appid":"'.$appid.'"
              }';
       $result=$this->curl_post_ssl($url,$vars);
       $result_json=json_decode($result,1);
       return $result_json;
   }   
   public function open_bind($appid='',$type=0,$open_appid=''){//绑定
       $component_appid=$this->config['WX_OPEN_APPID'];
       if(empty($appid))return false;
       if(empty($open_appid))$open_appid=C('OPEN_APPID');
       $component_access_token=$this->get_access_token($appid,$type);
       $url="https://api.weixin.qq.com/cgi-bin/open/bind?access_token=".$component_access_token;
       $vars='{
                "appid":"'.$appid.'",
                "open_appid":"'.$open_appid.'"
              }';
       $result=$this->curl_post_ssl($url,$vars);
       $result_json=json_decode($result,1);
       //
       $siteid=C('APPID');
       $authorization_info=$appid.'_'.$siteid.'.php';
       $old= $this->wxcache($authorization_info);
       $old['wx_open_appid']=$open_appid;
       $this->wxcache($authorization_info,$old);
       //
       return $result_json;
   }
   public function open_unbind($appid='',$type=0,$open_appid=''){//解绑
       $component_appid=$this->config['WX_OPEN_APPID'];
       if(empty($appid))return false;
       if(empty($open_appid))$open_appid=C('OPEN_APPID');
       $component_access_token=$this->get_access_token($appid,$type);
       $url="https://api.weixin.qq.com/cgi-bin/open/unbind?access_token=".$component_access_token;
       $vars='{
                "appid":"'.$appid.'",
                "open_appid":"'.$open_appid.'"
              }';
       $result=$this->curl_post_ssl($url,$vars);
       $result_json=json_decode($result,1);
       return $result_json;
   }
   public function open_get_appid($appid='',$type=0){//获取开放平台帐号
       $component_appid=$this->config['WX_OPEN_APPID'];
       if(empty($appid))return false;    
       $component_access_token=$this->get_access_token($appid,$type);
       $url="https://api.weixin.qq.com/cgi-bin/open/get?access_token=".$component_access_token;
       $vars='{
                "appid":"'.$appid.'"
              }';
       $result=$this->curl_post_ssl($url,$vars);
       $result_json=json_decode($result,1);
       return $result_json;
   }
    /**获取开放平台的open_appid
     * @param string
     * @return bool
     */
    public function open_bind_wxall($appid){
        if(empty($appid))return false;
        $open_appid=C("OPEN_APPID");
        if($open_appid)return true;
        $wxinfo=$this->wxconfig($appid);
        if($wxinfo) {
            $authorizer_appid = $wxinfo['authorization_info']['authorizer_appid'];
            if (empty($open_appid)) {
                $res = $this->open_get_appid($authorizer_appid);
                if ($res['errcode'] == 0) {
                    $new_appid = $res['open_appid'];
                } else {
                    $res = $this->open_create($authorizer_appid);
                    if ($res['errcode'] == 0) {
                        $new_appid = $res['open_appid'];
                    }
                }
                if($new_appid){
                    $map = $data = array();
                    $map['name'] = 'OPEN_APPID';
                    $data['value'] = $new_appid;
                    $count = M("Config")->where($map)->count();
                    if (empty($count)) {
                        $save = M("Config")->where($map)->add($data);
                    } else {
                        $save = M("Config")->where($map)->save($data);
                    }
                }else{
                    //print_r($res);
                }
                if ($save) {
                    S('DB_CONFIG_DATA', null);
                    return true;
                } else {
                    return false;
                }
            } else {
                return true;
            }
        }else{
            return true;
        }
    }
   /**
    * 获取当前授权access_token
    * @param $appid 站点id或应用id
    * @param 类型 0 微信 1小程序
    */
   public function get_access_token($appid,$type=0){
        $return =array('status'=>0,'info'=>'');
        if(empty($appid))return false;
        $wxconfig= $this->wxconfig($appid,'',$type);        
        if(empty($wxconfig) || empty($wxconfig['authorization_info']['authorizer_access_token'])){
            $return['info']='access_token获取失败';return $return;
        }else{
            $access_token=$wxconfig['authorization_info']['authorizer_access_token'];
            $access_token_time=$wxconfig['expires_time'];
            if($access_token && $access_token_time>NOW_TIME){
            }elseif($wxconfig['authorization_info']['authorizer_refresh_token']){
                $access_token= $this->refresh_token($wxconfig);
                if(empty($access_token))$access_token=$wxconfig['authorization_info']['authorizer_access_token'];
            }
            return $access_token;
        }
   }
   //刷新token
   public function refresh_token($wxconfig=''){
       if(empty($wxconfig))return false;
       $component_appid=$this->config['WX_OPEN_APPID'];       
       $component_access_token=$this->get_component_access_token();
       $url="https://api.weixin.qq.com/cgi-bin/component/api_authorizer_token?component_access_token=".$component_access_token;
       $appid=$wxconfig['authorization_info']['authorizer_appid'];
       $refresh_token=$wxconfig['authorization_info']['authorizer_refresh_token'];
       $vars='{
                "component_appid":"'.$component_appid.'",
                "authorizer_appid":"'.$appid.'",
                "authorizer_refresh_token":"'.$refresh_token.'",
                }';
       $result=$this->curl_post_ssl($url,$vars);
       $result_json=json_decode($result,1);
       if($result_json['errcode']=='61023'){//refresh_token is invalid
            $refresh_token_new=$this->get_refresh_token($appid);
            if($refresh_token_new){
                $wxconfig['authorization_info']['authorizer_refresh_token']=$refresh_token_new;
                return $this->refresh_token($wxconfig);
            }
       }
       $wxconfig['expires_time']=NOW_TIME+$result_json['expires_in'];
       if($result_json['authorizer_refresh_token']){
        $wxconfig['authorization_info']['authorizer_access_token']=$result_json['authorizer_access_token'];
        $wxconfig['authorization_info']['expires_in']=$result_json['expires_in'];
        $wxconfig['authorization_info']['authorizer_refresh_token']=$result_json['authorizer_refresh_token'];
       }       
       $this->wxconfig($appid,$wxconfig);
       return $result_json['authorizer_access_token'];
   }
   /**
    * 获取刷新token
    * @param $wx_appid 微信或小程序的应用id
    */
   private function get_refresh_token($wx_appid=''){
        $authinfo=$this->get_authorizer_info($wx_appid);
        return $authinfo['authorization_info']['authorizer_refresh_token'];
   }
   
   /**
    * 获取授权方的帐号基本信息
    */
   public function get_authorizer_info($appid=''){   
       if(empty($appid))$appid=$this->getappid();
       if(empty($appid))return false;  
       $component_appid=$this->config['WX_OPEN_APPID'];  
       $component_access_token=$this->get_component_access_token();
       $url="https://api.weixin.qq.com/cgi-bin/component/api_get_authorizer_info?component_access_token=".$component_access_token;
       $vars='{
                "component_appid":"'.$component_appid.'", 
                "authorizer_appid":"'.$appid.'" 
                }';
       $result=$this->curl_post_ssl($url,$vars);
       $result_json=json_decode($result,1);
       if(empty($result_json) || !empty($result_json['errcode']))return $result_json;
       return $result_json;
   }
   //识别二维码内容
   public function get_wxqrcode($username=''){
        if(empty($username))return false;
        $paramurl ='http://open.weixin.qq.com/qr/code?username='.$username;
        $result=$this->get_wxqrcode1($paramurl);
        if(!empty($result)){return $result;}
        return $this->get_wxqrcode2($paramurl);
   }//识别二维码内容api1
   public function get_wxqrcode1($url){
        if(empty($url))return false;
        $param =array('data'=>$url);
        $url='https://cli.im/api/browser/deqr';
        $result=$this->curl_post_ssl($url,$param);
        $result_json=json_decode($result,1);
        if(!empty($result_json['data']['RawData'])){
            return $result_json['data']['RawData'];
        }
        return $this->get_wxqrcode2($username);
   }//识别二维码内容api2
   public function get_wxqrcode2($url=''){
        if(empty($url))return false;
        $param =array('url'=>$url);
        $url='https://tool.bitefu.net/qreader/';
        $result=$this->curl_post_ssl($url,$param);
        $result_json=json_decode($result,1);
        if($result_json['status']==1 && !empty($result_json['info'])){
            return $result_json['info'];
        }return false;
   }
   //获取商户appid
   public function getappid(){
        $appid= C('appid');
        if(empty($appid))$appid=I('request.appid');
        $config= $this->wxconfig($appid);
        return $config['authorization_info']['authorizer_appid'];
   }
   //获取请求CODEurl
   public function returngetcode(){
        $appid=$this->getappid();
        $mobile_url=session('mobile_url');
        if(empty($mobile_url) || !str_exists($mobile_url,'http')){            
            $callbackurl = GetCurUrl();
            $url_parse=parse_url($callbackurl);
            session("mobile_url",$callbackurl);
        }
        $callback='http://'.BASE_DOMAIN.'/saasapi.php/Weixin/getwxuserwxid/appid/'.$appid.'.html';
        $component_appid=$this->config['WX_OPEN_APPID'];  
        $param ['appid'] = $appid;
        $param ['redirect_uri'] = $callback . '?getOpenId=1';
        $param ['response_type'] = 'code';
        $param ['scope'] = 'snsapi_userinfo';//snsapi_base
        $param ['state'] = 'hanchaowx';
        $param ['component_appid'] = $component_appid;
        return 'https://open.weixin.qq.com/connect/oauth2/authorize?' . http_build_query ( $param ) . '#wechat_redirect';
   }
   /**
    * 通过code换取access_token并获取用户openid
    */
   public function getwxopenid($code,$auto=1){
        $component_appid=$this->config['WX_OPEN_APPID'];
        $component_access_token=$this->get_component_access_token();
        $param ['appid'] = $this->getappid();
        $param ['code'] = $code;
        $param ['grant_type'] = 'authorization_code';
        $param ['component_appid'] = $component_appid;
        $param ['component_access_token'] = $component_access_token;
        $url = 'https://api.weixin.qq.com/sns/oauth2/component/access_token?'.http_build_query ( $param );
        $content = curlget ( $url );
        $content = json_decode ( $content, true );
        if($content['openid']){session('wxopenid',$content['openid']);
            $sessionname='wxtoken'.$param['appid'];
            $content['expires_time']=NOW_TIME+$content['expires_in'];
            //在此存储配置更新到数据库
            $this->update_wx_access_token($content);
        }
        if($auto==1)redirect ( $callback . '&openid=' . openid_encode($content['openid']));
        else return $content['openid'];
   }//在此存储配置更新到数据库
   public function update_wx_access_token($token){
        if(empty($token['openid']))return false;C('TOKEN_ON',false);
        $mod=M('WxAccessToken');
        $map=array();
        $map['openid']=$token['openid'];
        $check=$mod->where($map)->count();
        $data=$mod->create($token);
        if($check){            
            $result=$mod->where($map)->save($data);
        }else{
            $result=$mod->add($data);
        }return true;
   }
   //获取客户端access_token
   public function getwx_access_token($openid=''){
        if(empty($openid))$openid=get_openid();
        if(empty($openid))return false;
        $map=array();
        $map['openid']=$openid;
        $token=M('WxAccessToken')->where($map)->field(true)->find();       
        if($token && $token['access_token'] && $token['expires_time']>NOW_TIME){return $token['access_token'];}
        if($token && $token['refresh_token']){return $this->wxrefresh_token($openid);}
        $url=$this->returngetcode();
        redirect ($url);
   }
   //刷新客户端access_token
   private function wxrefresh_token($openid=''){
        if(empty($openid))$openid=get_openid();
        if(empty($openid))return false;
        $map=array();
        $map['openid']=$openid;
        $token=M('WxAccessToken')->where($map)->field(true)->find();
        
        $component_appid=$this->config['WX_OPEN_APPID'];
        $component_access_token=$this->get_component_access_token();
        $param ['appid'] = $this->getappid();
        $param ['grant_type'] = 'refresh_token';
        $param ['component_appid'] = $component_appid;
        $param ['component_access_token'] = $component_access_token;
        $param ['refresh_token'] = $token['refresh_token'];
        $url = 'https://api.weixin.qq.com/sns/oauth2/component/refresh_token?'.http_build_query ( $param );
        $content = curlget ( $url );
        $content = json_decode ( $content, true );
        if($content){
            if($content['access_token'])$token['access_token']=$content['access_token'];
            if($content['refresh_token'])$token['refresh_token']=$content['refresh_token'];
            $token['expires_time']=NOW_TIME+$content['expires_in'];
            //在此存储配置更新到数据库
            $this->update_wx_access_token($content);
        }
        return $content['access_token'];
   }
   /**
    * 通过code换取access_token并获取用户openid
    */
   public function getwxuserinfo($openid=''){
        if(empty($openid))return false;
        $access_token=$this->getwx_access_token($openid);
        $param ['access_token'] = $access_token;
        $param ['openid'] = $openid;
        $param ['lang'] = 'zh_CN';
        $url = 'https://api.weixin.qq.com/sns/userinfo?'.http_build_query($param);
        //file_put_contents('uploads/PAY-wx'.$openid.'.txt',$url);
        $content = curlget ( $url );
        $content = json_decode ($content, true);
        return $content;
   }
   /**
     * 判断当前是否为小程序配置
     * @param $array 授权数组
     */
   private function is_smallapp($array){
        $first=intval($array['authorization_info']['func_info'][0]['funcscope_category']['id']);
        return in_array($first,array(17,18,19,25));
   }
   /**
    * 公众号配置的存取
    * @param $appid 可传站点id 也可传公众号id
    * @param $data 配置值 为空则为获取
    * @param $type 当为获取的时候 $type有效 0 微信配置 1小程序
    */
   public function wxconfig($appid,$data='',$type=0){
       if(empty($appid))return false;
       $cachename_more='config_more.php';
       if(empty($data)){//获取配置
            $siteid='';
            if(strlen($appid)>10){//传输入应用id检索
                $config_more=$this->wxcache($cachename_more);
                if(!empty($config_more) && !empty($config_more[$appid])){
                    $siteid=$config_more[$appid];
                }
            }
            if(empty($siteid)){
                $cachename=$type==1?'config_listsmall.php':'config_list.php';
                $config_list=$this->wxcache($cachename);
                if(empty($config_list))return false;$siteid=$appid;
                if(strlen($appid)>10){
                    $siteid=array_search($appid,$config_list);
                }else{
                    $appid=$config_list[$siteid];
                }
            }
            $authorization_info=$appid.'_'.$siteid.'.php';
            return $this->wxcache($authorization_info);
       }else{
            $siteid=$appid;
            if(strlen($siteid)>10){$siteid=$data['shopid'];}
            $appid=$data['authorization_info']['authorizer_appid'];
            if($this->is_smallapp($data)){
                $cachename='config_listsmall.php';
                $morecode=I('morecode');
                if($morecode){
                    $cachename_moresmall='config_moresmall.php';
                    $config_morelist=$this->wxcache($cachename_moresmall);
                    $config_morelist[$siteid.'_'.$morecode]=$appid;
                    $this->wxcache($cachename_moresmall,$config_morelist);
                }
            }else{
                $cachename='config_list.php';
            }
            $config_list=$this->wxcache($cachename);
            $config_more=$this->wxcache($cachename_more);            
            
            //去除重复
            if($config_list){
                $checkkey=array_search($appid,$config_list);
                if(!empty($checkkey))unset($config_list[$checkkey]);
            }           
            
            $config_list[$siteid]=$appid;
            $config_more[$appid]=$siteid;
            $this->wxcache($cachename,$config_list);
            $this->wxcache($cachename_more,$config_more);
            $authorization_info=$appid.'_'.$siteid.'.php';
            return $this->wxcache($authorization_info,$data);
       }
   }
   /*测试接受消息的方法*/
   public function receive_new(){
       $streamData = file_get_contents('php://input'); 
       $data = (array)simplexml_load_string($streamData);
       $encrypt=implode(',',$data);
       $encrypt_array=explode(',',$encrypt);
       $encrypt=$encrypt_array[1];
       $getdata=I('get.');
       //file_put_contents('uploads/PAYreceive_get_'.time().'.txt',var_export($getdata,1));     
       $timeStamp  = empty($getdata['timestamp'])     ? ""    : trim($getdata['timestamp']) ;
       $nonce      = empty($getdata['nonce'])     ? ""    : trim($getdata['nonce']) ;
       $msg_sign   = empty($getdata['msg_signature']) ? ""    : trim($getdata['msg_signature']) ;
       $encodingAesKey = $this->config['WX_ENCODINGAESKEY'];//公众号消息加解密Key
       $token = $this->config['WX_TOKEN']; //公众号消息校验Token 
       $appId = $this->config['WX_OPEN_APPID'];  //开放平台的appid 
       $pc = new \Common\Vendor\Weixinopen\WXBizMsgCrypt($token, $encodingAesKey, $appId);
       /**
        * 读出  encrypt参数
        * 安全机制 解密参数格式  $format
       */
       $format = "<xml><ToUserName><![CDATA[".$appId."]]></ToUserName><Encrypt><![CDATA[%s]]></Encrypt></xml>";
       $from_xml = sprintf($format, $encrypt);
       $msg = '';
       $errCode = $pc->decryptMsg($msg_sign, $timeStamp, $nonce, $from_xml, $msg);
       if($errCode==0){
           $res=json_decode(json_encode(simplexml_load_string($msg,'SimpleXMLElement',LIBXML_NOCDATA)),1);
           if(is_array($res) && $res){
      // file_put_contents('uploads/PAYreceive_data_'.time().'.txt',var_export($res,1));
                $weixinresponse=new \Common\Vendor\Weixinresponse;
                $backdata=$weixinresponse->reply($res);
                if($backdata['type'] && $backdata['content']){
                    $weixin = new \Common\Vendor\WeixinChat;
                    $weixin->setData($res);
                    $response=$weixin->response($backdata['content'],$backdata['type'],0,0);
                    $encryptMsg = '';
                    $errCode = $pc->encryptMsg($response, $timeStamp, $nonce, $encryptMsg);
                    if ($errCode == 0) {
                    	echo  $encryptMsg;return ;
                    } else {
                    	print($errCode . "\n");
                    }
                }
           }
       }
   }
   public function wxcache($name,$value=''){
        if(empty($name))return false;
        $name=ROOT_PATH.'/wxconfig/'.$name;
        if($value){
            $con = "<?php return;//".json_encode($value)."?>";
            oaofile($name, $con);
        }else{
            $content=oaofile($name);
            $content=strtr($content,array('<?php return;//'=>'','?>'=>''));
            return json_decode($content,1);
        }
   }
   //获取第三方平台接口调用凭据
   private function get_verify_ticket(){
        $verify_ticket=$this->wxcache('verify_ticket.php');
        if($verify_ticket && !empty($verify_ticket['component_verify_ticket'])){
            return $verify_ticket['component_verify_ticket'];
        }else return false;
   }
   public function curl_post_ssl($url,$vars,$second=30,$aHeader=array()){
       $ch = curl_init();
       //超时时间
       curl_setopt($ch,CURLOPT_TIMEOUT,$second);
       curl_setopt($ch,CURLOPT_RETURNTRANSFER, 1);
       //这里设置代理，如果有的话
       curl_setopt($ch,CURLOPT_URL,$url);
       curl_setopt($ch,CURLOPT_SSL_VERIFYPEER,false);
       curl_setopt($ch,CURLOPT_SSL_VERIFYHOST,false);
       if( count($aHeader) >= 1 ){
           curl_setopt($ch, CURLOPT_HTTPHEADER, $aHeader);
       }
       curl_setopt($ch,CURLOPT_POST, 1);
       curl_setopt($ch,CURLOPT_POSTFIELDS,$vars);
       $data = curl_exec($ch);
       if($data){
           curl_close($ch);
           return $data;
       }else {
           $error = curl_errno($ch);
           curl_close($ch);
           return false;
       }
   }
}
?>