美文网首页
php微信分享

php微信分享

作者: Mracale | 来源:发表于2021-12-19 15:04 被阅读0次

    后台代码

    <?php
    $appid="";
    $secret="";
    class JSSDK {
      private $appId;
      private $appSecret;
     
      public function __construct($appId, $appSecret) {
        $this->appId = $appId;
        $this->appSecret = $appSecret;
      }
     
      public function getSignPackage() {
        $jsapiTicket = $this->getJsApiTicket();
        $url = "http://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
        $timestamp = time();
        $nonceStr = $this->createNonceStr();
     
        // 这里参数的顺序要按照 key 值 ASCII 码升序排序
        $string = "jsapi_ticket=$jsapiTicket&noncestr=$nonceStr&timestamp=$timestamp&url=$url";
     
        $signature = sha1($string);
     
        $signPackage = array(
          "appId"     => $this->appId,
          "nonceStr"  => $nonceStr,
          "timestamp" => $timestamp,
          "url"       => $url,
          "signature" => $signature,
          "rawString" => $string
        );
        return $signPackage;
      }
     
      private function createNonceStr($length = 16) {
        $chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
        $str = "";
        for ($i = 0; $i < $length; $i++) {
          $str .= substr($chars, mt_rand(0, strlen($chars) - 1), 1);
        }
        return $str;
      }
     
      private function getJsApiTicket() {
        // jsapi_ticket 应该全局存储与更新,以下代码以写入到文件中做示例
        $data = json_decode(file_get_contents("jsapi_ticket.json"));
        if (empty($data) || $data->expire_time < time()) {
          $accessToken = $this->getAccessToken();
          $url = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?type=jsapi&access_token=$accessToken";
          $res = json_decode($this->httpGet($url));
          $ticket = $res->ticket;
          if ($ticket) {
            $data->expire_time = time() + 7000;
            $data->jsapi_ticket = $ticket;
            $fp = fopen("jsapi_ticket.json", "w");
            fwrite($fp, json_encode($data));
            fclose($fp);
          }
        } else {
          $ticket = $data->jsapi_ticket;
        }
     
        return $ticket;
      }
     
      private function getAccessToken() {
        // access_token 应该全局存储与更新,以下代码以写入到文件中做示例
        $data = json_decode(file_get_contents("access_token.json"));
        if (empty($data) || $data->expire_time < time()) {
          $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=$this->appId&secret=$this->appSecret";
          $res = json_decode($this->httpGet($url));
          $access_token = $res->access_token;
          if ($access_token) {
            $data->expire_time = time() + 7000;
            $data->access_token = $access_token;
            $fp = fopen("access_token.json", "w");
            fwrite($fp, json_encode($data));
            fclose($fp);
          }
        } else {
          $access_token = $data->access_token;
        }
        return $access_token;
      }
     
      private function httpGet($url) {
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($curl, CURLOPT_TIMEOUT, 500);
        curl_setopt($curl, CURLOPT_URL, $url);
     
        $res = curl_exec($curl);
        curl_close($curl);
     
        return $res;
      }
    }
     
    $jssdk = new JSSDK($appid,$secret);
    $signPackage = $jssdk->GetSignPackage();
    ?>
    

    前台代码

    <!DOCTYPE html>
    <html>
    <head>
        <meta charset="utf-8">
        <title>微信js-sdk</title>
        <link rel="stylesheet" href="https://cdn.bootcss.com/bootstrap/3.3.7/css/bootstrap.min.css"> 
        <script src="https://cdn.bootcss.com/jquery/2.1.1/jquery.min.js"></script>
        <script src="https://cdn.bootcss.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
    </head>
    <body style="margin: 0 auto;text-align: center;font-size: 50px;">
        <p style="font-size: 100px;text-align: center;margin-top: 300px;"><span class="res"></span>米</p>
    </body>
    <script type="text/javascript" src="http://res.wx.qq.com/open/js/jweixin-1.4.0.js"></script>
    <script type="text/javascript">
        wx.config({
            debug: false, // 开启调试模式,调用的所有api的返回值会在客户端alert出来,若要查看传入的参数,可以在pc端打开,参数信息会通过log打出,仅在pc端时才会打印。
            appId: '<?php echo $signPackage["appId"];?>', // 必填,公众号的唯一标识
            timestamp: <?php echo $signPackage["timestamp"];?>, // 必填,生成签名的时间戳
            nonceStr: '<?php echo $signPackage["nonceStr"];?>', // 必填,生成签名的随机串
            signature: '<?php echo $signPackage["signature"];?>',// 必填,签名
            jsApiList: [
                'onMenuShareTimeline',
                'onMenuShareAppMessage',
                'onMenuShareQQ',
                'onMenuShareWeibo',
                'scanQRCode',
                'getLocation',
            ] // 必填,需要使用的JS接口列表
        });
        wx.ready(function(){
        // config信息验证后会执行ready方法,所有接口调用都必须在config接口获得结果之后,config是一个客户端的异步操作,所以如果需要在页面加载时就调用相关接口,则须把相关接口放在ready函数中调用来确保正确执行。对于用户触发时才调用的接口,则可以直接调用,不需要放在ready函数中。
            weiRegst();
        });
        wx.error(function(res){
        // config信息验证失败会执行error函数,如签名过期导致验证失败,具体错误信息可以打开config的debug模式查看,也可以在返回的res参数中查看,对于SPA可以在这里更新签名。
        });
        var weiShare={
            title:'标题',
            desc:'描述',
            imgUrl:'http://img.longhoo.net/web/20170420/20170420025343756001.jpg',
            link:'http://www.longhoo.net/index.html'
        }  
        //微信分享注册
        function weiRegst(){
            //分享到朋友圈
            wx.onMenuShareTimeline({
                title: weiShare.title,
                link: weiShare.link,
                imgUrl:weiShare.imgUrl,
                trigger: function (res) {
                    alert('用户点击分享到朋友圈1111');
                },
                success: function (res) {
                    // alert('已分享111111');
                    <?php file_put_contents("wx0420.txt", "已分享111111"); ?>
                },
                cancel: function (res) {
                    alert('已取消1111111');
                },
                fail: function (res) {
                    alert(JSON.stringify(res));
                }
            });
            //分享给朋友
            wx.onMenuShareAppMessage({
                title: weiShare.title,
                desc: weiShare.desc,
                link:  weiShare.link,
                imgUrl:weiShare.imgUrl,
                trigger: function (res) {
                    alert('用户点击分享到朋友圈2222');
                },
                success: function (res) {
                    // alert('已分享22222');
                    <?php file_put_contents("wx0420.txt", "已分享111111"); ?>
                },
                cancel: function (res) {
                    alert('已取消22222');
                },
                fail: function (res) {
                    alert(JSON.stringify(res));
                }
            });
            //分享到QQ
            wx.onMenuShareQQ({
                title: weiShare.title,
                desc: weiShare.desc,
                link:  weiShare.link,
                imgUrl:weiShare.imgUrl
     
            });
            //分享到微博
            wx.onMenuShareWeibo({
                title: weiShare.title,
                desc: weiShare.desc,
                link:  weiShare.link,
                imgUrl:weiShare.imgUrl
     
            });
            //调起微信扫一扫接口
            /*wx.scanQRCode({
                needResult: 0, // 默认为0,扫描结果由微信处理,1则直接返回扫描结果,
                scanType: ["qrCode","barCode"], // 可以指定扫二维码还是一维码,默认二者都有
                success: function (res) {
                var result = res.resultStr; // 当needResult 为 1 时,扫码返回的结果
                }
            });*/
            wx.getLocation({
                type: 'gcj02', // 默认为wgs84的gps坐标,如果要返回直接给openLocation用的火星坐标,可传入'gcj02'
                success: function (res) {
                    var latitude = res.latitude; // 纬度,浮点数,范围为90 ~ -90
                    var longitude = res.longitude; // 经度,浮点数,范围为180 ~ -180。
                    var speed = res.speed; // 速度,以米/每秒计
                    var accuracy = res.accuracy; // 位置精度
                    $.post('http://game1.longhoo.net/test.php',{lng2:latitude,lat2:longitude},function(res){
                        $(".res").html(res);
                    });
                     
                }
            });
        }
    </script>
    </html>
    

    相关文章

      网友评论

          本文标题:php微信分享

          本文链接:https://www.haomeiwen.com/subject/lclofrtx.html