• thinkphp5.0 + 微信分享


    因为是做微信公众号好友助力的活动和游戏,所以有个需要分享的页面,判定谁分享出去的,然后谁帮助了好友,和之前获取userinfo的一起贴出来.

    1.入口文件(名字随便取,你开心就好.下面只贴文件里的方法)

        //获取用户头像和微信号
        public  function getUserInfo(){
    //        $appid='wxa037f5cede358c84';
    //        $appsecret='e4cdd89734bae590bce8abbcfda82940';
            $app = Db::name('wxconf')->where('id=1')->find();
            $appid = $app['appid'];
            $appsecret = $app['appsecret'];
    
            if(!$appid || !$appsecret){
                self::alter("请配置appid和appsecret");exit;
            }
    
                $request=Request::instance();
                $code=$request->param('code');
                if (!$code) {
                    header("Content-type: text/html; charset=utf-8");
                    $redirect_url='http://'.$_SERVER['HTTP_HOST'].$_SERVER['PHP_SELF'];
                    $this->redirect("https://open.weixin.qq.com/connect/oauth2/authorize?appid={$appid}&redirect_uri={$redirect_url}&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect");
                } else {
                    $code = $request->param('code');
                    $tokenurl = "https://api.weixin.qq.com/sns/oauth2/access_token?appid={$appid}&secret={$appsecret}&code={$code}&grant_type=authorization_code";
                    $token = $this->http_get($tokenurl);
                    $tokenobj = json_decode($token);
                    $access_token = $tokenobj->access_token;
                    $openid = $tokenobj->openid;
                    if(!$access_token || !$openid){
                        self::alter($tokenobj->errmsg);exit;
                    }
                    $userurl = "https://api.weixin.qq.com/sns/userinfo?access_token={$access_token}&openid={$openid}&lang=zh_CN";
                    $info = $this->http_get($userurl);
                    $infoobj = json_decode($info);
                    $data['openid'] = $openid;
                    $data['username'] = $infoobj->nickname;
                    $data['avatar'] = $infoobj->headimgurl;
                    session('userInfo',$data);
    
                }
            }
    
        public function http_get($url){
            $ch = curl_init($url) ;
            curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);//https
            curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);//https
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, true) ;
            curl_setopt($ch, CURLOPT_BINARYTRANSFER, true) ;
            $output = curl_exec($ch) ;
            curl_close($ch);
            return $output;
        }
        public function alter($msg){
            echo <<<EOF
            <script>
            alert($msg);
            </script>
    EOF;
    
        }
    
        //获取验证access_token
        function access_token($appid,$appsecret,$access_token,$access_token_time,$expires_in)
        {
    
    
            //判断access_token有效期)
            if((time()-$access_token_time)>=$expires_in)
            {
                //接口地址http请求方式: GET
                $url="https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=$appid&secret=$appsecret";
                $retdate=  $this->curl_get($url);
                //判断获取access_token
                $access_token= json_decode($retdate,true);
                if($access_token['access_token']!='' && $access_token['expires_in']>0)
                {
                    //修改数据库
                    $conf = Db::name('wxconf');
                    $data['access_token']      = $access_token['access_token'];
                    $data['access_token_time'] = time();
                    $data['expires_in']        = $access_token['expires_in']-3600;
                    $i = $conf->where('id=1')->update($data);
                    if($i)
                    {
    
                    }
                    else
                    {
                        exit('数据库写入access_token失败!');
                    }
                }
                else
                {
                    exit($retdate);
                }
            }
    
    
        }
    
        //获取验证jsapi_ticket
        function jsapi_ticket($access_token,$jsapi_ticket,$jsapi_ticket_time,$jsexpires_in)
        {
            //判断jsapi_ticket有效期)
            if((time()-$jsapi_ticket_time)>=$jsexpires_in)
            {
                //接口地址http请求方式: GET
                $url="https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=$access_token&type=jsapi";
                $retdate=  $this->curl_get($url);
                //判断获取jsapi_ticket
                $jsapi_ticket= json_decode($retdate,true);
                if($jsapi_ticket['errcode']=='0')
                {
                    //修改数据库
                    $conf = Db::name('wxconf');
                    $data['jsapi_ticket']      = $jsapi_ticket['ticket'];
                    $data['jsapi_ticket_time'] = time();
                    $data['jsexpires_in']      = $jsapi_ticket['expires_in'];
                    $i = $conf->where('id=1')->update($data);
                    if($i)
                    {
                        return $jsapi_ticket['ticket'];
                    }
                    else
                    {
                        exit('数据库写入access_token失败!');
                    }
                }
                else
                {
                    exit($retdate);
                }
            }
            else
            {
                return $jsapi_ticket;
            }
    
    
        }
        //提交方法GET
        function curl_get($url)
        {
    
            $ch = curl_init ();
            curl_setopt ( $ch, CURLOPT_CUSTOMREQUEST, 'GET' );
            curl_setopt ( $ch, CURLOPT_SSL_VERIFYPEER, false );
            curl_setopt ( $ch, CURLOPT_URL, $url );
            ob_start ();
            curl_exec ( $ch );
            $return_content = ob_get_contents ();
            ob_end_clean ();
            $return_code = curl_getinfo ( $ch, CURLINFO_HTTP_CODE );
            return $return_content;
        }
    
    
    
        //提交方法POST
        function curl_post($url,$post_data)
        {
            //初始化
            $curl = curl_init();
            //设置抓取的url
            curl_setopt($curl, CURLOPT_URL,$url);
            //设置头文件的信息作为数据流输出
            curl_setopt($curl, CURLOPT_HEADER, 1);
            //设置获取的信息以文件流的形式返回,而不是直接输出。
            curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
            //设置post方式提交
            curl_setopt($curl, CURLOPT_POST, 1);
            //设置post数据
            /*
            $post_data = array(
                "username" => "coder",
                "password" => "12345"
                );*/
            //关闭SSL认证
            curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
            //提交数据
            curl_setopt($curl, CURLOPT_POSTFIELDS, $post_data);
            //执行命令
            $data = curl_exec($curl);
    
            if(curl_errno($curl))
            {
                return  'errno'.curl_error($curl);
            }
            else
            {
                //显示获得的数据
                return $data;
            }
    
        }

    2. 页面的方法

        public function index(){$openid=session('userInfo.openid');//当前用户的openid
    
            //分享配置
            $share =new Weixin();//上面贴的方法文件
            $conf = Db::name('wxconf');//实例化表格  以下是表格内容
            $data = $conf->where('id=1')->find();
            $appid            = $data['appid'];
            $appsecret        = $data['appsecret'];
            $access_token     = $data['access_token'];
            $access_token_time= $data['access_token_time'];
            $expires_in       = $data['expires_in'];
            $jsapi_ticket     = $data['jsapi_ticket'];
            $jsexpires_in     = $data['jsexpires_in'];
            $jsapi_ticket_time= $data['jsapi_ticket_time'];
            //获取验证access_token
            $returns = $share->access_token($appid,$appsecret,$access_token,$access_token_time,$expires_in);
            if($returns==1)
            {
                $data = $conf->where('id=1')->find();
                $jsapi_ticket = $data['jsapi_ticket'];
                $jsexpires_in = $data['jsexpires_in'];
                $jsapi_ticket_time = $data['jsapi_ticket_time'];
            }
    
            $jsapi_ticket =  $share->jsapi_ticket($access_token,$jsapi_ticket,$jsapi_ticket_time,$jsexpires_in);
            $noncestr = $this->create_chr(16);
            $timestamp= time();
            // 注意 URL 一定要动态获取,不能 hardcode.
            $protocol = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off' || $_SERVER['SERVER_PORT'] == 443) ? "https://" : "http://";
            $url = "$protocol$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
            $signstr ='jsapi_ticket='.$jsapi_ticket.'&noncestr='.$noncestr.'&timestamp='.$timestamp.'&url='.$url;
            $signature =sha1($signstr);
    
            $this->assign('appid',$appid);
            $this->assign('signature',$signature);
            $this->assign('nonceStr',$noncestr);
            $this->assign('timestamp',$timestamp);
            //分享内容
            $wxshare = Db::name('info');//实例化信息表 里面有活动分享的标题 链接 图片 描述
            $share = $wxshare->where('id=1')->find();
            $this->assign('title',$share['wx_share_title']);//分享标题
            $this->assign('links',$share['wx_share_url'].'?openid='.$openid);//分享链接
            $imgurl = $protocol.$share['src'].UPLOADS_IMG.$share['wx_share_pic'];//分享图片链接
            $this->assign('imgurl',$imgurl);
            $this->assign('descs',$share['wx_share_draw']);//分享描述
    
            return $this->fetch();
    //        }
        }

    3.view上的js

    用了layui 没用的可以自己改成alert 这个无所谓

    <script src="http://res.wx.qq.com/open/js/jweixin-1.2.0.js"></script>
    
    
    <script>
    //赋值系统配置
    var appId     = '{$appid}';
    var timestamp = '{$timestamp}';
    var nonceStr  = '{$nonceStr}';
    var signature = '{$signature}';
    //赋值分享配置
    var title = '{$title}';
    var links = '{$links}';
    var imgurl= '{$imgurl}';
    var descs = '{$descs}'; 
     //alert(imgurl);alert(descs);
    wx.config({
        debug:false,  
        appId: appId,  
        timestamp: timestamp,  
        nonceStr:  nonceStr,  
        signature: signature, 
        jsApiList: ['onMenuShareTimeline','onMenuShareAppMessage','onMenuShareQQ','onMenuShareWeibo','onMenuShareQZone']  
    });
    
    wx.ready(function()
    {
        
    
        //分享到朋友圈
        wx.onMenuShareTimeline({
            // 分享标题
            title:title, 
            // 分享链接,该链接域名或路径必须与当前页面对应的公众号JS安全域名一致
            link:links, 
            // 分享图标
            imgUrl:imgurl, 
            success: function () 
            { 
                // 用户确认分享后执行的回调函数
                ajax_fx('微信朋友圈');
            },
            cancel: function () 
            { 
                // 用户取消分享后执行的回调函数
          
            }
        });
        
        //分享给朋友
        wx.onMenuShareAppMessage({
            // 分享标题
            title:title, 
            // 分享描述
            desc:descs, 
            // 分享链接,该链接域名或路径必须与当前页面对应的公众号JS安全域名一致
            link:links, 
            // 分享图标
            imgUrl:imgurl, 
            // 分享类型,music、video或link,不填默认为link
            type: 'link', 
            // 如果type是music或video,则要提供数据链接,默认为空
            dataUrl: '', 
            success: function () 
            { 
                // 用户确认分享后执行的回调函数
                 ajax_fx('微信朋友');
            },
            cancel: function () 
            { 
                // 用户取消分享后执行的回调函数
            }
        });
        //分享到QQ
        wx.onMenuShareQQ({
            // 分享标题
            title:title, 
            // 分享描述
            desc:descs, 
            // 分享链接
            link:links, 
            // 分享图标
            imgUrl:imgurl, 
            success: function () 
            { 
               // 用户确认分享后执行的回调函数
                ajax_fx('QQ');
            },
            cancel: function () 
            { 
               // 用户取消分享后执行的回调函数
            }
        });
        
        //分享到腾讯微博
        wx.onMenuShareWeibo({
            // 分享标题
            title:title, 
            // 分享描述
            desc: descs, 
            // 分享链接
            link:links, 
            // 分享图标
            imgUrl:imgurl, 
            success: function () { 
               // 用户确认分享后执行的回调函数
               ajax_fx('腾讯微博');
            },
            cancel: function () { 
                // 用户取消分享后执行的回调函数
            }
        });
        //分享到QQ空间
        wx.onMenuShareQZone({
            // 分享标题
            title:title, 
            // 分享描述
            desc:descs, 
            // 分享链接
            link:links, 
            // 分享图标
            imgUrl:imgurl, 
            success: function () { 
               // 用户确认分享后执行的回调函数
               ajax_fx('QQ空间');
            },
            cancel: function () { 
                // 用户取消分享后执行的回调函数
            }
        });
    
    
    });
    // 需要检测的JS接口列表,所有JS接口列表见附录2,
    /*
    wx.checkJsApi({
        jsApiList: ['onMenuShareTimeline'], 
        success: function(res) 
        {
            //alert(res);
            // 以键值对的形式返回,可用的api值true,不可用为false
            // 如:{"checkResult":{"chooseImage":true},"errMsg":"checkJsApi:ok"}
        }
    });
    */
    
      function ajax_fx(d)
      {
         $.ajax({
                   type: "POST",
                   url: "{:U('Home/index/index7_do')}",
                   data: 'd='+d,
                   success: function(msg)
                   { 
                     if(msg==2)
                     {
                        //提示
                            layer.open({
                            content: '分享成功,获得了答题次数奖励!'
                            ,skin: 'msg'
                            ,time: 5 //2秒后自动关闭
                            });
                     }  
                     else if(msg==1)
                     {
                        //提示
                            layer.open({
                            content: '分享成功,今日已获得过分享奖励了!'
                            ,skin: 'msg'
                            ,time: 5 //2秒后自动关闭
                            });
                     } 
                     else
                     {
                            //提示
                            layer.open({
                            content: '系统错误,请稍候再试!'
                            ,skin: 'msg'
                            ,time: 5 //2秒后自动关闭
                            });
                     } 
                   }
                }); 
      } 
    </script>
    技术最菜,头发最少
  • 相关阅读:
    swift5.x 错误处理
    iOS--iPhoneX设备判断
    swift5.x 多线程的应用场景
    Swift5.x 多线程编程
    Swift5.x 范型
    swift5.x 类初始化、反初始化, 指定初始化器,便利初始化器
    swift5.x 扩展(extension)
    swift5.x 多态,类型检查,类型转换
    Effective java笔记(十),序列化
    Effective java笔记(九),并发
  • 原文地址:https://www.cnblogs.com/gushengyan/p/9012757.html
Copyright © 2020-2023  润新知