小程序 后台發送模板消息


<?php

/**
 *
 * 處理用戶模板消息 formid
 *
 * @author
 *
 */
class UserFormidController extends Controller
{
    /**
     * 接收用戶formId,存入表User_formid
     */
    public function actionIndex()
    {
        $userInfo = $this->userInfo;

        $app = new User_formidModel ();
        $app->uid = $this->user_id;
        $app->formid = $_REQUEST['fromid'];
        $app->openid = $userInfo->openid;
        $app->add_time = time();
        if($_REQUEST['fromid']){
            if (!$app->save()){
                echo '成功';
            }
        }
    }




    public function actionSendmsg()
    {
        $re = $this->sendTemplateMsg(317359,['可口可樂宣傳主題曲制作,感興趣的聯系13012345678','記得帶傘']);
        var_dump($re);

    }




    /*
     * 小程序向發送用戶發送模板消息
     * 傳入用戶的uid、消息數組、頁面地址
     * 同時依賴get_access_token(),curl()這個兩個方法
     * 返回200為成功發送,404未找到可用的formid,其他錯誤代號為
     * 40037template_id不正確;41028form_id不正確,或者過期;41029form_id已被使用;41030page不正確;45009接口調用超過限額(目前默認每個帳號日調用限額為100萬)
     * $this->sendTemplateMsg(317359,['可口可樂宣傳主題曲制作','記得帶傘']);
    */
    public function sendTemplateMsg($uid,$temp_arr,$page='pages/index/index'){
        //根據uid在formid表中查詢該用戶
        $connection = Yii::app()->impression;
        //七天前的時間,低於這個時間的記錄已經失效
        $where_time = (int)time() - 604800;
        $sql = " SELECT * FROM `imp_user_formid` WHERE `uid`= ".$uid.' AND `add_time`>'.$where_time.' ORDER BY `add_time` ASC limit 1';
        $userRes = $connection->createCommand($sql)->queryAll();
        if(count($userRes) > 0){
            //組織消息內容
            $value = array(
                "keyword1"=>array(
                    "value"=>$temp_arr[0],
                    "color"=>"#4a4a4a"
                ),
                "keyword2"=>array(
                    "value"=>$temp_arr[1],
                    "color"=>"#4a4a4a"
                )
            );

            $send_date = array();
            $send_date['touser'] = $userRes[0]['openid'];
            $send_date['template_id']='h20O855x1vIPxJCHYgPIXWA2pyeKYtb5Bh0V5onquEs';
            $send_date['page']= $page;  //點擊模板卡片后的跳轉頁面,僅限本小程序內的頁面。支持帶參數,該字段不填則模板無跳轉。
            $send_date['form_id'] = $userRes[0]['formid'];
            $send_date['data']=$value;                        //模板內容,不填則下發空模板
            $send_date['color']='';                        //模板內容字體的顏色,不填默認黑色
            $send_date['emphasis_keyword']='';
            //發送
            $url = 'https://api.weixin.qq.com/cgi-bin/message/wxopen/template/send?access_token=' .$this->get_access_token();
            $res_str = $this->curl($url,json_encode($send_date));
            $res = json_decode($res_str, true);
            if($res['errcode'] == 0){
                //成功 刪除用過的 formid
                $sql = " DELETE FROM `imp_user_formid` WHERE `id`= ".$userRes[0]['id'];
                $connection->createCommand($sql)->execute();
                //刪除過期的 formid
                $sql2 = " DELETE FROM `imp_user_formid` WHERE `uid`= ".$uid.' AND `add_time`<'.$where_time;
                $connection->createCommand($sql2)->execute();

                return 200;
            }else{
                return $res['errcode'];
            }
        }else{
            //刪除過期的 formid
            $sql2 = " DELETE FROM `imp_user_formid` WHERE `uid`= ".$uid.' AND `add_time`<'.$where_time;
            $connection->createCommand($sql2)->execute();
            return 404;
        }

    }

    //獲取小程序的 access_token
    public function get_access_token() {
        $connection = Yii::app()->impression;
        $sql = "SELECT *  FROM `imp_weixin_account` WHERE `id`=1";
        $Row = $connection->createCommand($sql)->queryRow();
        $access_token = $Row['access_token'];
        if ($Row['access_token_time'] < time()) {
            $info = file_get_contents("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" . $Row['appid'] . "&secret=" . $Row['appsecret']);
            $info = json_decode($info);
            $access_token = $info->access_token;
            $access_token_time = time() + 7000;
            $upsql = "UPDATE `imp_weixin_account` SET `access_token` = '" . $access_token . "' ,`access_token_time` ='" . $access_token_time . "' WHERE `id`=1 ";
            $connection->createCommand($upsql)->execute();
        }
        return $access_token;
    }


    //curl post方式
    public function curl($url, $params) {
        //初始化
        $curl = curl_init();
        //設置抓取的url
        curl_setopt($curl, CURLOPT_URL, $url);
        //設置頭文件的信息作為數據流輸出
        curl_setopt($curl, CURLOPT_HEADER, false);
        //設置獲取的信息以文件流的形式返回,而不是直接輸出。
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        //設置post方式提交
        curl_setopt($curl, CURLOPT_POST, 1);

        curl_setopt($curl, CURLOPT_POSTFIELDS, $params);
        //執行命令
        $data = curl_exec($curl);
        //關閉URL請求
        curl_close($curl);
        //顯示獲得的數據
        return $data;
    }






}

數據庫結構

 


免責聲明!

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



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