公众号模板消息 php,PHP实现发送模板消息(微信公众号版)
以下為開發(fā)步驟:
1.微信公眾號(hào)為服務(wù)號(hào)且開通微信認(rèn)證(其他類型賬號(hào)不能發(fā)送)
2.ip白名單設(shè)置你的服務(wù)器ip(用于獲取access_token)
3.網(wǎng)頁授權(quán)你的域名(用于獲取用戶的openid)
4.開通模板消息并在模板庫中選用模板
5.獲取openid
6.發(fā)送模板消息
ip白名單
網(wǎng)頁授權(quán)
開通模板消息并選用模板
獲取openid
1.用戶同意授權(quán),獲取code
appid:公眾號(hào)appid基礎(chǔ)設(shè)置里有(必填)
redirect_uri:重定向地址,用于接收code(必填)
response_type:返回類型,請(qǐng)?zhí)顚慶ode(必填)
scope:應(yīng)用授權(quán)作用域,snsapi_base (不彈出授權(quán)頁面,直接跳轉(zhuǎn),只能獲取用戶openid),snsapi_userinfo (彈出授權(quán)頁面,可通過openid拿到昵稱、性別、所在地。并且, 即使在未關(guān)注的情況下,只要用戶授權(quán),也能獲取其信息 )(必填)
#wechat_redirect:無論直接打開還是做頁面302重定向時(shí)候,必須帶此參數(shù)(必填)
完成參數(shù)填寫后直接扔進(jìn)你的自定義菜單欄里,點(diǎn)擊跳轉(zhuǎn)url
2.通過code換取網(wǎng)頁授權(quán)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發(fā)送請(qǐng)求,可聯(lián)系我要完整代碼
$res = (array)json_decode($res); // 返回結(jié)果為json,其中包含openid,access_token
appid:公眾號(hào)appid基礎(chǔ)設(shè)置里有(必填)
secret:公眾號(hào)secret基礎(chǔ)配置里生成(必填)
code:第一步獲取的code(必填)
grant_type:填寫為authorization_code(必填)
正確返回的結(jié)果:
{ "access_token":"ACCESS_TOKEN",
"expires_in":7200,
"refresh_token":"REFRESH_TOKEN",
"openid":"OPENID",
"scope":"SCOPE" }
其中openid扔進(jìn)你的數(shù)據(jù)庫,發(fā)送模板消息的時(shí)候用
發(fā)送模板消息
1.獲取access_token
appid:公眾號(hào)appid(必填)
secret:公眾號(hào)secret(必填)
grant_type:獲取access_token填寫client_credential(必填)
2.拼接模板消息
$data=[
"touser"=>$openid, //對(duì)方的openid,前一步獲取
"template_id"=>"EVcUo-BP_A59s8sXjmYDZPEXtbaMpOCwVQguN4TUwHY", //模板id
"miniprogram"=>["appid"=>"", //跳轉(zhuǎn)小程序appid
"pagepath"=>"pages/index/index"],//跳轉(zhuǎn)小程序頁面
"data"=>[
"first"=>[
"value"=> "你的賬戶即將到期,請(qǐng)及時(shí)繳費(fèi)", //自定義參數(shù)
"color"=> ‘#173177‘//自定義顏色
],
"keyword1"=>[
"value"=> $account, //自定義參數(shù)
"color"=> ‘#173177‘//自定義顏色
],
"keyword2"=>[
"value"=> $time, //自定義參數(shù)
"color"=> ‘#173177‘//自定義顏色
],
"remark"=>[
"value"=> "如有疑問,請(qǐng)聯(lián)系當(dāng)?shù)鼐W(wǎng)點(diǎn)", //自定義參數(shù)
"color"=> ‘#173177‘//自定義顏色
],
]
];
3.發(fā)送模板消息
$url="https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=appid&secret=secret"; //此時(shí)再次請(qǐng)求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; // 發(fā)送模板消息接口
return json_decode(self::curl($msgurl,$params=json_encode($data),$ispost=1,$https=1));
總結(jié)
以上是生活随笔為你收集整理的公众号模板消息 php,PHP实现发送模板消息(微信公众号版)的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Python WordCloud 文本分
- 下一篇: php域名转向,php强制用户转向www