<?php
/**
 * 微信绑定账户
 * 精誉美车公众号
 */

namespace app\modules\third\wx;

use yii;

class WxBind
{
    public $app_id = 'wxdd3d2c71ad906f27';
    public $app_secret = 'd3652b3704c3ec9d18d54b540b1a69c5';

    public function __construct()
    {
        if (!empty(Yii::$app->params['wx_bind'])) {
            $this->app_id = Yii::$app->params['wx_bind']['app_id'];
            $this->app_secret = Yii::$app->params['wx_bind']['app_secret'];
        }
    }

    /**
     * 获取用户的access_token
     * @param $code
     * @param $state
     * @return bool|mixed
     */
    public function getAccessToken($code,$state)
    {
        $url = "https://api.weixin.qq.com/sns/oauth2/access_token";
        $data = [
            'grant_type' => 'authorization_code',
            'appid' => $this->app_id,
            'secret' => $this->app_secret,
            'code' => $code,
            'state' => $state, //防止crf码
        ];
        /** 正确返回
         * {
         * "access_token":"ACCESS_TOKEN",   接口调用凭证
         * "expires_in":7200,               接口调用凭证超时时间，单位（秒）
         * "refresh_token":"REFRESH_TOKEN", 用户刷新access_token
         * "openid":"OPENID",               授权用户唯一标识
         * "scope":"SCOPE",                 用户授权的作用域，使用逗号（,）分隔
         * "unionid":"o6_bmasdasdsad6_2sgVt7hMZOPfL" 只有在用户将公众号绑定到微信开放平台帐号后，才会出现该字段
         * }
         */
        $wx_result = json_decode($this->curlGet($url, $data), true);
        if (isset($wx_result['access_token'])) {
            return $wx_result;
        } else {
            Yii::warning(json_encode($wx_result, JSON_UNESCAPED_UNICODE));
            return false;
        }
    }

    //获取用户信息
    public function getUserInfo($access_token, $openid)
    {
        $url = "https://api.weixin.qq.com/sns/userinfo";
        $data = [
            'access_token' => $access_token,
            'openid' => $openid,
            'lang' => 'zh_CN',
        ];
        /**
         * {
         * "openid":" OPENID",
         * "nickname": NICKNAME,
         * "sex":"1",
         * "province":"PROVINCE"
         * "city":"CITY",
         * "country":"COUNTRY",
         * "headimgurl": "http://wx.qlogo.cn/mmopen/g3MonUZtNHkdmzicIlibx6iaFqAc56vxLSUfpb6n5WKSYVY0ChQKkiaJSgQ1dZuTOgvLLrhJbERQQ4eMsv84eavHiaiceqxibJxCfHe/46",
         * "privilege":[
         * "PRIVILEGE1"
         * "PRIVILEGE2"
         * ],
         * "unionid": "o6_bmasdasdsad6_2sgVt7hMZOPfL"
         * }
         */
        $wx_result = json_decode(self::curlGet($url, $data), true);
        if (isset($wx_result['errcode'])) {
            Yii::warning(json_encode($wx_result, JSON_UNESCAPED_UNICODE));
            return false;
        } else {
            return $wx_result;
        }
    }

    //校验AccessToken 有效性
    public function checkAccessToken($access_token, $openid)
    {
        $url = "https://api.weixin.qq.com/sns/auth";
        $data = [
            'access_token' => $access_token,
            'openid' => $openid,
        ];

        $wx_result = json_decode($this->curlGet($url, $data), true);
        if ($wx_result['errcode'] == 0) {
            return true;
        } else {
            return false;
        }
    }

    //刷新AccessToken
    public function refreshAccessToken($refresh_token)
    {

        $url = "https://api.weixin.qq.com/sns/oauth2/refresh_token";
        $data = [
            'grant_type' => 'refresh_token',
            'appid' => $this->app_id,
            'refresh_token' => $refresh_token,
        ];
        $wx_result = json_decode($this->curlGet($url, $data), true);
        if (isset($wx_result['errcode'])) {
            return false;
        } else {
            return $wx_result;
        }
    }

    //发送模板消息
    public function sendTemplateMessage($data)
    {
        $ACCESS_TOKEN = AccessToken::getAccessToken();
        $url = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=$ACCESS_TOKEN";
        //https://open.weixin.qq.com/connect/oauth2/authorize?appid=wx0ce69aba0709b60c&redirect_uri=http%3A%2F%2Fbamboo.ftmore.com&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect
        $data = [
            'touser' => $data['openid'],
            'template_id' => $data['template_id'],
            'url' => "https://open.weixin.qq.com/connect/oauth2/authorize?appid=wx0ce69aba0709b60c&redirect_uri=" . urlencode($data['url']) . "&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect",
            'data' => [
                'first' => [
                    'value' => "尊敬的用户：\n您的" . $data['search_type'] . "支付成功。\n",
                ],
                "keyword1" => [
                    "value" => date("Y年m月d日 H时i分", $data['time']),//2018年1月9日17时34分
                ],
                "keyword2" => [
                    "value" => $data['search_type'],//xxxx查询
                ],
                "keyword3" => [
                    "value" => "人民币" . $data['price'] . "元\n",
                ],
                "remark" => [
                    "value" => $data['remark'],
                    'color' => '#ff0000',
                ],
            ],
        ];
        $result = $this->curlPost($url, $data);
        return $result;
    }

    //退款通知
    public function sendRefundTemplateMessage($data)
    {
        //https://open.weixin.qq.com/connect/oauth2/authorize?appid=wx0ce69aba0709b60c&redirect_uri=http%3A%2F%2Fbamboo.ftmore.com&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect

        $ACCESS_TOKEN = AccessToken::getAccessToken();

        $url = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=$ACCESS_TOKEN";

        $data = [
            'touser' => $data['openid'],
            'template_id' => $data['template_id'],
            'url' => $data['url'],
            'data' => [
                'first' => [
                    'value' => "尊敬的用户：\n您的" . $data['search_type'] . "失败，已按支付方式原路退款，请注意查收。\n",
                ],
                "keyword1" => [
                    "value" => date("Y年m月d日 H时i分", $data['time']),//2018年1月9日17时34分
                ],
                "keyword2" => [
                    "value" => $data['search_type'],
                ],
                "remark" => [
                    "value" => "金额：人民币" . $data['price'] . "元\n",
                ],
            ],
        ];
        $this->curlPost($url, $data);
    }

    /**
     * 给用户发送信息
     * @param $data
     * @return mixed
     */
    public function sendCustomerMsg($data)
    {
        $ACCESS_TOKEN = AccessToken::getAccessToken();
        $url = "https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token=$ACCESS_TOKEN";

        $customer_msg = [
            'touser' => $data['openid'],
            'msgtype' => 'text',
            'text' => [
                'content' => $data['content'],
            ],
        ];
        return json_decode($this->curlPost($url, $customer_msg), true);
    }

    public function curlGet($url, $postFields)
    {
        $postFields = http_build_query($postFields);
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_POST, 0);
        curl_setopt($ch, CURLOPT_HEADER, 0);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $postFields);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
        $result = curl_exec($ch);
        $error = curl_error($ch);
        curl_close($ch);
        if ($error) {
            Yii::warning('微信绑定get' . $error);
        }
        return $result;
    }


    public function curlPost($url, $postFields)
    {
        $postFields = json_encode($postFields, JSON_UNESCAPED_UNICODE);
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_HEADER, 0);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $postFields);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
        $result = curl_exec($ch);
        $error = curl_error($ch);
        curl_close($ch);
        if ($error) {
            Yii::warning('微信绑定post' . $error);
        }
        return $result;
    }
}
