一、注册融云账号

如果我们不是以即时通讯为主营业务;那么建议使用第三方的服务;这里以融云为例;

官网:http://www.rongcloud.cn/

注册融云;创建应用;获得App Key和App Secret;

二、设置配置文件 prtected/config/params.php

 'RONG_IS_DEV'            => true,//是否是在开发中
// 'RONG_DEV_APP_KEY' => '8luwapkvu3xwl', //融云开发环境下的key 仅供测试使用
// 'RONG_DEV_APP_SECRET' => '1Aw1D7F6Td25', //融云开发环境下的SECRET 仅供测试使用
'RONG_DEV_APP_KEY' => 'x4vkb1qpx4vkk', //融云开发环境下的key 仅供测试使用
'RONG_DEV_APP_SECRET' => 'QaMSerPSeF', //融云开发环境下的SECRET 仅供测试使用
'RONG_PRO_APP_KEY' => '', //融云生产环境下的key
'RONG_PRO_APP_SECRET' => '', //融云生产环境下的SECRET

三、加载配置文件(见附件)

     3.1 RongCloud 融云Service API 接口    引入融云sdk:/prtected/vendor/RongCloud.class.php  ----文件见附件

     3.2 引入静态页面文件  base、emoji、rongcloud(融云文件)  /themes/default    ----文件见附件

四、公共方法代码 公共函数: /prtected/componts/Common.php

     

  1 /**
  2     * 根据配置项获取对应的key和secret
  3     * @return array key和secret
  4     */
  5    public static function get_rong_key_secret(){
  6       // 判断是需要开发环境还是生产环境的key
  7       $RONG_IS_DEV=Yii::app()->params['RONG_IS_DEV'];
  8 //    $key=Yii::$app->params['RONG_DEV_APP_KEY'];
  9 //    $secret=Yii::$app->params['RONG_DEV_APP_SECRET'];
 10       if ($RONG_IS_DEV) {
 11          $key=Yii::app()->params['RONG_DEV_APP_KEY'];;
 12          $secret=Yii::app()->params['RONG_DEV_APP_SECRET'];
 13       }else{
 14          $key=Yii::app()->params['RONG_DEV_APP_KEY'];;
 15          $secret=Yii::app()->params['RONG_DEV_APP_SECRET'];
 16       }
 17       $data=array(
 18          'key'=>$key,
 19          'secret'=>$secret
 20       );
 21       return $data;
 22    }
 23    /**
 24     * 获取融云token
 25     * @param  integer $uid 用户id
 26     * @return integer      token
 27     */
 28 public static function get_rongcloud_token($uid){
 29       // 从数据库中获取token
 30       $token=OauthUser::model()->find('uid=:uid',array(':uid'=>$uid));
 31 
 32       // 如果有token就返回
 33       if ($token&&$token->access_token) {
 34          return $token->access_token;
 35       }
 36        $res=self::getNameAvatar($uid);//获取用户名称和头像
 37       if($res==false){
 38          return false;
 39       }
 40       // 获取key和secret
 41       $key_secret=self::get_rong_key_secret();
 42       // 实例化融云
 43       $rong_cloud=new RongCloud($key_secret['key'],$key_secret['secret']);
 44       // 获取token
 45       $token_json=$rong_cloud->getToken($uid,$res['name'],$res['avatar']);
 46       $token_array=json_decode($token_json,true);
 47       // 获取token失败
 48       if ($token_array['code']!=200) {
 49          return false;
 50       }
 51       $token=$token_array['token'];
 52       $objectPost = new OauthUser;
 53       $objectPost->uid = $uid;
 54       $objectPost->type = 1;
 55       $objectPost->nickname = $res['name'];
 56       $objectPost->head_img = $res['avatar'];
 57       $objectPost->access_token = $token;
 58       if ($objectPost->save()) {
 59          return $token;
 60       }else{
 61          return false;
 62       }
 63    }
 64    /**
 65     * 更新融云头像
 66     * @param  integer $uid 用户id
 67     * @return boolear      操作是否成功
 68     */
 69 public static function refresh_rongcloud_token($uid){
 70        $res=self::getNameAvatar($uid);
 71        if($res==false){
 72          return false;
 73       }
 74       // 获取key和secret
 75       $key_secret=self::get_rong_key_secret();
 76       // 实例化融云
 77       $rong_cloud=new RongCloud($key_secret['key'],$key_secret['secret']);
 78       // 更新融云用户头像
 79       $result_json=$rong_cloud->userRefresh($uid,$res['name'],$res['avatar']);
 80       $result_array=json_decode($result_json,true);
 81       if ($result_array['code']==200) {
 82          return true;
 83       }else{
 84          return false;
 85       }
 86    }
 87    /**
 88     * 获取名称,头像
 89     * @param  integer $uid 用户id
 90     * @return $arr    name 名称 avatar头像
 91     */
 92    public static function getNameAvatar($uid){
 93         // 获取用户昵称和头像
 94       $user_data=Users::model()->find('uid=:uid',array(':uid'=>$uid));
 95       //获取店铺名称和头像
 96       $store_data=Store::model()->find('user_id=:user_id AND st_status=1',array(':user_id'=>$uid));
 97       // 用户不存在
 98       if (empty($user_data)&&empty($store_data)) {
 99          return false;
100       }elseif (empty($store_data)){
101          $arr['name']=$user_data->user_name;
102          $arr['avatar']=self::getImg($user_data->avatar);
103       }else{
104          $arr['name']=$store_data->store_name;
105          $arr['avatar']=self::getImg($store_data->st_pics);
106       }
107       return $arr;
108    }

五、写一个控制器用来获取token、好友列表的头像和用户名:\protected\modules\customers\controllers\RongController.class.php

 

 1 <?php
 2 /**
 3  * 融云api接口
 4  */
 5 class RongController extends Controller
 6 {
 7     /**
 8      * @var string the default layout for the views. Defaults to '//layouts/column2', meaning
 9      * using two-column layout. See 'protected/views/layouts/column2.php'.
10      */
11     public $layout = "//layouts/default";
12 
13     /**
14      * @return array action filters
15      */
16     public function filters()
17     {
18         return array(
19             'accessControl', // perform access control for CRUD operations
20             'postOnly + delete', // we only allow deletion via POST request
21         );
22     }
23 
24     /**
25      * Specifies the access control rules.
26      * This method is used by the 'accessControl' filter.
27      * @return array access control rules
28      */
29     public function accessRules()
30     {
31         return array(
32         array('allow',  // allow all users to perform 'index' and 'view' actions
33                 'actions'=>array('getToken','getUserInfo'),
34                 'users'=>array('*'),
35         ),
36         array('allow',
37                 'actions'=>array('admin','delete','create','update'),
38                 'expression' => 'ComView::res_access()'
39                 ),
40 
41                 array('deny',  // deny all users
42                 'users'=>array('*'),
43                 ),
44                 );
45     }
46     /**
47      * 获取token
48      */
49     public function actionGetToken(){
50         // 获取用户id
51         $uid=Yii::app()->user->getId();
52         // 获取token
53         $token=Common::get_rongcloud_token($uid);
54         $data=array(
55             'token'=>$token
56         );
57         $this->ajax_return($data,'获取成功',0);
58     }
59     /**
60      * 传递一个、或者多个用户id
61      * 获取用户头像用户名;用来组合成好友列表
62      */
63     public function actionGetUserInfo(){
64         if(!isset($_POST['uids'])||!empty($_POST['uids'])){
65             $uids=$_POST['uids'];
66             $uids=explode(',',$uids);
67             $data=array();
68             for ($i=0;$i<count($uids);$i++){
69                 $res=Common::getNameAvatar($uids[$i]);
70                 $data[$i]['id']=$uids[$i];
71                 if($res){
72                     $data[$i]['username']=$res['name'];
73                     $data[$i]['avatar']=$res['avatar'];
74                 }
75             }
76             $this->ajax_return($data,'获取用户数据成功',0);
77         }
78     }
79 
80     function ajax_return($data='',$error_message='成功',$error_code=1){
81         $all_data=array(
82             'error_code'=>$error_code,
83             'error_message'=>$error_message,
84         );
85         $all_data['data']=$data;
86         echo json_encode($all_data);
87         exit(0);
88     }
89 
90 }
View Code

六、控制器代码获取用户信息 加载到页面

     

        $user_data=new Users();
        if(Yii::app()->user->getId()){
            $user_data=Users::model()->find('uid=:uid',array(':uid'=>Yii::app()->user->getId()));
            $data=Common::getNameAvatar(Yii::app()->user->getId());
            $user_data->uid=Yii::app()->user->getId();
            $user_data->user_name=$data['name'];
            $user_data->avatar=$data['avatar'];
        }
        // 获取融云key
        $rong_key_secret=Common::get_rong_key_secret();
        $this->render('store_list',array(
            'model'=>$model,
            'dataProvider'=>$dataProvider,
            'user_data'=>$user_data,
            'rong_key'=>$rong_key_secret['key'],// 融云key
            'rong_token'=>Common::get_rongcloud_token($user_data->uid)//获取融云token
        ));

 

七、集成前端部分Html 代码 

      加载前端Css 、js 文件 融云文件等。 

然后下面是我痛苦的研究了融云的sdk后简化了的使用方法;

 

    /themes/default/rongcloud/js/main.js (主要文件)

 

  1 <link rel="stylesheet" href="<?php echo Yii::app()->request->baseUrl;?>/themes/default/rongcloud/css/bootstrap.min.css"/>
  2 <link rel="stylesheet" href="<?php echo Yii::app()->request->baseUrl;?>/themes/default/rongcloud/css/bootstrap-theme.min.css" />
  3 <link rel="stylesheet" type="text/css" href="<?php echo Yii::app()->request->baseUrl;?>/themes/default/base/css/base.css"/>
  4 <link rel="stylesheet" type="text/css" href="<?php echo Yii::app()->request->baseUrl;?>/themes/default/js/swiper/idangerous.swiper.css"/>
  5 <!--<body class="modal-open">-->
  6 <!--<button class="bjy-rong-chat" targetid="89" avatar="/Upload/avatar/user2.jpg" targetname="admin2">点击与用户2(admin2)聊天-->
  7 <!--</button>-->
  8     <div class="modal fade" id="bjy-chat-modal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel"
  9          aria-hidden="true" style="display: none;">
 10         <div class="modal-dialog">
 11             <div class="modal-content">
 12                 <div class="bjy-top">
 13                     <div class="bjy-t-myinfo"> <?php echo $user_data['user_name'];?>
 14                         <img class="bjy-t-avatar"
 15                           src="<?php echo $user_data['avatar'];?>">
 16                     </div>
 17                     <div class="bjy-t-title"><span class="bjy-tt-name"></span><span class="bjy-tt-edu"></span>
 18                         <div class="bjy-tt-close" data-dismiss="modal" aria-hidden="true"></div>
 19                     </div>
 20                 </div>
 21                 <div class="bjy-chat bjy-emoji-out3">
 22                     <div class="bjy-friend-list"></div>
 23                     <div class="bjy-chat-box bjy-show-out">
 24                         <div class="bjy-cb-history"></div>
 25                         <div class="bjy-cb-middle">
 26                             <button type="button" class="bjy-emoji-ico"></button>
 27                             <div class="bjy-emoji-box">
 28                                 <div class="bjy-e-triangle" style="display:block;width:20px;height:20px;">
 29                                     <div style="display:block;position:absolute;left:10px;top:10px;width:0;height:0;border-style:solid;border-width:10px;border-color:transparent transparent #eee  transparent;"></div>
 30                                     <div style="display:block;position:absolute;left:10px;top:11px;;width:0;height:0;border-style:solid;border-width:10px;border-color:transparent transparent #fff transparent;"></div>
 31                                 </div>
 32                                 <div class="xb-h-10"></div>
 33                                 <ul class="nav nav-tabs">
 34                                     <li class="active bjy-emoji-category"><a href="#bjy-face-11" data-toggle="tab">表情</a>
 35                                     </li>
 36                                     <li class="bjy-emoji-category"><a href="#bjy-face-12" data-toggle="tab">动物</a></li>
 37                                     <li class="bjy-emoji-category"><a href="#bjy-face-13" data-toggle="tab">水果</a></li>
 38                                     <li class="bjy-emoji-category"><a href="#bjy-face-14" data-toggle="tab">国旗</a></li>
 39                                     <li class="bjy-emoji-category"><a href="#bjy-face-15" data-toggle="tab">键盘</a></li>
 40                                 </ul>
 41                                 <div class="tab-content">
 42                                     <div class="tab-pane fade bjy-emoji-imgs in active" id="bjy-face-11"></div>
 43                                     <div class="tab-pane fade bjy-emoji-imgs" id="bjy-face-12"></div>
 44                                     <div class="tab-pane fade bjy-emoji-imgs" id="bjy-face-13"></div>
 45                                     <div class="tab-pane fade bjy-emoji-imgs" id="bjy-face-14"></div>
 46                                     <div class="tab-pane fade bjy-emoji-imgs" id="bjy-face-15"></div>
 47                                 </div>
 48                             </div>
 49                         </div>
 50                         <div class="bjy-cb-sendbox"><textarea
 51                                 class="bjy-emoji-textarea bjy-emoji-from3 bjy-cbs-content hide" name="content"></textarea>
 52                             <div class="bjy-show-box bjy-emoji-box3" contenteditable="true"></div>
 53                         </div>
 54                         <ul class="bjy-cb-handle">
 55                             <li class="bjy-cbh-close" data-dismiss="modal" aria-hidden="true">关闭</li>
 56                             <li class="bjy-cbh-send" data-uid=''>发送</li>
 57                         </ul>
 58                     </div>
 59                 </div>
 60             </div>
 61         </div>
 62     </div>
 63     <script src="<?php echo Yii::app()->request->baseUrl;?>/themes/default/rongcloud/js/jquery-1.10.2.min.js"></script>
 64 <script src="<?php echo Yii::app()->request->baseUrl;?>/themes/default/rongcloud/js/bootstrap.min.js"></script>
 65     <script>
 66 
 67         var xbIsLogin = 1,
 68             Loginurl="<?php echo yii::app()->createUrl('user/users/userAuth');?>"
 69             rongUserInfoUrl = "<?php echo yii::app()->createUrl('customers/rong/getUserInfo');?>",
 70             rongKey = "<?php echo $rong_key;?>",
 71             rongToken = "<?php echo $rong_token;?>",
 72             xbUserInfo = {
 73                 id: "<?php echo $user_data['uid'];?>",
 74                 name: "<?php echo $user_data['user_name'];?>",
 75                 avatar: "<?php echo $user_data['avatar'];?>"
 76             };
 77         if("<?php echo $user_data['uid'];?>"==''){
 78             xbIsLogin = false;//判断是否登陆
 79          }
 80 
 81         // 下面的代码是用来测试的
 82 //        $('#bjy-chat-modal').modal('show');
 83 //        setTimeout(function () {
 84 //            $('.bjy-fl-one').click();
 85 //        }, 2000)
 86     </script>
 87     <script src="<?php echo Yii::app()->request->baseUrl;?>/themes/default/emoji/js/config.js"></script>
 88     <script src="<?php echo Yii::app()->request->baseUrl;?>/themes/default/emoji/js/emoji-picker.js"></script>
 89     <script src="<?php echo Yii::app()->request->baseUrl;?>/themes/default/emoji/js/jquery.emojiarea.js"></script>
 90     <script src="http://cdn.ronghub.com/RongIMLib-2.0.6.beta.min.js"></script>
 91     <script src="<?php echo Yii::app()->request->baseUrl;?>/themes/default/rongcloud/js/RongEmoji-2.0.2.beta.min.js"></script>
 92     <script src="<?php echo Yii::app()->request->baseUrl;?>/themes/default/rongcloud/js/main.js"></script>
 93     <script src="<?php echo Yii::app()->request->baseUrl;?>/themes/default/base/js/base.js"></script>
 94     <script>
 95         $(function () {
 96             // 初始化emoji
 97             window.emojiPicker = new EmojiPicker({
 98                 emojiable_selector: '[data-emojiable=true]',
 99                 assetsPath: '<?php echo Yii::app()->request->baseUrl;?>/themes/default/emoji/images',
100                 'iconSize': 20
101             });
102             window.emojiPicker.discover();
103 
104 
105             // 需要转emoji的选择器 表情选择、学霸秀、聊天框
106             var toEmoji = ['.bjy-emoji-box', '.lqk-cfont-one', '.bjy-cbhl-content,.lqk-sshow-info'];
107             $.each(toEmoji, function (index, val) {
108                 $.each($(val), function (k, v) {
109                     var str = $(v).html();
110                     var newStr =window.emojiPicker.unicodeToImage(str);
111                     $(v).html(newStr);
112                 });
113 
114             });
115             // 评论框内的图片转换为from中utf8
116             var imageDiv = ['.bjy-emoji-box1', '.bjy-emoji-box2', '.bjy-emoji-box3'];
117             var emojiFrom = ['.bjy-emoji-from1', '.bjy-emoji-from2', '.bjy-emoji-from3'];
118             $.each(imageDiv, function (index, val) {
119                 $(val).blur(function (event) {
120                     var str = emojiDeleteTag($(this).html());
121                     $(emojiFrom[index]).val(str);
122                 });
123             });
124 
125             /**
126              * 将带有emoji图片的字符串转为utf8
127              * @param  {string} str 带emoji图片的字符串
128              * @return {string}     utf8字符串
129              */
130             function emojiDeleteTag(str) {
131                 var str = str.replace(/<img.*?src=\".*?\".*?style=\".*?\".*?alt=\"/g, '');
132                 var str = str.replace(/<img.*?style=\'.*?\'.*?alt=\"/g, '');
133                 var str = str.replace(/\".*?src=\".*?\">/g, '');
134                 str = str.replace(/:">/g, ':');
135                 str = window.emojiPicker.colonToUnicode(str);
136                 return str;
137             }
138 
139             // 显示或隐藏表情框
140             $('.bjy-emoji-ico').click(function (event) {
141                 var parentObj = $(this).parents('.bjy-show-out').eq(0);
142                 parentObj.find('.bjy-emoji-box').toggleClass('show');
143                 parentObj.find('.bjy-emoji-category').eq(0).click();
144             });
145             // 点击emoji分类;获取分类下的表情
146             $('.bjy-emoji-box').on('click', '.bjy-emoji-category', function (event) {
147                 var indexNumber = $(this).index(),
148                     thisEmojiConfig = Config.EmojiCategories[indexNumber],
149                     thisHtml = '',
150                     colon = '';
151                 // 将colon格式的标签转为图片格式
152                 $.each(thisEmojiConfig, function (index, val) {
153                     colon += ':' + Config.Emoji[val][1][0] + ':';
154                     thisHtml = window.emojiPicker.colonToImage(colon);
155                 });
156                 // 将图片插入到div中
157                 $(this).parents('.bjy-emoji-box').eq(0).find('.bjy-emoji-imgs').eq(indexNumber).html(thisHtml);
158             });
159             // 点击添加表情
160             $('body').on('click', '.bjy-emoji-box img', function (event) {
161                 var str = $(this).prop("outerHTML");
162                 $(this).parents('.bjy-show-out').eq(0).find('.bjy-show-box').focus();
163                 insertHtmlAtCaret(str);
164                 // 选择表情后关闭表情选择框
165                 $(this).parents('.bjy-show-out').eq(0).find('.bjy-emoji-box').removeClass('show')
166             });
167 
168         })
169 
170 
171         /**
172          * 在textarea光标后插入内容
173          * @param  string  str 需要插入的内容
174          */
175         function insertHtmlAtCaret(str) {
176             var sel, range;
177             if (window.getSelection) {
178                 sel = window.getSelection();
179                 if (sel.getRangeAt && sel.rangeCount) {
180                     range = sel.getRangeAt(0);
181                     range.deleteContents();
182                     var el = document.createElement("div");
183                     el.innerHTML = str;
184                     var frag = document.createDocumentFragment(), node, lastNode;
185                     while ((node = el.firstChild)) {
186                         lastNode = frag.appendChild(node);
187                     }
188                     range.insertNode(frag);
189                     if (lastNode) {
190                         range = range.cloneRange();
191                         range.setStartAfter(lastNode);
192                         range.collapse(true);
193                         sel.removeAllRanges();
194                         sel.addRange(range);
195                     }
196                 }
197             } else if (document.selection && document.selection.type != "Control") {
198                 document.selection.createRange().pasteHTML(str);
199             }
200         }
201     </script>
202 <!--</body>-->

 具体详细代码请看上一篇Tp的   

    

      

posted on 2017-02-18 16:00  IM杨燕飞  阅读(979)  评论(0编辑  收藏  举报