<?php

namespace App\Services;


use App\Components\AsyncResponse;

class ProcurementWeiXinSendMessageService
{
    use AsyncResponse;
    //获取access_token
    public  function get_access_token($appId = '', $appSecret = ''){
        $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=$appId&secret=$appSecret";
        $result = file_get_contents($url);
        $result = json_decode($result,true);
        if (array_key_exists("access_token", $result)) return $result['access_token'];
        return null;
    }
    //发送微信模版消息通知
    public function sendWenChantTemplate($param)
    {
        try {
            $params['touser'] = $param['touser'];
            $params['mp_template_msg'] = $param['mp_template_msg'];
            $res = $this -> send_message($params);
        } catch (\Exception $e) {
            LogService::log(__METHOD__,"发送模板消息失败",$params." | ".$e->getMessage());
        }
        LogService::log(__METHOD__,"发送模板消息成功",$params);
    }

    /**
     * @desc 发送微信消息
     * param     string
     * $type
     * $param['title'] 消息标题
     * $param['reason'] 消息内容或者消息原因
     */
    public function send_message($param)
    {

        $appId=config('weiXin.xiaoChengXu.appId');
        $appSecret=config('weiXin.xiaoChengXu.appSecret');
        $data = [
            "touser" => $param['touser'],
            "mp_template_msg" => $param['mp_template_msg'],
        ];
        $json = json_encode($data, JSON_UNESCAPED_UNICODE);
        $access_token = self::get_access_token($appId, $appSecret);
        $url = "https://api.weixin.qq.com/cgi-bin/message/wxopen/template/uniform_send?access_token=" . $access_token;

        //以'json'格式发送post的https请求
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_POST, 1); // 发送一个常规的Post请求
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);
        if (!empty($json)) {
            curl_setopt($curl, CURLOPT_POSTFIELDS, $json);
        }
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        $output = curl_exec($curl);
        curl_close($curl);
        return $output;
    }

}
