php 异步请求微信模板消息_PHP实现发送模板消息(微信公众号版)

以下为开发步骤:

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

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

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

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

5.获取openid

6.发送模板消息

ip白名单

网页授权

开通模板消息并选用模板

获取openid

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

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

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

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

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

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

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

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

$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

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"],//跳转小程序页面

"data"=>[

"first"=>[

"value"=> "你的账户即将到期,请及时缴费", //自定义参数

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

],

"keyword1"=>[

"value"=> $account, //自定义参数

"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));

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值