Home  >  Article  >  Web Front-end  >  Summarize and share some notes on WeChat JS SDK access

Summarize and share some notes on WeChat JS SDK access

零下一度
零下一度Original
2017-06-23 10:19:191058browse

To access WeChat JS SDK, you can first refer to the official website documentation. To sum up, there are several steps:

1. Bind domain name:
First log in to the WeChat public platform and enter "Official Account Settings" Fill in the "JS interface security domain name" in the "Function Settings".
Note: After logging in, you can view the corresponding interface permissions in the "Developer Center".

2. Introduce JS files: Introduce the following JS files in the page that needs to call the JS interface, (supports https):,
Note: Supports loading using the AMD/CMD standard module loading method, here is the additional introduction of jquery .cookie.js, sha1.js, you need to use

3 later. Get the access_token, and then get the jsapi_ticket. Since the function to get the jsapi_ticket cannot be called frequently, you can save a global jsapi_ticket and store it in the cookie. If Get it again when it is out of date; in addition, it is recommended to put these two acquisition operations on the server to ensure security;

4. Splice noncestr (random string), valid jsapi_ticket, timestamp (timestamp), url ( The URL of the current web page (excluding # and its following parts), after sorting all the parameters to be signed according to the ASCII code of the field name from small to large (lexicographic order), use the format of URL key-value pairs (i.e. key1=value1&key2=value2… ) are concatenated into a string string1. It should be noted here that all parameter names are lowercase characters.

5.sha1 encryption generates signature signature;

6. Configure wx.config, wx.ready, wx.error and other methods, among which wx.ready is the callback after successful configuration, other suggestions are recommended Methods such as WeChat sharing wx.onMenuShareTimeline, wx.onMenuShareAppMessage, etc. are all placed in ready to achieve the purpose of synchronous execution;

Server interface:

//access_token是公众号的全局唯一票据
    public function getTokenForJS() {
        $appid = "不告诉你";
        $secret = "不告诉你";
        $url = "https://api.weixin.qq.com/cgi-bin/token?appid=".$appid."&secret=".$secret."&grant_type=client_credential";
        $result = http_request($url);
        echo $result;exit;
    }
    
    //获取ticket
    public function getTicket(){
        $access_token = I("get.access_token");
        $url = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=".$access_token."&type=jsapi";
        //$this->ajaxJSON($url);
        $result = http_request($url);
        echo $result;exit;
    }
    
    function http_request($url, $data = null)
    {
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
        if (!empty($data)) {
            curl_setopt($curl, CURLOPT_POST, 1);
            curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
        }
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        $info = curl_exec($curl);
        curl_close($curl);
        return $info;
    }

Front-end js:

function setWechatJS() {
    // var temp = "jsapi_ticket=kgt8ON7yVITDhtdwci0qeRukvrGB1QLAfzCcybh4a_VMg6rgB4OhdsD4O2ruRI0OUPG5VfpKlYYWXcyEeChbBw&noncestr=4df32E3jY6YneEPNfGfs&timestamp=1498120656&url=";
    // alert( hex_sha1(temp)); return false;
    //生成随机字符串
    var randomString = function(len) {
        len = len || 32;
        var $chars = 'ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz2345678';    /****默认去掉了容易混淆的字符oOLl,9gq,Vv,Uu,I1****/
        var maxPos = $chars.length;
        var pwd = '';
        for (var i = 0; i < len; i++) {
            pwd += $chars.charAt(Math.floor(Math.random() * maxPos));
        }
        return pwd;
    };

    var showShareSetting = function () {
        console.log("title="+title+",description="+description+",link="+url+",imgUrl="+imgUrl);
    };

    //wx配置参数
    var jsapi_ticket = $.cookie(&#39;jsapi_ticket&#39;);
    var hello2 = &#39;hello222&#39;;
    console.log("jsapi_ticket="+jsapi_ticket);

    var wxConfig = function () {
        //alert(&#39;ddd=&#39;+jsapi_ticket);
        //获取当前url,不含#以及之后的部分
        var timestamp = new Date().getTime();  //生成签名的时间戳(当前时间)
        var noncestr = randomString(20);
        var signature = &#39;&#39;;       //签名
        var url = window.location.href;
        var index = url.indexOf(&#39;#&#39;);
        if(index !== -1 ) {
            url = url.slice(0,index);
        }
        var temp = "jsapi_ticket="+jsapi_ticket+"&noncestr="+noncestr+"&timestamp="+timestamp+"&url="+url;
        signature = hex_sha1(temp);
        console.log("signature="+signature);
        wx.config({
            debug: false, // 开启调试模式,调用的所有api的返回值会在客户端alert出来,若要查看传入的参数,可以在pc端打开,参数信息会通过log打出,仅在pc端时才会打印。
            appId: &#39;wx0875a197e0e5bcd7&#39;, // 必填,公众号的唯一标识
            timestamp: timestamp, // 必填,生成签名的时间戳
            nonceStr: noncestr, // 必填,生成签名的随机串
            signature: signature,// 必填,签名,见附录1
            jsApiList: [
                &#39;checkJsApi&#39;,
                &#39;onMenuShareTimeline&#39;,
                &#39;onMenuShareAppMessage&#39;,
                &#39;onMenuShareQQ&#39;,
                &#39;onMenuShareWeibo&#39;,
                &#39;onMenuShareQZone&#39;
            ] // 必填,需要使用的JS接口列表,所有JS接口列表见附录2
        });

        wx.ready(function () {
            //配置成功之后回调
            console.log("微信JS SDK配置成功!");
            //实例化title\imgUrl
            title = $(&#39;title&#39;).html();   //默认取title
            description = $("meta[name=&#39;description&#39;]").attr(&#39;content&#39;);
            //判断当前页面类型取缩略图
            $("body img").each(function(index,element){
                var width = $(element).width();
                var height = $(element).height();
                var Src = $(element).attr("src");
                if(width>200 && height>200){//去页面中第一张宽高都大于200的图片
                    imgUrl = Src;
                    //console.log(Src);
                    return false;
                }else{//未在页面中取到合适的图片就选取银河的logo图
                    imgUrl = MyPic+"/H5/img/icon.png";
                }
            });
            showShareSetting();
            //分享到朋友圈
            wx.onMenuShareTimeline({
                title: title, // 分享标题
                link: url, // 分享链接,该链接域名或路径必须与当前页面对应的公众号JS安全域名一致
                imgUrl: imgUrl, // 分享图标
                success: function () {
                    // 用户确认分享后执行的回调函数
                    showShareSetting();
                },
                cancel: function () {
                    // 用户取消分享后执行的回调函数
                }
            });
            //分享给朋友
            wx.onMenuShareAppMessage({
                title: title, // 分享标题
                desc: description, // 分享描述
                link: url, // 分享链接,该链接域名或路径必须与当前页面对应的公众号JS安全域名一致
                imgUrl: imgUrl, // 分享图标
                type: '', // 分享类型,music、video或link,不填默认为link
                dataUrl: '', // 如果type是music或video,则要提供数据链接,默认为空
                success: function () {
                    // 用户确认分享后执行的回调函数
                    showShareSetting();
                },
                cancel: function () {
                    // 用户取消分享后执行的回调函数
                }
            });
            //分享到QQ
            wx.onMenuShareQQ({
                title: title, // 分享标题
                desc: description, // 分享描述
                link: url, // 分享链接
                imgUrl: imgUrl, // 分享图标
                success: function () {
                    // 用户确认分享后执行的回调函数
                    showShareSetting();
                },
                cancel: function () {
                    // 用户取消分享后执行的回调函数
                }
            });

            //分享到QQ空间
            wx.onMenuShareQZone({
                title: title, // 分享标题
                desc: description, // 分享描述
                link: url, // 分享链接
                imgUrl: imgUrl, // 分享图标
                success: function () {
                    // 用户确认分享后执行的回调函数
                    showShareSetting();
                },
                cancel: function () {
                    // 用户取消分享后执行的回调函数
                }
            });
        });
        wx.error(function(res){
            console.log("微信JS SDK配置错误!");
            // config信息验证失败会执行error函数,如签名过期导致验证失败,具体错误信息可以打开config的debug模式查看,也可以在返回的res参数中查看,对于SPA可以在这里更新签名。
        });
    };

    //待分享生成的标题、链接、缩略图
    var title,url,imgUrl,description;
    //本地cookie查找不到缓存再去请求网络
    if(typeof (jsapi_ticket) == 'undefined' || jsapi_ticket == ''){
        //alert('aaa='+jsapi_ticket);
        //以下步骤分别获取全局access_token、jsapi_ticket、signature
        $.get(MyUrl+"getTokenForJS",function (data) {
            var access_token = data['access_token'];
            //获取全局access_token,以及7200秒之后刷新的问题
            //先出cookie中取,如果没有,
            $.get(MyUrl+"getTicket?access_token="+access_token,function(data){
                jsapi_ticket = data['ticket'];
                //保存当前jsapi_ticket
                var date = new Date();
                date.setTime(date.getTime()+7200*1000);//只能这么写,10表示10秒钟
                //?替换成分钟数如果为60分钟则为 60 * 60 *1000
                $.cookie('jsapi_ticket',jsapi_ticket,{expires:date,path:'/'}); //有效期7200秒
                console.log("jsapi_ticket="+jsapi_ticket);
                //alert('ccc='+jsapi_ticket);
                wxConfig();
            },'json');

        },'json');
    }else {
        //alert('bbb='+jsapi_ticket);
        wxConfig();
    }
}

The above is the detailed content of Summarize and share some notes on WeChat JS SDK access. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Previous article:Summary on var usageNext article:Summary on var usage