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萬肯定具有更高的次數


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM