微信公众号开发代码参考

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了微信公众号开发代码参考相关的知识,希望对你有一定的参考价值。

<?php

namespace backend\modules\api\controllers;

use common\models\SmsReport;
use common\models\Aes;
use common\models\Counter;
use common\models\Phone;
use common\models\City;
use common\models\oss\oss;
use common\models\PersonLooking;
use Yii;
use yii\rest\Controller;
use backend\modules\api\common\lib\Helper;
use backend\modules\api\models\User;
use backend\modules\api\models\FreeDelivery;
use backend\modules\api\models\Register;
use backend\modules\api\common\lib\HttpUploadFile;
use yii\base\Object;
use backend\modules\api\models\Login;
use backend\modules\api\models\Equipment;
use backend\modules\api\models\Active;
use backend\modules\api\models\Order;
use backend\modules\api\models\AdminDelivery;
use backend\modules\api\models\ShopActive;
use backend\modules\api\models\Abnormal;
use backend\modules\api\models\WxUser;

header(‘Access-Control-Allow-origin:*‘);
header(‘Access-Control-Allow-Credentials:true‘);
header(‘Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS‘);
header(‘Access-Control-Allow-Headers:Origin, No-Cache, X-Requested-With, If-Modified-Since, Pragma, Last-Modified, Cache-Control, Expires, Content-Type, X-E4M-With‘);
header(‘Content-Type: text/html; charset=utf-8‘);

class WechatController extends Controller {
    public function actionIndex(){
        $nonce = Yii::$app->request->get(‘nonce‘);
        $token = ‘adshare‘;
        $timestamp = Yii::$app->request->get(‘timestamp‘);
        $echostr = Yii::$app->request->get(‘echostr‘);
        $signature = Yii::$app->request->get(‘signature‘);
        $array = array();
        $array = array($nonce,$timestamp,$token);
        sort($array);
        $str = sha1(implode($array));
        if($str == $signature && $echostr){
            return $echostr;
        }else{
            self::actionMessage();
        }
    }

    public function actionGetUserInfo($token,$openid){
        $url = ‘https://api.weixin.qq.com/cgi-bin/user/info?access_token=‘.$token.‘&openid=‘.$openid.‘&lang=zh_CN‘;

        $res= self::actionCurlRequest($url);
        return json_decode($res,true);
    }


    public function actionMessage(){
        $postArr = $GLOBALS[‘HTTP_RAW_POST_DATA‘];
        $postObj = simplexml_load_string($postArr);
        if(strtolower($postObj->MsgType) == ‘event‘){
            if(strtolower($postObj->Event) == ‘subscribe‘){

                $UserInfo = WxUser::find()->where([‘openid‘=>$postObj->FromUserName])->one();
                if(!empty($UserInfo)){
                    $UserInfo->is_subscribe = 1;
                    $model->save(false);
                }else{
                    //获取用户信息
                    $token = self::actionGetToken();
                    $res = self::actionGetUserInfo($token,$postObj->FromUserName);
                    $model = new WxUser();
                    $model->openid = $res[‘openid‘];
                    $model->unionid = $res[‘unionid‘];
                    $model->sex = $res[‘sex‘];
                    $model->imgs = $res[‘headimgurl‘];
                    $model->username = $res[‘nickname‘];
                    $model->create_time = time();
                    $model->login_time = time();
                    $model->login_ip = $_SERVER["REMOTE_ADDR"];
                    $model->create_ip = $_SERVER["REMOTE_ADDR"];
                    //$model->lng = $Longitude;
                    //$model->lat = $Latitude;
                    $model->save(false);
                }

                $toUser = $postObj->FromUserName;//用户的openid
                $fromUser = $postObj->ToUserName;
                $time = time();
                $Msgtype = ‘news‘;
                $arr = array(
                    array(
                        ‘Title‘=>‘欢迎关注AD共享‘,
                        ‘Description‘=>‘这是一个属于互联网传媒的时代‘,
                        ‘PicUrl‘=>‘http://fx.peita.net/adShared/img/icon/banner.png‘,
                        ‘Url‘=>‘http://fx.peita.net/adShared/pages/home.html‘
                    )
                );

                $template = "<xml>
                            <ToUserName><![CDATA[%s]]></ToUserName>
                            <FromUserName><![CDATA[%s]]></FromUserName>
                            <CreateTime>%s</CreateTime>
                            <MsgType><![CDATA[%s]]></MsgType>
                            <ArticleCount>".count($arr)."</ArticleCount>
                            <Articles>";
                
                foreach($arr as $key=>$v){
                    $template .="<item>
                            <Title><![CDATA[".$v[‘Title‘]."]]></Title>
                            <Description><![CDATA[".$v[‘Description‘]."]]></Description>
                            <PicUrl><![CDATA[".$v[‘PicUrl‘]."]]></PicUrl>
                            <Url><![CDATA[".$v[‘Url‘]."]]></Url>
                            </item>";
                }
                
                $template .="</Articles>
                            </xml>";
                $info = sprintf($template,$toUser,$fromUser,$time,$Msgtype);
                echo $info;

                
                /*$toUser = $postObj->FromUserName;
                $fromUser = $postObj->ToUserName;
                $time = time();
                $Msgtype = ‘text‘;
                //$Content = $postObj->FromUserName;
                $Content = ‘欢迎关注AD共享公众号‘;
                $template = "<xml>
                            <ToUserName><![CDATA[%s]]></ToUserName>
                            <FromUserName><![CDATA[%s]]></FromUserName>
                            <CreateTime>%s</CreateTime>
                            <MsgType><![CDATA[%s]]></MsgType>
                            <Content><![CDATA[%s]]></Content>
                            </xml>";
                $info = sprintf($template,$toUser,$fromUser,$time,$Msgtype,$Content);
                echo $info;*/
            }

            if($postObj->Event == ‘LOCATION‘){
                $model = WxUser::find()->where([‘openid‘=>$postObj->FromUserName])->one();
                $model->lng = $postObj->Longitude;
                $model->lat = $postObj->Latitude;
                $model->save(false);

                /*$toUser = $postObj->FromUserName;
                $fromUser = $postObj->ToUserName;
                $time = time();
                $Msgtype = ‘text‘;
                //$Content = $postObj->FromUserName;
                $Content = ‘已经上报您的地理位置信息‘;
                $template = "<xml>
                            <ToUserName><![CDATA[%s]]></ToUserName>
                            <FromUserName><![CDATA[%s]]></FromUserName>
                            <CreateTime>%s</CreateTime>
                            <MsgType><![CDATA[%s]]></MsgType>
                            <Content><![CDATA[%s]]></Content>
                            </xml>";
                $info = sprintf($template,$toUser,$fromUser,$time,$Msgtype,$Content);
                echo $info;*/
            }


            if(strtolower($postObj->Event) == ‘unsubscribe‘){
                $model = WxUser::find()->where([‘openid‘=>$postObj->FromUserName])->one();
                if(!empty($model)){
                    $model->is_subscribe = 2;
                    $model->save(false);
                }
                
            }

            if($postObj->Event == ‘CLICK‘ && $postObj->EventKey == ‘balance‘){
                $data = WxUser::find()->select(‘openid,username,all_money‘)->where([‘openid‘=>$postObj->FromUserName])->one();

                if(empty($data)){
                    $toUser = $postObj->FromUserName;
                    $fromUser = $postObj->ToUserName;
                    $time = time();
                    $Msgtype = ‘text‘;
                    //$Content = $postObj->FromUserName;
                    $Content = ‘未获取到您的个人信息,您可以试着重新关注一下‘;
                    $template = "<xml>
                                <ToUserName><![CDATA[%s]]></ToUserName>
                                <FromUserName><![CDATA[%s]]></FromUserName>
                                <CreateTime>%s</CreateTime>
                                <MsgType><![CDATA[%s]]></MsgType>
                                <Content><![CDATA[%s]]></Content>
                                </xml>";
                    $info = sprintf($template,$toUser,$fromUser,$time,$Msgtype,$Content);
                    echo $info;
                    die;
                }


                if(!empty(Yii::$app->session[‘wx_token‘])){
                    $token = Yii::$app->session[‘wx_token‘];
                }else{
                    unset(Yii::$app->session[‘wx_token‘]);
                    $token = self::actionGetToken();
                }

                $toUser = $data->openid;
                $url = ‘https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=‘.$token;
                $sj = date(‘Y-m-d H:i:s‘,time());
                $money = $data->all_money.‘元‘;
                $message = [
                    ‘touser‘=>$toUser,
                    ‘template_id‘=>‘egyvsRQoBVnOwiyNLk94yhNkhNSDCWKA68GwDf_1QZg‘,
                    ‘data‘=>[
                        ‘first‘=>[‘value‘=>‘您好,账户余额信息如下:‘,‘color‘=>‘#FF0000‘],
                        ‘keyword1‘=>[‘value‘=>$data->username,‘color‘=>‘#173177‘],
                        ‘keyword2‘=>[‘value‘=>$money,‘color‘=>‘#173177‘],
                        ‘keyword3‘=>[‘value‘=>$sj,‘color‘=>‘#173177‘],
                        ‘remark‘=>[‘value‘=>‘如有任何疑问请登录会员系统联系在线客服‘,‘color‘=>‘#173177‘]
                    ]
                ];

                $data2 = json_encode($message);
                $res = self::actionCurlRequest($url,$data2);
                return $res;

            }


            if($postObj->Event == ‘VIEW‘ && $postObj->EventKey == ‘http://fx.peita.net/adShared/pages/home.html‘){
                $model = WxUser::find()->where([‘openid‘=>$postObj->FromUserName])->one();
                if(!empty($model)){
                    $model->login_ip = $_SERVER["REMOTE_ADDR"];
                    $model->save(false);
                }
                
            }


        }

    }

    //发送模版消息
    public function actionPushMessage($openid,$all_money,$username){

        //$wxinfo = WxUser::find()->select(‘openid,username,all_money‘)->where([‘<‘, ‘all_money‘, 10])->asArray()->all();


        if(!empty(Yii::$app->session[‘wx_token‘])){
            $token = Yii::$app->session[‘wx_token‘];
        }else{
            unset(Yii::$app->session[‘wx_token‘]);
            $token = self::actionGetToken();
        }

        $url = ‘https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=‘.$token;
        $time = date(‘Y-m-d H:i:s‘,time());
        $cz_url = ‘http://www.peita.net‘;
        $message = [
            ‘touser‘=>$openid,
            ‘template_id‘=>‘SudqvwsNYy4AFqBO4_KaWklYlhrc69c74jiAF3VBoCU‘,
            ‘url‘=>$cz_url,
            ‘data‘=>[
                ‘first‘=>[‘value‘=>‘您好,您的账户余额不足。请尽快充值,以免影响您的使用。‘,‘color‘=>‘#FF0000‘],
                ‘keyword1‘=>[‘value‘=>$username,‘color‘=>‘#173177‘],
                ‘keyword2‘=>[‘value‘=>$all_money.‘元‘,‘color‘=>‘#173177‘],
                ‘keyword3‘=>[‘value‘=>$cz_url,‘color‘=>‘#173177‘],
                ‘keyword4‘=>[‘value‘=>$time,‘color‘=>‘#173177‘],
                ‘remark‘=>[‘value‘=>‘如有任何疑问请登录会员系统联系在线客服‘,‘color‘=>‘#173177‘]
            ]
        ];

        $data = json_encode($message);
        $res = self::actionCurlRequest($url,$data);

    }


    //充值成功模板
    public function actionRechargePushMessage(){

        if(!empty(Yii::$app->session[‘wx_token‘])){
            $token = Yii::$app->session[‘wx_token‘];
        }else{
            unset(Yii::$app->session[‘wx_token‘]);
            $token = self::actionGetToken();
        }

        $url = ‘https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=‘.$token;
        $time = date(‘Y-m-d H:i:s‘,time());
        $message = [
            ‘touser‘=>‘oH9aS1fyOd-GNXKM59Gx1y3RJNd4‘,
            ‘template_id‘=>‘f1ZvxWXPmwE-FdRmdEwG7H_S3bfa98rhVw5ERQHPSMc‘,
            ‘data‘=>[
                ‘first‘=>[‘value‘=>‘您好,你已成功进行账户充值。‘,‘color‘=>‘#FF0000‘],
                ‘accountType‘=>[‘value‘=>‘充值账户‘,‘color‘=>‘#173177‘],
                ‘account‘=>[‘value‘=>‘张伟‘,‘color‘=>‘#173177‘],
                ‘amount‘=>[‘value‘=>‘100元‘,‘color‘=>‘#173177‘],
                ‘result‘=>[‘value‘=>‘充值成功‘,‘color‘=>‘#173177‘],
                ‘remark‘=>[‘value‘=>‘如有任何疑问请登录会员系统联系在线客服‘,‘color‘=>‘#173177‘]
            ]
        ];

        $data = json_encode($message);
        $res = self::actionCurlRequest($url,$data);

        return json_decode($res,true);

    }


    public function actionGetToken(){
        $url = ‘https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=wx69c7f72146629b05&secret=7367d829b543a55dc99ddf01c9ca0023‘;
        $res = json_decode(self::actionCurlRequest($url));
        Yii::$app->session[‘wx_token‘] = $res->access_token;
        return $res->access_token;
    }

    public function actionSetMenu(){
        if(!empty(Yii::$app->session[‘wx_token‘])){
            $token = Yii::$app->session[‘wx_token‘];
        }else{
            unset(Yii::$app->session[‘wx_token‘]);
            $token = self::actionGetToken();
        }
        $url = ‘https://api.weixin.qq.com/cgi-bin/menu/create?access_token=‘.$token;
        $data = array(
            ‘button‘=>array(
                array(
                    ‘type‘=>‘view‘,
                    ‘name‘=>‘广告投放‘,
                    ‘url‘=>‘https://open.weixin.qq.com/connect/oauth2/authorize?appid=wx69c7f72146629b05&redirect_uri=http://fx.peita.net/adShared/index.html&response_type=code&scope=snsapi_base&state=123&connect_redirect=1#wechat_redirect‘
                ),
                array(
                    ‘name‘=>‘我的‘,
                    ‘sub_button‘=>array(
                        array(
                            ‘type‘=>‘view‘,
                            ‘name‘=>‘充值‘,
                            ‘url‘=>‘http://www.peita.net‘
                        ),
                        array(
                            ‘type‘=>‘click‘,
                            ‘name‘=>‘查看余额‘,
                            ‘key‘=>‘balance‘
                        )
                    )
                ),
            ),
        );
        
        //创建菜单
        $res= self::actionCurlRequest($url,json_encode($data,JSON_UNESCAPED_UNICODE));
        return $res;
    }


    public function actionDelMenu(){
        if(!empty(Yii::$app->session[‘wx_token‘])){
            $token = Yii::$app->session[‘wx_token‘];
        }else{
            unset(Yii::$app->session[‘wx_token‘]);
            $token = self::actionGetToken();
        }
        $url = ‘https://api.weixin.qq.com/cgi-bin/menu/delete?access_token=‘.$token;
        $res= self::actionCurlRequest($url);
        return $res;
        
    }

    public function actionCurlRequest($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;
    }

    public function actionCodeGetUserInfo(){
        $code = Yii::$app->request->get(‘code‘);
        $url = ‘https://api.weixin.qq.com/sns/oauth2/access_token?appid=wx69c7f72146629b05&secret=7367d829b543a55dc99ddf01c9ca0023&code=‘.$code.‘&grant_type=authorization_code‘;
        $res = json_decode(self::actionCurlRequest($url));
        $openid = $res->openid;
        $data = WxUser::find()->where([‘openid‘=>$openid])->one();
        if(empty($data)) return Helper::format_data(SUCC,null);
        return Helper::format_data(SUCC,$data);

    }


    /*
     * ipad 返回
     * @param browser总浏览量,type 根据1,2,3判断返回的广告来源,1付费用户,2商家用户,3后台用户,equipment_imei设备imei,active_id 该设备投放的广告主键id,shop_id 设备所属商家id
     */
     public function actionReturnPlay(){
        $request = Yii::$app->request->post();
        $money = $request[‘browser‘]*0.01;
        if($request[‘type‘] == 1){
            $model = new WxUser();
            $user = new User();
            $models = new Active();
            $order = new Order();
            $Person = new PersonLooking();
            $time = date(‘Ymd‘,time());
            $equipment = equipment::find()->select(‘equipment_id,equipment_imei‘)->where([‘equipment_imei‘=>$request[‘equipment_imei‘]])->andwhere([‘fault_status‘=>0])->one();
            if(empty($equipment)) {
                return Helper::format_data(IMEI,null);
            }
            $PersonLooking = $Person->find()->where([‘equipment_id‘=>$equipment->equipment_id])->andWhere([‘create_time‘=>$time])->one();
            if(empty($PersonLooking)){
                $Person->equipment_id = $equipment->equipment_id;
                $Person->hour_looking = $request[‘browser‘];
                $Person->create_time = $time;
                $Person->save(false);
            }else{
                $PersonLooking->hour_looking += $request[‘browser‘];
                $PersonLooking->save(false);
            }
            if($request[‘status‘] == 1){
                $active = $models->find()->where([‘a_id‘=>$request[‘active_id‘]])->where([‘shop_type‘=>1])->one();
            }elseif($request[‘status‘] == 2){
                $active = $models->find()->where([‘a_id‘=>$request[‘active_id‘]])->where([‘shop_type‘=>2])->one();
            }
            $wx_id = $active->user_id;
            $active->browser += $request[‘browser‘];
            $str = $user->find()->where([‘id‘=>$request[‘shop_id‘]])->one();
            if(empty($str)){
                return Helper::format_data(INVALID_ACCESS_TOKEN,null);
            }
            $money_all = $money*0.3;
            $str->current_money += $money_all;
            $str->money_count += $money_all;
            if($active->save(false) == false){
                return Helper::format_data(ERROR_ACTIVE,$active->getErrors());
            }
            $arr = $order->find()->where([‘order_id‘=>$request[‘order_id‘]])->one();
            if(empty($arr)){
                    return Helper::format_data(INVALID_ACCESS_TOKEN,null);
            }
            $arr->price += $money;
            if($arr->save(false) == false){
                return Helper::format_data(ERROR_ORDER,$arr>getErrors());
            }
            if($request[‘status‘] == 1){  //微信推送
                $data = $model->find()->where([‘id‘=>$wx_id])->one();
                if(empty($data)){
                    return Helper::format_data(INVALID_ACCESS_TOKEN,null);
                }
                if($data->amount < $money){
                    $result = FreeDelivery::deleteAll([‘shop_id‘=>$request[‘shop_id‘]]);
                    $data->amount -= $money;
                    if($data->save(false)){
                        $data->all_money += $data->amount;
                        $data->amount = 0;
                        if($data->save(false)){
                                if($str->save(false)){
                                    $res = self::actionPushMessage($data->openid,$data->all_money,$data->username);
                                    return Helper::format_data(SUCC,[‘shop_id‘=>$request[‘shop_id‘],‘type‘=>1,‘res‘=>json_decode($res)]);
                                }
                            }
                        }
                }
                $data->amount -= $money;
                $data->save(false);
                if($data->save(false) == false)        return Helper::format_data(ERROR_WXUSER,$data->getErrors());
                if($str->save(false)){
                    return Helper::format_data(SUCC,$str->id);
                }
            }elseif($request[‘status‘] == 2){ //个推
                $data = $user->find()->where([‘id‘=>$wx_id])->one();
                if(empty($data)){
                    return Helper::format_data(INVALID_ACCESS_TOKEN,null);
                }
                if($data->amount < $money){
                $result = FreeDelivery::deleteAll([‘shop_id‘=>$request[‘shop_id‘]]);
                if($data->save(false)){
                    $data->money_count += $data->amount;
                    $data->amount = 0;
                    if($data->save(false)){
                            if($str->save(false)){
                                
                                return Helper::format_data(SUCC,[‘shop_id‘=>$request[‘shop_id‘],‘type‘=>1]);
                            }
                        }
                    }
                }
                $data->amount -= $money;
                $data->save(false);
                if($data->save(false) == false)        return Helper::format_data(ERROR_WXUSER,$data->getErrors());
                if($str->save(false)){
                    return Helper::format_data(SUCC,$str->id);
                }
            }
            
        }elseif($request[‘type‘] == 2){
            $models = new ShopActive();
            $active = $models->find()->where([‘a_id‘=>$request[‘active_id‘]])->one();
            $active->browser += $request[‘browser‘];
            if($active->save(false)){
                return Helper::format_data(SUCC,$active->a_id);
            }
            return Helper::format_data(ERROR_ORDER,$active->getErrors());
        }
        $AdminDelivery = new AdminDelivery();
        $data = $AdminDelivery->find()->where([‘active_id‘=>$request[‘active_id‘]])->one();
        if(empty($data)){
            $AdminDelivery->shop_id = $request[‘shop_id‘];
            $AdminDelivery->active_id = $request[‘active_id‘];
            $AdminDelivery->price = $money;
            $AdminDelivery->delivery_time = date(‘Ymd‘);
            $AdminDelivery->browse_num = $request[‘browser‘];
            if($AdminDelivery->save()){
                return Helper::format_data(SUCC,$AdminDelivery->id);
            }
            return Helper::format_data(ERROR_ORDER,$AdminDelivery->getErrors());
        }
        $data->price += $money;
        $data->browse_num += $request[‘browser‘];
        if($data->save(false)){
            return Helper::format_data(SUCC,$data->id);
        }
        return Helper::format_data(ERROR_ORDER,$data->getErrors());
     }
}

 

以上是关于微信公众号开发代码参考的主要内容,如果未能解决你的问题,请参考以下文章

PHP微信公众号开发常用功能

微信公众号开发

微信公众号开发

如何编辑微信公众号内容?

微信公众号如何使用域名直接调试本地开发环境代码的方案

微信公众平台如何通过php代码给会员发送被动响应消息