微信js-sdk使用简述

1. 微信JS-SDK是微信公众平台 面向网页开发者提供的基于微信内的网页开发工具包。 

https://developers.weixin.qq.com/doc/offiaccount/OA_Web_Apps/JS-SDK.html#0

使用:

一,先登陆微信公众号后台绑定js安全域名,不需要加http或https,详情百度。

二、信公众号后台设置服务器的IP为白名单,否则无法获取access_token,详情百度

三、引入wx-js-sdk

1.使用script标签 http://res.wx.qq.com/open/js/...(支持https)引入;

2.如果使用vue-cli脚手架工具,可以先npm install weixin-js-sdk -s 加载依赖包 以下已脚手架为例

.vue 文件中 import wx from 'weixin-js-sdk';

Ps: timestamp,nonceStr,signature从后端获取。jsApiList整个是允许的js接口,想写一个,这里必须先注册。

//微信分享sdk配置
getConfig() {

    let that = this;
    let qs = require('qs');
    let postInfo = {
        url: window.location.href //获取当前路径
    }
    let posturl = this.common.HTTPHOST + '/api/wx/shareWx';

    axios.post(posturl, qs.stringify(postInfo), {
        headers: { 'Content-Type': 'application/x-www-form-urlencoded' }
    }).then(res => {
        let resData = res.data;
        let that = this;
        if (resData.ret == 1) {
            /*
            *noncestr: "eQhBNUudbCQxwJmQ"
            *signature: "28533352b0d4e55efda7ecccf8bbbf20b318fd5d"
            *timestamp: 1579070054
            */
            //1.配置js-sdk接口
            wx.config({
                debug: false, // 开启调试模式,调用的所有api的返回值会在客户端alert出来,若要查看传入的参数,可以在pc端打开,参数信息会通过log打出,仅在pc端时才会打印。
                appId: "wxe215942b3e49b9e1", // 必填,公众号的唯一标识
                timestamp: resData.data.timestamp, // 必填,生成签名的时间戳
                nonceStr: resData.data.noncestr, // 必填,生成签名的随机串
                signature: resData.data.signature, // 必填,签名
                jsApiList: [
                    "updateAppMessageShareData", //分享给朋友
                    "updateTimelineShareData" //分享给朋友圈
                ] // 必填,需要使用的JS接口表列
            });

            wx.ready(function () {
                // config信息验证后会执行ready方法,所有接口调用都必须在config接口获得结果之后,config是一个客户端的异步操作,所以如果需要在页面加载时就调用相关接口,则须把相关接口放在ready函数中调用来确保正确执行。对于用户触发时才调用的接口,则可以直接调用,不需要放在ready函数中。

                let imgUrl = !that.$store.state.wxShareImgUrl ? (that.common.HOSTURL + '/images/dadi.png') : that.$store.state.wxShareImgUrl;
                //分享给朋友 新版本
                wx.updateAppMessageShareData({
                    title: !that.$store.state.wxShareTitle ? that.common.getLocalStorage('xiangName') : that.$store.state.wxShareTitle, // 分享标题
                    desc: !that.$store.state.wxShareDescription ? ("专注" + that.common.getLocalStorage('xiangName') + "资讯和百姓生活服务") : that.$store.state.wxShareDescription, // 分享描述
                    link: window.location.href, // 分享链接,该链接域名或路径必须与当前页面对应的公众号JS安全域名一致
                    imgUrl: imgUrl, // 分享图标
                    success: function () {
                        // 设置成功
                        // alert("分享成功");
                    }
                });

                //分享给朋友圈
                wx.updateTimelineShareData({
                    title: !that.$store.state.wxShareTitle ? that.common.getLocalStorage('xiangName') : that.$store.state.wxShareTitle,
                    link: window.location.href,
                    imgUrl: imgUrl,
                    success: function () {
                        // alert("分享成功");
                    },
                    cancel: function () {
                    }
                });

            });

            wx.error(function (res) {
                // config信息验证失败会执行error函数,如签名过期导致验证失败,具体错误信息可以打开config的debug模式查看,也可以在返回的res参数中查看,对于SPA可以在这里更新签名。
            });



        }
    }).catch(err => {
        console.log(err);
    })


}

后端tp5接口

//微信网页版js分享所需参数
public function shareWx()
{
    /*
    * post.url
    */
    if (Request::instance()->isPost()) {
        //1.获取jsapi_ticket票据
        $jsapi_ticket = $this->getJsApiTicket();
        $timestamp    = time();
        $url          = input('post.url'); //先写死,可以获取到当前的url

        //2.获取16位随机码
        $noncestr = $this->getRandCode();
        //3.获取signature签名算法
        $signature = "jsapi_ticket=" . $jsapi_ticket . "&noncestr=" . $noncestr . "&timestamp=" . $timestamp . "&url=" . $url;
        $signature = sha1($signature);

        show(1, '获取完成', array(
            'timestamp' => $timestamp,
            'noncestr'  => $noncestr,
            'signature' => $signature
        ));
    }


}

//微信网页版获取jsapi_ticket全局票据
protected function getJsApiTicket()
{
    //如果缓存中保存有效的 jsapi_ticket
    if (session('jsapi_ticket_expire_time') > time() && session('jsapi_ticket')) {
        $jsapi_ticket = session('jsapi_ticket');
    } else {
        $access_token = $this->getWxAccessToken();
        $url          = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=" . $access_token . "&type=jsapi";
        $res          = $this->http_curl($url);
        $jsapi_ticket = $res['ticket'];
        //加入缓存
        session('jsapi_ticket', $jsapi_ticket);
        session('jsapi_ticket_expire_time', time() + 7000);
    }

    return $jsapi_ticket;

}

//微信网页版js获得随机码 16位
public function getRandCode($num = 16)
{

    $array  = array(
        'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9'
    );
    $tmpstr = '';
    $max    = count($array);

    for ($i = 1; $i <= $num; $i++) {
        $key    = rand(1, $max - 1);  // 'A' => $array[0]
        $tmpstr .= $array[$key];
    }
    return $tmpstr;
}

// 获取全局accesstoken
public function getWxAccessToken()
{
    //1. 请求url地址
    $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" . $this->appid . "&secret=" . $this->appsecret;
    //2. 获取token
    $res = $this->http_curl($url);
    return $res['access_token'];
}
发布了88 篇原创文章 · 获赞 6 · 访问量 3万+

猜你喜欢

转载自blog.csdn.net/codipy/article/details/103995948