<?php
namespace SRVX\Utils;
use SRVX\Model\SysCfg;

class Wx
{
    /**
     * @param $url
     * @param $data
     * @return bool|string
     */
    public function post($url, $data = '')
    {
        //初始化
        $ch = curl_init($url);
        //设置请求的参数
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
        if ($data) {
            curl_setopt($ch, CURLOPT_POST, 1);//设置请求方式为post
            curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
        }
        curl_setopt($ch, CURLOPT_TIMEOUT, 10);
        //执行发送
        $res = curl_exec($ch);
        //返回
        return $res;
    }

    public function postV1($url, $data = '', $header = [])
    {
        //初始化
        $ch = curl_init($url);
        //设置请求的参数
        curl_setopt ( $ch, CURLOPT_URL, $url );

        curl_setopt ( $ch, CURLOPT_RETURNTRANSFER, true );
        if (!empty($header)) {
            curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
        }
        curl_setopt ( $ch, CURLOPT_CONNECTTIMEOUT, 500 );
        curl_setopt ( $ch, CURLOPT_SSL_VERIFYPEER, FALSE );
        curl_setopt ( $ch, CURLOPT_SSL_VERIFYHOST, false );
        if ($data) {
            curl_setopt ( $ch, CURLOPT_POST, 1 );
            @curl_setopt ( $ch, CURLOPT_POSTFIELDS, $data );
        }
        //执行发送
        $res = curl_exec($ch);
        //返回
        return $res;
    }

    /**
     * curl提交数据
     *
     * @author
     * @version     shop 1.10
     */
    function postCurl($url, $data)
    {
        //初始化
        $ch = curl_init($url);
        //设置请求的参数
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_POST, 1);//设置请求方式为post
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
        curl_setopt($ch, CURLOPT_TIMEOUT, 10);
        //执行发送
        $res = curl_exec($ch);
        //返回
        return $res;
    }

    /**
     * 凭证获取
     * @author
     * @version
     */
    public function getAcessToken()
    {
        $app_id = (new SysCfg())->findFirst(['conditions' => "key = 'wx_official_account_app_id'", 'columns' => ['val']]);
        $app_secret = (new SysCfg())->findFirst(['conditions' => "key = 'wx_official_account_app_secret'", 'columns' => ['val']]);
        $data = [
            'appid' => $app_id->val,
            'secret' => $app_secret->val,
            'grant_type' => 'client_credential'
        ];
        $token = (new Sredis)->redisGet("zyos_access_token");
        if (!$token) {
            $url = $url = "https://api.weixin.qq.com/cgi-bin/token";
            $res = json_decode($this->post($url, $data), true);
            (new Sredis)->redisSet("zyos_access_token", $res['access_token'], 3600);
            return $res['access_token'];
        }
        return $token;
    }

}

