<?php
include_once("WxPay.pub.config.php");
/**
 * 微信接口 (模板消息)
 */
class WxPlugin
{
    protected $appid;
    protected $secrect;
    protected $accessToken;
 
    function  __construct()
    {
        $this->appid = WxPayConf_pub::APPID;
        $this->secrect = WxPayConf_pub::APPSECRET;
        $this->accessToken = $this->getToken($this->appid, $this->secrect);
    }
 
    /**
     * 发送post请求
     * @param string $url
     * @param string $param
     * @return bool|mixed
     */
    function request_post($url = '', $param = '')
    {
        if (empty($url) || empty($param)) {
            return false;
        }
        $postUrl = $url;
        $curlPost = $param;
        $ch = curl_init(); //初始化curl
        curl_setopt($ch, CURLOPT_URL, $postUrl); //抓取指定网页
        curl_setopt($ch, CURLOPT_HEADER, 0); //设置header
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); //要求结果为字符串且输出到屏幕上
        curl_setopt($ch, CURLOPT_POST, 1); //post提交方式
        curl_setopt($ch, CURLOPT_POSTFIELDS, $curlPost);
        $data = curl_exec($ch); //运行curl
        curl_close($ch);
        return $data;
    }

    /**
     * 发送get请求
     * @param string $url
     * @return bool|mixed
     */
    function request_get($url = '')
    {
        if (empty($url)) {
            return false;
        }
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        $data = curl_exec($ch);
        curl_close($ch);
        return $data;
    }

    /**
     * 获取token
     * @param $appid
     * @param $appsecret
     * @return mixed
     */
    protected function getToken($appid, $appsecret)
    {
        if (S($appid)) {
            $access_token = S($appid);
        } else {
            $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=$appid&secret=$appsecret";
            $token = $this->request_get($url);
            $token = json_decode(stripslashes($token));
            $arr = json_decode(json_encode($token), true);
            $access_token = $arr['access_token'];
            S($appid, $access_token, 7000);
        }
        return $access_token;
    }

    /**
     * 查看 access_token
     */
    public function viewToken()
    {
        return $this->accessToken;
    }

    /**
     * 发送自定义的模板消息
     * @param $touser               OpenID
     * @param $template_id          模板消息ID
     * @param $url                  详情链接
     * @param $data
     * @param string $topcolor
     * @return bool
     */
    public function doSend($touser, $template_id, $url, $data, $topcolor = '#7B68EE')
    {
        /*
         * data => array(
            'first' => array('value' => urlencode("您好,您已购买成功"), 'color' => "#743A3A"),
            'name' => array('value' => urlencode("商品信息:微时代电影票"), 'color' => '#EEEEEE'),
            'remark' => array('value' => urlencode('永久有效!密码为:1231313'), 'color' => '#FFFFFF'),
        )
         */
        $template = array(
            'touser' => $touser,
            'template_id' => $template_id,
            'url' => $url,
            'topcolor' => $topcolor,
            'data' => $data
        );
        $json_template = json_encode($template);
        $url = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=" . $this->accessToken;
        $dataRes = $this->request_post($url, urldecode($json_template));
        $result = json_decode($dataRes);
        if ($result->errcode === 0) {
            return array("status" => 1, "msg" => $result);
        } else {
            return array("status" => -1, "msg" => $result->errmsg);
        }
    }

    /**
     * 发送自定义的模板消息 (小程序用)
     * @param form_id              表单提交场景下，为 submit 事件带上的 formId；支付场景下，为本次支付的 prepay_id
     * @param touser               接收者（用户）的 openid
     * @param template_id          所需下发的模板消息的id
     * @param url                  详情链接
     * @param page                 点击模板卡片后的跳转页面，仅限本小程序内的页面。支持带参数,（示例index?foo=bar）。该字段不填则模板无跳转。
     * @param data                 模板内容，不填则下发空模板
     * @param color                模板内容字体的颜色，不填默认黑色
     * @param emphasis_keyword     模板需要放大的关键词，不填则默认无放大
     * @return bool
     */
    public function XcxSend($params)
    {
        /**
         *   $params['data'] = array(
         *       "keyword1" => array("value" => date("Y年m月d日", $_SERVER['REQUEST_TIME']), "color" => "#173177"),
         *       "keyword2" => array("value" => "功能测试", "color" => "#173177")
         *   );
         */
        $template = array(
            'form_id' => $params['form_id'],
            'touser' => $params['touser'],
            'template_id' => $params['template_id'],
            'data' => $params['data']
        );
        if ($params['page']) {
            $template['page'] = $params['page'];
        }
        if ($params['url']) {
            $template['url'] = $params['url'];
        }
        if ($params['color']) {
            $template['color'] = $params['color'];
        }
        if ($params['emphasis_keyword']) {
            $template['emphasis_keyword'] = $params['emphasis_keyword'];
        }
        $json_template = json_encode($template);
        $url = "https://api.weixin.qq.com/cgi-bin/message/wxopen/template/send?access_token=" . $this->accessToken;    // 与公众号接口不一致
        $dataRes = $this->request_post($url, urldecode($json_template));
        $result = json_decode($dataRes);
        if ($result->errcode === 0) {
            return array("status" => 1, "msg" => $result);
        } else {
            return array("status" => -1, "msg" => $result->errmsg, "template" => $template);
        }
    }
}