微信JS-SDK自定义分享接入的注意点

微信文档 ,https://developers.weixin.qq.com/doc/offiaccount/OA_Web_Apps/JS-SDK.html,php

在用微信自定义分享,遇到了几个坑,记录一下。html

注意点1:进入“公众号设置”的“功能设置”里填写“JS接口安全域名”。注意公众号须要认证,不然可能提示使用接口 没有权限;

注意点2:access_token是公众号的全局惟一接口调用凭据,有效时间2小时,注意缓存,不能每次都获取新的,次数一天2000次,能够缓存,或者存入数据表,用时判断当前时间和存入的时间差。实在超过,可在微信后台 接口权限中清空次数,一个月只能清3次android

其中的jsapi_ticket也是,缓存或者存表。web

注意点3: 签名的注意事项ajax

 

 

 

 注意点4:签名时的url, 在pc的微信中,url没有拼接什么,而在手机的微信中,会在你当前页面上自动拼接上朋友圈 from=timeline,微信群 from=groupmessage,好友分享 from=singlemessage,签名时要注意,不要漏掉,能够在前台ajax请求时,或者当前页面的url,传入后台签名。json

注意点5:windows

 

 

在手机微信中这些接口确实已经废弃,用了,就会提示不支持,而在pc微信中,仍是用这些,不能用新的api

因为pc和手机使用的方法不一样,在php中定义了两套,用手机打开时访问一套,pc打开时访问一套,或者弄访问地址彻底不同的页面,pc一个地址,手机一个地址数组

下面是php中的定义,手机和pc虽然是同一个网址,可是真正访问的仍是两套缓存

function is_mobile(){
    $user_agent = $_SERVER['HTTP_USER_AGENT'];

    $mobile_agents = Array("240x320","acer","acoon","acs-","abacho","ahong","airness","alcatel","amoi","android","anywhereyougo.com","applewebkit/525","applewebkit/532","asus","audio","au-mic","avantogo","becker","benq","bilbo","bird","blackberry","blazer","bleu","cdm-","compal","coolpad","danger","dbtel","dopod","elaine","eric","etouch","fly ","fly_","fly-","go.web","goodaccess","gradiente","grundig","haier","hedy","hitachi","htc","huawei","hutchison","inno","ipad","ipaq","ipod","jbrowser","kddi","kgt","kwc","lenovo","lg ","lg2","lg3","lg4","lg5","lg7","lg8","lg9","lg-","lge-","lge9","longcos","maemo","mercator","meridian","micromax","midp","mini","mitsu","mmm","mmp","mobi","mot-","moto","nec-","netfront","newgen","nexian","nf-browser","nintendo","nitro","nokia","nook","novarra","obigo","palm","panasonic","pantech","philips","phone","pg-","playstation","pocket","pt-","qc-","qtek","rover","sagem","sama","samu","sanyo","samsung","sch-","scooter","sec-","sendo","sgh-","sharp","siemens","sie-","softbank","sony","spice","sprint","spv","symbian","tablet","talkabout","tcl-","teleca","telit","tianyu","tim-","toshiba","tsm","up.browser","utec","utstar","verykool","virgin","vk-","voda","voxtel","vx","wap","wellco","wig browser","wii","windows ce","wireless","xda","xde","zte");
    $is_mobile = false;
    foreach ($mobile_agents as $device) {//这里把值遍历一遍,用于查找是否有上述字符串出现过
        if (stristr($user_agent, $device)) { //stristr 查找访客端信息是否在上述数组中,不存在即为PC端。
            $is_mobile = true;
            break;
        }
    }
    return $is_mobile;
}

if(is_mobile()){ //跳转至wap分组
    define('BIND_MODULE','Mobile');
}else{
    define('BIND_MODULE','Home');
}

 

判断access_token 过时,我这只是2000秒,远远不到7200秒(2小时),

time字段设置为了默认值当前时间
  $access_time = M("dc_weixin")->order("id desc")->getField("time");
        $time = time() - strtotime($access_time);
        if($time>2000){
            $url="https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=".$this->app_id."&secret=".$this->app_secret;
            $content = file_get_contents($url);
            $result = json_decode($content);
            $data['access_token'] = $result->access_token;
            $weixin = M("dc_weixin")->data($data)->add();
        }

  //jsapi_ticket

  public function getJk(){
        $this->getToken();
        $access_token =  M("dc_weixin")->order("id desc")->getField("access_token");

        $jk_time = M("dc_jk")->order("id desc")->getField("time");
        $time = time() - strtotime($jk_time);
        if($time>2000){
            $url = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=".$access_token."&type=jsapi";
            $content = file_get_contents($url);
            $result = json_decode($content);
            $data['jk'] = $result->ticket;
            $weixin = M("dc_jk")->data($data)->add();
        }

    }

 

 /*
     * 随机字符串
     */
    function create_guid() {
        $charid = strtoupper(md5(uniqid(mt_rand(), true)));
        $hyphen = chr(45);// "-"
        $uuid =
            substr($charid, 0, 8).$hyphen
            .substr($charid, 8, 4).$hyphen
            .substr($charid,12, 4).$hyphen;
        return str_replace("-","",$uuid);
    }

 

 //签名   页面里ajax访问,签名的方法

 public function dcsign_mob(){
$html = $_SERVER['HTTP_REFERER']; $time = strtotime(date('Y-m-d H:i:s',time())); $nostr = $this->create_guid(); $jk= M("dc_jk")->order("id desc")->getField("jk"); $url = "jsapi_ticket=".$jk."&noncestr=".$nostr."&timestamp=".$time."&url=".$html; $signature = sha1($url); $data['html'] = $html; $data['time'] = $time; $data['nostr'] = $nostr; $data['signature'] = $signature; $this->ajaxReturn($data); //返回到html也中 }
 $.ajax({
            url: "{:U('**/**')}",
            type: "get",              //data:{} //这里没有将页面的url传入签名方法中,
            timeout: 20000, //超时时间设置,单位毫秒
            success: function (data) {

                console.log(data);

                wx.config({
                    debug: true, // 开启调试模式,调用的全部api的返回值会在客户端alert出来,若要查看传入的参数,能够在pc端打开,参数信息会经过log打出,仅在pc端时才会打印。
                    appId: '*****', // 必填,公众号的惟一标识
                    timestamp: data.time, // 必填,生成签名的时间戳
                    nonceStr: data.nostr, // 必填,生成签名的随机串
                    signature: data.signature,// 必填,签名
                    jsApiList: [ 'checkJsApi',
                        'onMenuShareTimeline','onMenuShareAppMessage','updateAppMessageShareData','updateTimelineShareData'] // 必填,须要使用的JS接口列表
                });

                wx.ready(function() {


                    wx.updateAppMessageShareData({
                        title: shareTitle, // 分享标题
                        desc: descContent, // 分享描述
                        link: lineLink, // 分享连接,该连接域名或路径必须与当前页面对应的公众号JS安全域名一致
                        imgUrl: imgUrl, // 分享图标
                        success: function () {
                            // 用户确认分享后执行的回调函数
                        },
                        cancel: function () {
                            // 用户取消分享后执行的回调函数
                        }
                    });
                    wx.updateTimelineShareData({
                        title: shareTitle, // 分享标题
                        desc: descContent, // 分享描述
                        link: lineLink, // 分享连接,该连接域名或路径必须与当前页面对应的公众号JS安全域名一致
                        imgUrl: imgUrl, // 分享图标
                        success: function () {
                            // 用户确认分享后执行的回调函数
                        },
                        cancel: function () {
                            // 用户取消分享后执行的回调函数
                        }
                    });

                });


            },
            error: function (xhr, textStatus, errorThrown) {
                /*错误信息处理*/
                alert("进入error---");
                alert("状态码:"+xhr.status);
                alert("状态:"+xhr.readyState);//当前状态,0-未初始化,1-正在载入,2-已经载入,3-数据进行交互,4-完成。
                alert("错误信息:"+xhr.statusText );
                alert("返回响应信息:"+xhr.responseText );//这里是详细的信息
                alert("请求状态:"+textStatus);
                alert(errorThrown);
                alert("请求失败");
            },
            complete: function (XMLHttpRequest, status) {
                if (status == 'timeout') {
                    layer.msg("请求超时,请稍后再试!");
                    layer.close(index);
                }
            }
        });
相关文章
相关标签/搜索