小程序 后台发送模板消息


<?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;
    }






}

数据库结构