微信公众平台开发—微信JS-SDK

作者: honehou | 来源:发表于2016-10-23 21:13 被阅读0次

    简介

    微信JS-SDK是微信公众平台面向网页开发者提供的基于微信内的网页开发工具包。简而言之,便是可以在第三方的网页上按照特定的规则来调用这些js接口,网页开发者可借助微信高效地使用拍照、选图、语音、位置等手机系统的能力,同时可以直接使用微信分享、扫一扫、卡券、支付等微信特有的能力。

    使用步骤

    • 绑定域名
      直接填写www.xxx.com之类的域名,不用加 http:// ,否则在后续的测试中可能会出现invalid url domain的问题。
    • 引入JS文件
    • 通过config接口注入权限验证配置
    • 通过ready接口处理成功验证
    • 通过error接口处理失败验证

    详情:微信JS-SDK说明文档

    接口说明(仅介绍本文用到的两个接口)

    • 获取“分享到朋友圈”按钮点击状态及自定义分享内容接口
    wx.onMenuShareTimeline({
        title: '', // 分享标题
        link: '', // 分享链接
        imgUrl: '', // 分享图标
        success: function () { 
            // 用户确认分享后执行的回调函数
        },
        cancel: function () { 
            // 用户取消分享后执行的回调函数
        }
    });
    
    • 获取“分享给朋友”按钮点击状态及自定义分享内容接口
    wx.onMenuShareAppMessage({
        title: '', // 分享标题
        desc: '', // 分享描述
        link: '', // 分享链接
        imgUrl: '', // 分享图标
        type: '', // 分享类型,music、video或link,不填默认为link
        dataUrl: '', // 如果type是music或video,则要提供数据链接,默认为空
        success: function () { 
            // 用户确认分享后执行的回调函数
        },
        cancel: function () { 
            // 用户取消分享后执行的回调函数
        }
    });
    
    • 注意
      需仔细阅读:JS-SDK使用权限签名算法
      本人在测试过程中出现invalid signature的错误,原因是签名用的url必须是调用JS接口页面的完整URL

    示例代码

    说明:使用的是thinkphp框架
    视图index.html:

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta name="viewport" content="initial-scale=1.0;width=device-width" />
        <meta http-equiv="content" content="text/html; charset=utf-8" />
        <title>微信公众平台开发JS-SDK</title>
        <script src="http://res.wx.qq.com/open/js/jweixin-1.0.0.js"></script>
        <!-- 引入微信提供的js文件 -->
    </head>
    <body>
        hello world!
        <script>
            wx.config({
                debug: true, // 开启调试模式,调用的所有api的返回值会在客户端alert出来,若要查看传入的参数,可以在pc端打开,参数信息会通过log打出,仅在pc端时才会打印。
                appId: '填写公众号的appid', // 必填,公众号的唯一标识
                //下面大括号内为视图渲染
                timestamp: '{$timestamp}', // 必填,生成签名的时间戳
                nonceStr: '{$nonceStr}', // 必填,生成签名的随机串
                signature: '{$signature}',// 必填,签名,见附录1
                jsApiList: [
                    'onMenuShareTimeline',
                    'onMenuShareAppMessage'
                ] // 必填,需要使用的JS接口列表,所有JS接口列表见附录2
            });
            wx.ready(function(){
                //分享到朋友圈
                wx.onMenuShareTimeline({
                    title: '分享到朋友圈', // 分享标题
                    link: 'https://www.baidu.com/', // 分享链接
                    imgUrl: 'https://ss0.bdstatic.com/5aV1bjqh_Q23odCf/static/superman/img/logo/bd_logo1_31bdc765.png', // 分享图标
                    success: function () { 
                        // 用户确认分享后执行的回调函数
                    },
                    cancel: function () { 
                        // 用户取消分享后执行的回调函数
                    }
                });
    
                //分享给朋友
                wx.onMenuShareAppMessage({
                    title: '分享给朋友', // 分享标题
                    desc: '开发 分享给朋友功能', // 分享描述
                    link: 'https://www.baidu.com/', // 分享链接
                    imgUrl: 'https://ss0.bdstatic.com/5aV1bjqh_Q23odCf/static/superman/img/logo/bd_logo1_31bdc765.png', // 分享图标
                    type: 'link', // 分享类型,music、video或link,不填默认为link
                    dataUrl: '', // 如果type是music或video,则要提供数据链接,默认为空
                    success: function () { 
                        // 用户确认分享后执行的回调函数
                    },
                    cancel: function () { 
                        // 用户取消分享后执行的回调函数
                    }
                });
            });
            wx.error(function(res){});
        </script>
    </body>
    </html>
    

    控制器的index方法:

    public function index(){
        // 获取jsapi_ticket票据
        $jsapi_ticket = getJsApiTicket();
        // 生成signature
        $nonceStr = randomString();
        $url = '调用JS接口页面的完整URL';
        $signature = "jsapi_ticket=".$jsapi_ticket."&noncestr=".$nonceStr."&timestamp=".$timestamp."&url=".$url;
        $signature = sha1($signature);
        $this->assign('timestamp',$timestamp);
        $this->assign('nonceStr',$nonceStr);
        $this->assign('signature',$signature);
        $this->display("index");
        
        // 获取jsapi_ticket,它是公众号用于调用微信JS接口的临时票据
        function getJsApiTicket(){
            $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=公众号的appid&secret=公众号的secret";
            $res = (array)json_decode(httpRequest($url,'get'));
            $access_token = $res['access_token'];
            $url = 'https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token='.$access_token.'&type=jsapi';
            $res = (array)json_decode(httpRequest($url,'get'));
            $jsapi_ticket = $res['ticket'];
            return $jsapi_ticket;
        }
    
        //生成指定长度的随机串
        function randomString(){
            srand(microtime()*10000000);
            $possible="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890";
            $str="";
            $len = 16;
            while(strlen($str)<$len) {
                $str.=substr($possible,(rand()%(strlen($possible))),1);
            }
            return $str;
        }
    
        //使用curl进行请求,$method='get'or'post'
        function httpRequest($url, $method='get', $data='undefined'){
            $ch = curl_init();
            curl_setopt($ch, CURLOPT_URL, $url);
            if ($method == 'get'){
                curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
                curl_setopt($ch, CURLOPT_HEADER, 0);
                curl_setopt($ch, CURLOPT_USERAGENT, "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.22 (KHTML, like Gecko) Chrome/25.0.1364.172 Safari/537.22");
                curl_setopt($ch, CURLOPT_ENCODING ,'gzip'); //加入gzip解析
                curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);    // https请求 不验证证书和hosts
                curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
            }           
            if ($method == 'post'){
                curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
                curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
                curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
                curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (compatible; MSIE 5.01; Windows NT 5.0)');
                curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
                curl_setopt($ch, CURLOPT_AUTOREFERER, 1);
                curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
                curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
                if (curl_errno($ch)) {
                    return curl_error($ch);
                }
            }   
            $output = curl_exec($ch);       
            curl_close($ch);
            return $output;
        }
    }
    

    参考教程:
    PHP微信公众平台开发高级篇—微信JS-SDK
    微信JS-SDK说明文档

    相关文章

      网友评论

        本文标题:微信公众平台开发—微信JS-SDK

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