php小程序模板消息

 	/**
     *小程序  發送模板消息
     */
public function  send_template_news() 
    {
    	$form_id          =  '';    //form_id  有兩種     一種爲提交過表單後生成的form_id  一種爲支付後生成的prepay_id
	    $template_id      =  '';    //小程序後臺設置的模板id
        $openid           =  ''  ;  //用戶的openid 
        $access_token = $this->get_access_token();   //access_token
        $url = "https://api.weixin.qq.com/cgi-bin/message/wxopen/template/send?access_token=$access_token";
        $data = [
            //此處數據對應與小程序後臺設置的模板結構
            "keyword1" => ["value" => $order_no],//訂單號
            "keyword3" => ["value" => $payment_money],//支付金額
            "keyword4" => ["value" => date('Y-m-d H:i:s',$create_time)],//支付時間
        ];
        $post = [
            "touser"       => $openid,
            "template_id" => $template_id,
            "page"         => "pages/index/index",   //點擊
            "form_id"      => $prepay_id,
            "data"         => $data,
        ];
        $this->http($url, json_encode($post));   
}        

獲取access_token

public function get_access_token()
    {
        if (cache('access_token')){   //此處爲tp5cache緩存
            $access_token = cache('access_token');
        }else{
            $WX_APPID   =  '';   //小程序appid
            $WX_SECRET  =  ''; //小程序appsecret
            $url        =  'https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid='.$WX_APPID.'&secret='.$WX_SECRET;
            $infos      =  json_decode(file_get_contents($url));
            $access_token = $infos->access_token;
            cache('access_token',$access_token,7000);
        }
        return $access_token;
     }

發送http請求

/** Get 或 Post 請求
     * @param $url
     * @param null $data 爲null時,爲post方法
     * @return mixed
     */
    public function http($url, $data = null)
    {
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
        if (!empty($data)) {
            curl_setopt($curl, CURLOPT_POST, 1);
            curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
        }
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        $output = curl_exec($curl);
        curl_close($curl);

        return $output;
    }
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章