PHP实现发送模板消息(微信公众号版)

以下为开发步骤:

1.微信公众号为服务号且开通微信认证(其他类型账号不能发送)

2.ip白名单设置你的服务器ip(用于获取access_token)

3.网页授权你的域名(用于获取用户的openid)

4.开通模板消息并在模板库中选用模板

5.获取openid

6.发送模板消息

ip白名单

 
 
 
 

网页授权

 
 
 
 


开通模板消息并选用模板

 
 
 
 
 
 
 
 


获取openid

这是微信官方文档

1.用户同意授权,获取code

接口地址:https://open.weixin.qq.com/connect/oauth2/authorize?appid=APPID&redirect_uri=REDIRECT_URI&response_type=code&scope=SCOPE#wechat_redirect

appid:公众号appid基础设置里有(必填)

redirect_uri:重定向地址,用于接收code(必填)

response_type:返回类型,请填写code(必填)

scope:应用授权作用域,snsapi_base (不弹出授权页面,直接跳转,只能获取用户openid),snsapi_userinfo (弹出授权页面,可通过openid拿到昵称、性别、所在地。并且, 即使在未关注的情况下,只要用户授权,也能获取其信息 )(必填)

#wechat_redirect:无论直接打开还是做页面302重定向时候,必须带此参数(必填)

完成参数填写后直接扔进你的自定义菜单栏里,点击跳转url

2.通过code换取网页授权access_token

接口地址:https://api.weixin.qq.com/sns/oauth2/access_token?appid=APPID&secret=SECRET&code=CODE&grant_type=authorization_code

$code=$request->get("code"); //接收code,这里我用的laravel框架

$url="https://api.weixin.qq.com/sns/oauth2/access_token?appid=appid&secret=secret&code=".$code."&grant_type=authorization_code";

$res=HttpUtils::curl($url, $params = false, $ispost = 0, $https = 1);//此方法为curl发送请求,可联系我要完整代码

$res = (array)json_decode($res); // 返回结果为json,其中包含openid,access_token

appid:公众号appid基础设置里有(必填)

secret:公众号secret基础配置里生成(必填)

code:第一步获取的code(必填)

grant_type:填写为authorization_code(必填)

正确返回的结果:

{ "access_token":"ACCESS_TOKEN",

"expires_in":7200,

"refresh_token":"REFRESH_TOKEN",

"openid":"OPENID",

"scope":"SCOPE" }

其中openid扔进你的数据库,发送模板消息的时候用

发送模板消息

1.获取access_token

接口地址:https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=appid&secret=secret

appid:公众号appid(必填)

secret:公众号secret(必填)

grant_type:获取access_token填写client_credential(必填)

2.拼接模板消息

 

$data=[

            "touser"=>$openid, //对方的openid,前一步获取

            "template_id"=>"EVcUo-BP_A59s8sXjmYDZPEXtbaMpOCwVQguN4TUwHY", //模板id

            "miniprogram"=>["appid"=>"", //跳转小程序appid  

             "pagepath"=>"pages/index/index"],//跳转小程序页面   -------可略

    'url'=>'#' //模板跳转路径 可略

            "data"=>[

                "first"=>[

                    "value"=> "你的用户信息", //自定义参数

                    "color"=> '#173177'//自定义颜色

                ],

                "keyword1"=>[

                    "value"=> '', //自定义参数 --------- 申请时间

                    "color"=> '#173177'//自定义颜色

                ],

                "keyword2"=>[

                    "value"=> $time, //自定义参数  ------申请渠道

                    "color"=> '#173177'//自定义颜色

                ],

                "remark"=>[

                    "value"=> "如有疑问,请联系当地网点", //自定义参数

                    "color"=> '#173177'//自定义颜色

                ],

            ]

        ];

3.发送模板消息

$url="https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=appid&secret=secret"; //此时再次请求access_token,与获取openid的接口不同!!!

$access_token=json_decode(self::curl($url))->{"access_token"}; 

$msgurl="https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=".$access_token; // 发送模板消息接口

return json_decode(self::curl($msgurl,$params=json_encode($data),$ispost=1,$https=1));

function cash_message($openid, $cash_moeny){
    $appid = "****";
    $secret = "*****";
    $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=$appid&secret=$secret";
    $token =getJson($url);
    $token = json_decode($token, true);
    $uri ='https://api.weixin.qq.com/cgi-bin/message/template/send';
    $access_token = $token["access_token"];
    $uri = $uri.'?access_token='.$access_token;
    $user  = DB::table('users')->where(['watchid'=>$openid])->first();
    if(!$user){
        return false;
    }

    $data=  array('touser'=>$openid,   //发给谁
        'template_id'=>'s_pljD0B4u8IJ1vmC3GoTvw04M1cPgaVBaxTPS7sy-8',   //模板id
        'url'=>'#',     //这个是你发送了模板消息之后,当用户点击时跳转的连接
        'topcolor'=>"#FF0000",   //颜色
        'miniprogram' => '',
        'data'=>array(

            'first'=>array(
                'value'=>$user->nickname,
                'color'=>'#173177'
            ),
            'keyword1'=>array(
                'value'=>date('Y-m-d H:i:s',time()),
                'color'=>'#173177'
            ),
            'keyword2'=>array(
                'value'=>'微信端',
                'color'=>'#173177'
            ),
            'keyword3'=>array(
                'value'=>$cash_moeny,
                'color'=>'#173177'
            ),
            'keyword4'=>array(
                'value'=>'已到账',
                'color'=>'#173177'
            ),
            'remark'=>array(
                'value'=>'您的申请金额已到账,请注意查看',
                'color'=>'#173177'
            )
        )
    );
    $res_data = getJson($uri,$data);
    $res_data = json_decode($res_data, true);
    if ($res_data['errcode'] != 0) {
        return false;
    }
    return true;
}

function getJson($url = '', $param = [] ,$contentType = 'json'){
    $ch = curl_init();
    // 请求地址
    curl_setopt($ch, CURLOPT_URL, $url);
    // 请求参数类型
    $param = $contentType == 'json' ? urldecode(json_encode($param)) : http_build_query($param);
    // 关闭https验证
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
    // post提交
    if($param){
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $param);
    }
    // 返回的数据是否自动显示
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    // 执行并接收响应结果
    $output = curl_exec($ch);
    // 关闭curl
    curl_close($ch);
    return $output !== false ? $output : false;

}

  

1.openid获取需要网页获取

2.接口地址严格按照官方所给出的地址填写,参数顺序不能错

3.发送模板消息时获取的access_token具有2小时的时效可丢进缓存中,不必每次发送都获取,每天只有两千次,模板消息发送次数为10万次,当然根据你公众号的关注人数来确定,人数超过10万肯定具有更高的次数

原文地址:https://www.cnblogs.com/liyanxi/p/12068078.html