laravel框架发送微信模版消息

1、发送微信模版消息类
<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Log;
use App\Tools\MessageSender;
use App\Tools\MaYiResponse;
use App\UserLogin;
use Validator;
use App\Tools\SmsSender;


class MessageController extends Controller
{

    /**
     * @Author    sunxiaoli
     * @DateTime  2020-11-27
     * @desc      验证消息的确来自微信服务器
     * @return    [type]
     */
    public function checkSignature(Request $request)
    {
        Log::info('c端微信消息推送'.json_encode($request->all(), true));
        $signature = $_GET["signature"];
        $timestamp = $_GET["timestamp"];
        $echostr = $_GET["echostr"];
        $nonce = $_GET['nonce'];
        return $echostr;

        //{"signature":"7ff7a72a28306c4fe8683b377570bd2d0bf2c92d","echostr":"4674346088726517567","timestamp":"1606469146","nonce":"180665012"}
        $token = config('weixin.user.token');
        $tmpArr = array($token, $timestamp, $nonce);
        sort($tmpArr, SORT_STRING);
        $tmpStr = implode( $tmpArr );
        $tmpStr = sha1( $tmpStr );

        if ($tmpStr == $signature ) {
            return true;
        } else {
            return false;
        }
    }

    /**
     * @Author    sunxiaoli
     * @DateTime  2020-11-27
     * @param     string
     */
    public function user(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'u_code' => 'required',
        ]);
        $u_code = $request->input('u_code');
        $user = UserLogin::where(['u_code' => $u_code, 'step' => 6])->first();
        $data = [
            'touser' => $user['openid_wxc'],
            'first' => "您好,您的帐号".$user['name']."刚刚登录",
            'time' => date('Y-m-d H:i:s'),
            'ip' => $_SERVER['SERVER_ADDR'],
            'reason' => '备注:如果本次登录不是您本人所为,说明您的帐号已经被盗!为减少您的损失,请点击本条消息,立即锁定帐号。',
        ];
        try {
            new MessageSender($data, 1, 4);
        } catch (\Exception $e) {
            Log::error($e->getMessage());
            return MaYiResponse::response('发送失败!', 500);
        }
        return MaYiResponse::response('发送成功');
    }


    /**
     * @Author    sunxiaoli
     * @DateTime  2020-11-27
     * @param     string
     */
    public function business(Request $request)
    {
        return "success";
    }

    /**
     * 发送微信模版消息通知
     */
    public function sendWenChantTemplate($param){
        try {
            $params['touser'] = $param['touser'];
            $params['template_id'] = $param['template_id'];
            $params['title'] = $param['title'];
            $params['data'] = $param['data'];
            $params['url'] = $param['url'];
            //$type 1用户 2商户
            $res = $this -> send_message(1,$params);

        } catch (\Exception $e) {
            Log::error($e->getMessage());
            return MaYiResponse::response('发送短信验证码失败!', 500);
        }
        return MaYiResponse::response('验证码已发出,请注意查收,有效期2分钟!');
    }

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

            $appId = config('weixin.user.app_id');
            $appSecret = config('weixin.user.app_secret');
            $data = [
                "touser" => $param['touser'],
                "template_id" => $param['template_id'],
                "url" => $param['url'],
                "data" => $param['data']
            ];
            $json = json_encode($data, JSON_UNESCAPED_UNICODE);  //兼容php5.4以下json格式处理
            $access_token = self::get_access_token($appId, $appSecret);
            /*
            * POST发送https请求 客服接口api
            */
            $url = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=" . $access_token;
            //"https://api.weixin.qq.com/cgi-bin/message/custom/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);
            //curl_setopt($curl, CURLOPT_HTTPHEADER, $headers );
            $output = curl_exec($curl);
            curl_close($curl);

            return $output;
    }

    //获取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);
            Log::info('获取access_token'.$result);
            $result = json_decode($result,true);
            if (array_key_exists("access_token", $result)){
                $accesstoken = $result['access_token'];
                return $accesstoken;
            }
    }

}

2、调用发送方法

// 2.微信消息模版
$MessageController = new MessageController();
$param['touser'] = $UserLogin['openid_wxc'];
$param['param'] = $template;
$param['url'] = 'https://www.jiujiujuhe.com/m/order/orderlist';
$param['template_id'] = 'IjujrqX28rJw68MuV6rzRtZXXCqcVyfp-R2BD80A5NA';
$smssender = new SmsSender();
$tem = $smssender->templateBorrow($param['param']);
$param['data'] = [
    'first' => [
        "value"=>"订单审核通知",
        "color"=>"#173177"
    ],
    'keyword1' => [
        "value"=>'订单审核',
        "color"=>"#173177"
    ],
    'keyword2' => [
        "value"=>date('Y-m-d'),
        "color"=>"#173177"
    ],
    'keyword3' => [
        "value"=>$template['result'],
        "color"=>"#173177"
    ],
    'keyword4' => [
        "value"=>$tem,
        "color"=>"#173177"
    ],
    'remark' => [
        "value"=>'请及时查看',
        "color"=>"#173177"
    ],
];

$res = $MessageController->sendWenChantTemplate($param);

猜你喜欢

转载自blog.csdn.net/hechenhongbo/article/details/111310812