<?php
/**
 * 微信小程序开放平台
 * @Copyright (C) 2018 汉潮 All rights reserved.
 * @License http://www.hanchao9999.com
 * @Author xiaoq <570035208@qq.com>
 */
namespace Common\Vendor;
class Wxsmallopen{
	private $config;
    public $small_appid;
    private $wx;
	public function __construct($param=array()){
        if(empty($param))$param = I('param.');
        $this->access_token = $this->get_token($param);
    }
    /**
    * 设置小程序服务器域名 
    */
    public function modify_domain($param=array()){
        $url="https://api.weixin.qq.com/wxa/modify_domain?access_token=".$this->access_token;
        //file_put_contents('uploads/PAYdomain_url_'.time().'.txt',var_export($url,1));
        if(empty($param)&&!isset($param['action']))return;
        //file_put_contents('uploads/PAYdomain_param_'.time().'.txt',var_export($param,1));
        $result=$this->curl_post_ssl($url,json_encode($param));
        return json_decode($result,true);
    }
    /**
    * 设置小程序业务域名 
    */
    public function modify_webviewdomain($param=array()){
        $url="https://api.weixin.qq.com/wxa/setwebviewdomain?access_token=".$this->access_token;
        if(empty($param)&&!isset($param['action']))return;
        $result=$this->curl_post_ssl($url,json_encode($param));
        return json_decode($result,true);
    }
    /**
     * 为授权的小程序帐号上传小程序代码
     */
    public function commit($param){
        $url="https://api.weixin.qq.com/wxa/commit?access_token=".$this->access_token;
        if(!isset($param['template_id'])||empty($param['extAppid'])){
            return true;
        }
        $cachename_moresmall='config_moresmall.php';        
        $this->wx = new \Common\Vendor\Weixinopen;
        $config_morelist=$this->wx->wxcache($cachename_moresmall);
        $appid_array=array();
        $appid=C("appid");
        foreach($config_morelist as $key=>$val){
            if(strstr($key,$appid."_")){
                $appid_array[]=$val;
            }
        }
        $commit = array(
            "template_id"=>$param['template_id'],
            "ext_json"=>json_encode(array(
                "extAppid"=>$param['extAppid'],
                "ext"=>array(
                    "attr"=>C('appid')
                ),
                "navigateToMiniProgramAppIdList"=>$appid_array
                )
            ),
            "user_version"=>HANCHAO_WXSMALL_VERSION,
            "user_desc"=>"汉潮微信小程序"
        );
        $result=$this->curl_post_ssl($url,json_encode($commit,JSON_UNESCAPED_UNICODE));
        return json_decode($result,true);
    }
    /**
     * 获取体验小程序的体验二维码
     */
    public function get_qrcode(){
        $url="https://api.weixin.qq.com/wxa/get_qrcode?access_token=".$this->access_token;
        $result=curlget($url);
        return $this->data_uri($result);
    }
    public function data_uri($contents, $mime='image/png') {  
        $base64   = base64_encode($contents);  
        return ('data:' . $mime . ';base64,' . $base64);  
    } 
    /**
     * 将第三方提交的代码包提交审核
     */
    public function submit_audit(){
        //1.获取授权小程序帐号的可选类目
        $return = array('status'=>0,'msg'=>'小程序参数配置错误');
        $url="https://api.weixin.qq.com/wxa/get_category?access_token=".$this->access_token;
        $result=curlget($url);
        $result=json_decode($result,true);
        $category_list = $page_list = array();
        if($result['errcode']==0&&$result['errmsg']=='ok'){
            $category_list = $result['category_list'][1]?$result['category_list'][1]:$result['category_list'][0];//"category_list":[{"first_class":"商业服务","second_class":"广告\/设计","first_id":402,"second_id":774}]
        }else{
            return $return;
        }
        //2.获取小程序的第三方提交代码的页面配置
        $url="https://api.weixin.qq.com/wxa/get_page?access_token=".$this->access_token;
        $result=curlget($url);
        $result=json_decode($result,true);
        if($result['errcode']==0&&$result['errmsg']=='ok'){
            $page_list = $result['page_list'];
        }else{
            return $return;
        }
        //3.将第三方提交的代码包提交审核
        $url="https://api.weixin.qq.com/wxa/submit_audit?access_token=".$this->access_token;
        $data = array(
            "item_list"=>array(
                array(
                    'address'=>$page_list[0],
                    'tag'=>'汉潮 小程序',
                    'first_class'=>$category_list['first_class'],
                    'second_class'=>$category_list['second_class'],
                    'third_class'=>$category_list['third_class'],
                    "first_id"=>$category_list['first_id'],
                    "second_id"=>$category_list['second_id'],
                    "third_id"=>$category_list['third_id'],
                    "title"=>"首页"
                )
            )
        );
        $result=$this->curl_post_ssl($url,json_encode($data,JSON_UNESCAPED_UNICODE));
        $result=json_decode($result,true);
        if($result['errcode']==0&&$result['errmsg']=='ok'){
            $return['status'] = 1;
            $return['msg'] = '提交成功！';
        }else{
            $return['msg'] = $this->error_code($result['errcode']);
        }
        return $return;
    } 
    
    /**
     * 查询最新一次提交的审核状态
     */
    public function get_latest_auditstatus(){
        $url="https://api.weixin.qq.com/wxa/get_latest_auditstatus?access_token=".$this->access_token;
        $result=curlget($url);
        $result=json_decode($result,true);//0为审核成功，1为审核失败，2为审核中
        $status = array('审核成功','审核失败','审核中');
        if($result['errcode']==0&&$result['errmsg']=='ok'){
            $result['info'] = $status[$result['status']];
        }
        return $result;
    }
    /**
     * 查询最新一次提交的审核状态
     */
    public function release(){
        $url="https://api.weixin.qq.com/wxa/release?access_token=".$this->access_token;
        $result=$this->curl_post_ssl($url,'{}');
        $result=json_decode($result,true);//0为审核成功，1为审核失败，2为审核中
        $status = array("-1"=>'系统繁忙',"85019"=>'没有审核版本',"85020"=>'审核状态未满足发布');
        $result['info'] = $status[$result['errcode']];
        return $result;
    }
    /**
     * 获取校验文件名称及内容
     */
    public function qrcodejumpdownload(){
        $url="https://api.weixin.qq.com/cgi-bin/wxopen/qrcodejumpdownload?access_token=".$this->access_token;
        $result=$this->curl_post_ssl($url,'{}');
        $result=json_decode($result,true);
        $result['msg'] = $this->error_code($result['errcode'],1);
        return $result;
    }
    /**
     * 添加规则
     */
    public function qrcodejumpadd(){
        $url="https://api.weixin.qq.com/cgi-bin/wxopen/qrcodejumpadd?access_token=".$this->access_token;
        $data = array(
            "prefix"=>"https://".BASE_DOMAIN."/qrcodejump?appid=".C('appid'),
            "permit_sub_rule"=>"1",
            "path"=>"pages/index/index",
            "open_version"=>"1",
            "debug_url"=>array(
                "https://".BASE_DOMAIN."/qrcodejump?appid=".C('appid').'&test=1',
                "https://".BASE_DOMAIN."/qrcodejump?appid=".C('appid').'&test=2',
            ),
            "is_edit"=>0
        );
        $result=$this->curl_post_ssl($url,json_encode($data));
        $result=json_decode($result,true);
        $result['qrcodeconfig'] = $data;
        $result['msg'] = $this->error_code($result['errcode'],1);
        return $result;
    }
    /**
     * 发布规则
     */
    public function qrcodejumppublish($data){
        $url="https://api.weixin.qq.com/cgi-bin/wxopen/qrcodejumppublish?access_token=".$this->access_token;
        $data = array(
            "prefix"=>"https://".BASE_DOMAIN."/qrcodejump?appid=".C('appid'),
        );
        $result=$this->curl_post_ssl($url,json_encode($data));
        $result=json_decode($result,true);
        $result['msg'] = $this->error_code($result['errcode'],1);
        return $result;
    }
    /**
     * 添加成员
     */
    public function bind_tester($wechatid){
        $url="https://api.weixin.qq.com/wxa/bind_tester?access_token=".$this->access_token;
        $data = array(
            "wechatid"=>$wechatid,
        );
        $result=$this->curl_post_ssl($url,json_encode($data));
        $result=json_decode($result,true);
        $result['msg'] = $this->error_code($result['errcode'],2);
        return $result;
    }
    /**
     * 解除关系
     */
    public function unbind_tester($wechatid){
        $url="https://api.weixin.qq.com/wxa/unbind_tester?access_token=".$this->access_token;
        $data = array(
            "wechatid"=>$wechatid,
        );
        $result=$this->curl_post_ssl($url,json_encode($data));
        $result=json_decode($result,true);
        $result['msg'] = $this->error_code($result['errcode'],2);
        return $result;
    }
    /**
     * * 主动发送消息
     *
     * @param array  $param   内容数组
     * @param string $url   	url
     * @param string $openid   	发送者用户名
     * @param string $template_id   	模板ID
     * @return array 返回的信息
     */
    public function sendTplMsg($param, $template_id = '') {
        if(empty($param))return false;
        if(strlen($template_id)<16){
            $short_id=$template_id;
            $template_id=$this->get_template_id($short_id);
            if(empty($template_id)){
                return false;
            }else{
                $map=$data=array();
                $map['theme_remark']=$short_id;
                $data['theme_id']=$template_id;
                M('SmsTheme')->where($map)->save($data);
            }
        }
        /* 基础数据 */
        $data = array(
            "touser"=>$param['OPENID'],
            "template_id"=>$template_id,
            "page"=>'pages/index/index',
            "form_id"=>$param['formId'],
            "data"=>array(
                "keyword1"=>array(
                    "value"=> $param['keyword1'],//单号
                ),
                "keyword2"=>array(
                    "value"=> $param['keyword2'],//订单金额
                ),
                "keyword3"=>array(
                    "value"=> $param['keyword3'],//下单时间
                ),
                "keyword4"=>array(
                    "value"=> $param['keyword4'],//物品名称
                )
            )
        );
        /* 发送 */
        $url="https://api.weixin.qq.com/cgi-bin/message/wxopen/template/send?access_token=".$this->access_token;
        $result=$this->curl_post_ssl($url,json_encode($data));
        $result=json_decode($result,true);
        $result['msg'] = $this->error_code($result['errcode'],3);
        return $result;
    }
    /**
     * 获得模板ID
     * @param $short_id 模板库中模板的编号，有“TM**”和“OPENTMTM**”等形式
     */
    public function get_template_id($short_array=array()){
        if(empty($short_array))return false;
        $short_array=explode('|',$short_array);
        $short_id=$short_array[0];
        $short_types=explode(',',$short_array[1]);
        $data=array(
            'id'=>$short_id,
           'keyword_id_list'=>$short_types
        );
        $url="https://api.weixin.qq.com/cgi-bin/wxopen/template/add?access_token=".$this->access_token;
        $result=$this->curl_post_ssl($url,json_encode($data));
        $data=json_decode($result,true);
        return $data['template_id'];


    }
    /**
     * 消息模板
     */
   /* public function message($type=1,$param=array()){
        if(empty($param))return false;
        $url="https://api.weixin.qq.com/cgi-bin/message/wxopen/template/send?access_token=".$this->access_token;
        $data = array(
            "touser"=>$param['OPENID'],
            "template_id"=>'WzM-sW_AXKF6eyd56UfE6zDcWKNPbdigU9T5vU-42jQ',
            "page"=>'pages/index/index',
            "form_id"=>$param['formId'],
            "data"=>array(
                "keyword1"=>array(
                    "value"=> $param['keyword1'],//单号
                ),
                "keyword2"=>array(
                    "value"=> $param['keyword2'],//下单时间
                ),
                "keyword3"=>array(
                    "value"=> $param['keyword3'],//物品名称
                ),
                "keyword4"=>array(
                    "value"=> $param['keyword4'],//订单金额
                )
            )
        );
        $result=$this->curl_post_ssl($url,json_encode($data));
        $result=json_decode($result,true);
        $result['msg'] = $this->error_code($result['errcode'],3);
        return $result;
    }*/
    /**
     * 获取微信openid和unionid
     * @param string $code 用户登录标识
     * @return array 成功时 session_key和openid和unionid 失败时 errcode和errmsg
     */
    public function get_wx_info($code){        
        $this->wx = new \Common\Vendor\Weixinopen;
        $component_access_token=$this->wx->get_component_access_token();
        $url="https://api.weixin.qq.com/sns/component/jscode2session?appid=".$this->small_appid."&js_code=".$code."&grant_type=authorization_code&component_appid=".$this->config['WX_OPEN_APPID']."&component_access_token=".$component_access_token;
        $param=array();
        $res=curlget($url,$param,'POST');
        $res=json_decode($res,1);
        return $res;
    }
    public function get_location_small_code($param=array()){
        // $url="https://api.weixin.qq.com/cgi-bin/wxaapp/createwxaqrcode?access_token=".$this->access_token;
        if(!$this->access_token){
            $this->access_token = $this->get_token($param);
        }
        $url="https://api.weixin.qq.com/wxa/getwxacode?access_token=".$this->access_token;
        $param = array(
            "path"=>$param['path'],
            // "width"=>200,
            );
        $param = json_encode($param);
        $res=$this->curl_post_ssl($url,$param);
        // print_r($res);exit;
        return $this->data_uri($res);
    }
    public function getwxacode($param=array()){
        $url="https://api.weixin.qq.com/wxa/getwxacode?access_token=".$this->access_token;
        
        $param = array(
            "path"=>$param['path'],
            // "width"=>200,
            );
        $param = json_encode($param);
        $res=$this->curl_post_ssl($url,$param);
        // print_r($res);exit;
        return $this->data_uri($res);
    }
    public function get_token($param=array()){
        $appid = getconfig('WX_SHOP_APPID');
        $appsecret = getconfig('WX_SHOP_APPSERCRET');
        if(empty($appid) || empty($appsecret))return false;
        $cachename='smallget_token'.$appid;
        $token=S($cachename);if($token)return $token;        
        $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=$appid&secret=$appsecret";
        $httpstr = curlget($url);
        $harr = json_decode($httpstr, true);
        if($harr['access_token']){
            $cachetime=NOW_TIME+$harr['expires_in'];
            S($cachename,$harr['access_token'],$cachetime);
        }
        return $harr['access_token'];
    }
    public function error_code($code = '-1',$type = 0){
        $error = array(
            array(
                "-1"=>"系统繁忙",
                "86000"=>"不是由第三方代小程序进行调用",
                "86001"=>"不存在第三方的已经提交的代码",
                "85006"=>"标签格式错误",
                "85007"=>"页面路径错误",
                "85008"=>"类目填写错误",
                "85009"=>"已经有正在审核的版本",
                "85010"=>"item_list有项目为空",
                "85011"=>"标题填写错误",
                "85023"=>"审核列表填写的项目数不在1-5以内",
                "85077"=>"小程序类目信息失效（类目中含有官方下架的类目，请重新选择类目）",
                "86002"=>"小程序还未设置昵称、头像、简介。请先设置完后再重新提交。",
            ),
            array(
                "85066"=>"链接错误",
                "85068"=>"测试链接不是子链接",
                "85069"=>"校验文件失败",
                "85070"=>"链接为黑名单",
                "85071"=>"已添加该链接，请勿重复添加",
                "85072"=>"该链接已被占用",
                "85073"=>"二维码规则已满",
                "85074"=>"小程序未发布, 小程序必须先发布代码才可以发布二维码跳转规则",
                "85075"=>"个人类型小程序无法设置二维码规则",
                "85076"=>"链接没有ICP备案",
            ),
            array(
                "-1"=>"系统繁忙",
                "85001"=>"微信号不存在或微信号设置为不可搜索",
                "85002"=>"小程序绑定的体验者数量达到上限",
                "85003"=>"微信号绑定的小程序体验者达到上限",
                "85004"=>"微信号已经绑定",
            ),
            array(
                "40037"=>"template_id不正确",
                "41028"=>"form_id不正确，或者过期",
                "41029"=>"form_id已被使用",
                "41030"=>"page不正确",
                "45009"=>"接口调用超过限额（目前默认每个帐号日调用限额为100万）",
            ),
        );
        return $error[$type][$code];
    }
    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;
        }
    }
}
?>