微信公众号配置:js接口安全域名、ip白名单

需要appid \appsecrete

不管是ccess_token还是jsapi_ticket,都有一个存活期,大约是7200秒,在存活期内,最好不好重复获取,因为会造成混乱。可以用数据库或者文件把获取的ccess_token、jsapi_ticket保存下来,然后代码规定在7200秒的某个时间内重新获取,以免ccess_token、jsapi_ticket过期,获取的时间最好是存活期结束前的5分钟,也是6900秒左右。

use think\Db; use think\Config;

//微信分享需要信息

public static function getwechatshareinfo() { $config = Service::getConfig('wechat'); $appid = $config['app_id']; $secret = $config['app_secret']; $signPackage=self::getSignPackage($appid,$secret); $a=array('sha_str'=>$signPackage["signature"],'nonceStr'=>$signPackage["nonceStr"],'timestamp'=>$signPackage["timestamp"],'appid'=>$appid,'secret'=>$secret); return $a; } static function getSignPackage($appid,$secret) { $jsapiTicket = self::getJsApiTicket($appid,$secret); $url = "http://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]"; $timestamp = time(); $nonceStr = self::createNonceStr(); // 这里参数的顺序要按照 key 值 ASCII 码升序排序 $string = "jsapi_ticket=$jsapiTicket&noncestr=$nonceStr&timestamp=$timestamp&url=$url"; $signature = sha1($string); $signPackage = array( "nonceStr" => $nonceStr, "timestamp" => $timestamp, "url" => $url, "signature" => $signature, "rawString" => $string ); return $signPackage; } static function getJsApiTicket($appid,$secret) { // jsapi_ticket 应该全局存储与更新,以下代码以写入到文件中做示例 $data = Db::table('fa_wechat_ticket') ->where('id', 1) ->select(); if ($data[0]['time'] < time()) { $accessToken = self::getAccessToken($appid,$secret); $url = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?type=jsapi&access_token=$accessToken"; $res = json_decode(self::httpGet($url)); $ticket = $res->ticket; if ($ticket) { $data = array( 'time' =>time() + 7000, 'ticket' =>$ticket ); Db::table('fa_wechat_ticket')->where('id',1)->update($data); } } else { $ticket = $data[0]['ticket']; } return $ticket; } static function getAccessToken($appid,$secret) { // access_token 应该全局存储与更新,以下代码以写入到文件中做示例 $data = Db::table('fa_wechat_token') ->where('id', 1) ->select(); if ($data[0]['time'] < time()) { $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=$appid&secret=$secret"; $res = json_decode(self::httpGet($url)); $access_token = $res->access_token; if ($access_token) { $data = array( 'time' =>time() + 7000, 'token' =>$access_token ); Db::table('fa_wechat_token')->where('id',1)->update($data); } } else { $access_token = $data[0]['token']; } return $access_token; } static function httpGet($url) { $curl = curl_init(); curl_setopt($curl, CURLOPT_RETURNTRANSFER, true); curl_setopt($curl, CURLOPT_TIMEOUT, 500); curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false); curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false); curl_setopt($curl, CURLOPT_URL, $url); $res = curl_exec($curl); curl_close($curl); return $res; } //创建字符 static 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; } //微信分享需要信息     public static function getwechatshareinfo()     {         $config = Service::getConfig('wechat');         $appid = $config['app_id'];         $secret = $config['app_secret'];         $signPackage=self::getSignPackage($appid,$secret);                          $a=array('sha_str'=>$signPackage["signature"],'nonceStr'=>$signPackage["nonceStr"],'timestamp'=>$signPackage["timestamp"],'appid'=>$appid,'secret'=>$secret);         return $a;     }               static function getSignPackage($appid,$secret) {         $jsapiTicket = self::getJsApiTicket($appid,$secret);         $url = "http://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";         $timestamp = time();         $nonceStr = self::createNonceStr();         // 这里参数的顺序要按照 key 值 ASCII 码升序排序         $string = "jsapi_ticket=$jsapiTicket&noncestr=$nonceStr&timestamp=$timestamp&url=$url";         $signature = sha1($string);         $signPackage = array(             "nonceStr"  => $nonceStr,             "timestamp" => $timestamp,             "url"       => $url,             "signature" => $signature,             "rawString" => $string         );         return $signPackage;      }          static function getJsApiTicket($appid,$secret) {         // jsapi_ticket 应该全局存储与更新,以下代码以写入到文件中做示例         $data = Db::table('fa_wechat_ticket')             ->where('id', 1)             ->select();         if ($data[0]['time'] < time()) {             $accessToken = self::getAccessToken($appid,$secret);             $url = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?type=jsapi&access_token=$accessToken";             $res = json_decode(self::httpGet($url));             $ticket = $res->ticket;             if ($ticket) {                 $data = array(                     'time'    =>time() + 7000,                     'ticket'  =>$ticket                 );                 Db::table('fa_wechat_ticket')->where('id',1)->update($data);             }         } else {             $ticket = $data[0]['ticket'];         }         return $ticket;     }         static function getAccessToken($appid,$secret) {       // access_token 应该全局存储与更新,以下代码以写入到文件中做示例       $data = Db::table('fa_wechat_token')             ->where('id', 1)             ->select();         if ($data[0]['time'] < time()) {             $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=$appid&secret=$secret";             $res = json_decode(self::httpGet($url));             $access_token = $res->access_token;         if ($access_token) {             $data = array(                 'time' =>time() + 7000,                 'token' =>$access_token             );             Db::table('fa_wechat_token')->where('id',1)->update($data);         }       } else {         $access_token = $data[0]['token'];       }       return $access_token;     }          static function httpGet($url) {         $curl = curl_init();         curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);         curl_setopt($curl, CURLOPT_TIMEOUT, 500);         curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);         curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);         curl_setopt($curl, CURLOPT_URL, $url);         $res = curl_exec($curl);         curl_close($curl);         return $res;     }          //创建字符     static 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;     }

提示wx not define的话:
<script type="text/javascript">
    define = null;
    require = null;

</script> 

或者会影响部分功能把下面的代码提前,写在body标签下 

<script src="https://res.wx.qq.com/open/js/jweixin-1.4.0.js"></script>

<script>
          /*
           * 注意:
           * 1. 所有的JS接口只能在公众号绑定的域名下调用,公众号开发者需要先登录微信公众平台进入“公众号设置”的“功能设置”里填写“JS接口安全域名”。
           * 2. 如果发现在 Android 不能分享自定义内容,请到官网下载最新的包覆盖安装,Android 自定义分享接口需升级至 6.0.2.58 版本及以上。
           * 3. 常见问题及完整 JS-SDK 文档地址:http://mp.weixin.qq.com/wiki/7/aaa137b55fb2e0456bf8dd9148dd613f.html
           *
           * 开发中遇到问题详见文档“附录5-常见错误及解决办法”解决,如仍未能解决可通过以下渠道反馈:
           * 邮箱地址:weixin-open@qq.com
           * 邮件主题:【微信JS-SDK反馈】具体问题
           * 邮件内容说明:用简明的语言描述问题所在,并交代清楚遇到该问题的场景,可附上截屏图片,微信团队会尽快处理你的反馈。
           */
        
          var url=window.location.href.split('#')[0];
        console.log(url);
          wx.config({
            debug: false,
            appId: '{$app_id}',
            timestamp: '{$timestamp}',
            nonceStr: '{$nonceStr}',
            signature: '{$sha_str}',   
            url:url,
            jsApiList: [
             'updateAppMessageShareData',
              'updateTimelineShareData',
             
            ]
          });
        
        
          wx.checkJsApi({
          jsApiList: ['updateAppMessageShareData'], // 需要检测的JS接口列表,所有JS接口列表见附录2,
          success: function(res) {
          // 以键值对的形式返回,可用的api值true,不可用为false
          // 如:{"checkResult":{"chooseImage":true},"errMsg":"checkJsApi:ok"}
          //alert('right');
          }
        });
        var imgurl=window.location.protocol + '//' + window.location.hostname+'{$site.syfxtp}';
       /* $(document).ready(function() {
        $('.post img').each(function() {
            var maxWidth = 100; // 图片最大宽度
            var maxHeight = 100; // 图片最大高度
            var ratio = 0; // 缩放比例
            var width = $(this).width(); // 图片实际宽度
            var height = $(this).height(); // 图片实际高度
         
            // 检查图片是否超宽
            if(width > maxWidth){
                ratio = maxWidth / width; // 计算缩放比例
                $(this).css("width", maxWidth); // 设定实际显示宽度
                height = height * ratio; // 计算等比例缩放后的高度
                $(this).css("height", height * ratio); // 设定等比例缩放后的高度
            }
         
            // 检查图片是否超高
            if(height > maxHeight){
                ratio = maxHeight / height; // 计算缩放比例
                $(this).css("height", maxHeight); // 设定实际显示高度
                width = width * ratio; // 计算等比例缩放后的高度
                $(this).css("width", width * ratio); // 设定等比例缩放后的高度
            }
        });
        });*/
        console.log(imgurl);
        wx.ready(function () {
        //自定义“分享给朋友”及“分享到QQ”按钮的分享内容(1.4.0)
        wx.updateAppMessageShareData({ 
            title: '{$site.syfxtit}', // 分享标题
            desc: '{$site.syfxms}', // 分享描述
            link: url, // 分享链接,该链接域名或路径必须与当前页面对应的公众号JS安全域名一致
            imgUrl: imgurl, // 分享图标
            success: function (res) {
              // 设置成功
              showTip('朋友分享成功');
            }
          });
            wx.updateTimelineShareData({ 
                title: '{$site.syfxtit}', // 分享标题
                link: url, // 分享链接,该链接域名或路径必须与当前页面对应的公众号JS安全域名一致
                imgUrl:  imgurl, // 分享图标
                success: function (res) {
                  // 设置成
                  showTip('朋友分享成功');
                }
            });
        });
          
          </script>


点赞(0) 打赏

评论列表 共有 0 条评论

暂无评论
返回
顶部