详解vue开发中调用微信jssdk的问题

2022-10-20,,,,

起因

微信分享网址时无法分享图片,这个问题需要用jssdk去解决。其实开始的时候时可以看到图片的,但后来微信禁止了。所以只能使用jssdk去解决。
普通网页开发很简单,但是使用vue或其他前端框架开发spa单页面webapp的时候就会有问题了。只要url发生变化就会报签名错误。其实微信官方上已经写了说明。

所有需要使用js-sdk的页面必须先注入配置信息,否则将无法调用(同一个url仅需调用一次,对于变化url的spa的web app可在每次url变化时进行调用,目前android微信客户端不支持pushstate的h5新特性,所以使用pushstate来实现web app的页面会导致签名失败,此问题会在android6.2中修复)。
但这些说明然并卵(然而并没有什么卵用)。

问题根源

1 同一个url仅需调用一次,对于变化url的spa的web app可在每次url变化时进行调用
如果你的链接时采用hash方式,锚点变了也要重新调用,因为url发生了变化,这一点可以放在router的监听事件中比如watch一下$route,或者使用2.2 中引入的 beforerouteupdate 守卫。

2 生成签名时url中不能包含锚点
微信jssdk的签名是需要服务端来生成的,所以我们需要将当前页面的网址传递给服务端,由服务端生成wx.config初始化所需要的参数。
但是url传递的时候需要注意,一定一定一定不能带有锚点链接。可以使用location.href.split(‘#')[0]获取url中锚点之前的部分。
比如你的网址是
你只需要把传递到服务端,让服务端生成签名就可以了,你在调用jssdk的时候可以把url后面添加锚点链接。

实例

安装jssdk

npm install weixin-js-sdk --save

 前段代码

export default {
  mounted() {
   this.$nexttick(function () {
    this.getconfig()
   })
  },
  data () {
   return {
    detail: [],
   }
  },
  methods: {   
   // 微信分参数
   getconfig() { 
    let url = location.href.split('#')[0] //获取锚点之前的链接
    this.$http.get('/index.php',{
     params: {
      url: url
     }
    }).then(response => {
      let res = response.data;
      this.wxinit(res);
     })
   },
   // 微信分享
   wxinit(res) {
    let url = location.href.split('#')[0] //获取锚点之前的链接 
    let links = url+'#/food/' + this.$route.params.id;
    let title = this.detail.name + '-嘌呤查';
    let desc = '了解更多知识,请关注“嘌呤查”公众号';
    let imgurl = this.thumb;
    wx.config({
     debug: false,
     appid: res.appid,
     timestamp: res.timestamp,
     noncestr: res.noncestr,
     signature: res.signature,
     jsapilist: ['onmenusharetimeline', 'onmenushareappmessage', 'onmenushareqq', 'onmenushareweibo', 'onmenushareqzone']
    });
    wx.ready(function() {
     wx.onmenusharetimeline({
      title: title, // 分享标题
      desc: desc, // 分享描述
      link: links, // 分享链接
      imgurl: imgurl, // 分享图标
      success: function() {
//        alert("分享到朋友圈成功")
       //toast({
        //message: "成功分享到朋友圈"
       //});
      },
      cancel: function() {
//        alert("分享失败,您取消了分享!")
       //toast({
        //message: "分享失败,您取消了分享!"
       //});
      }
     });
     //微信分享菜单测试
     wx.onmenushareappmessage({
      title: title, // 分享标题
      desc: desc, // 分享描述
      link: links, // 分享链接
      imgurl: imgurl, // 分享图标
      success: function() {
       // alert("成功分享给朋友")
//       toast({
//        message: "成功分享给朋友"
//       });
      },
      cancel: function() {
       // alert("分享失败,您取消了分享!")
//       toast({
//        message: "分享失败,您取消了分享!"
//       });
      }
     });

     wx.onmenushareqq({
      title: title, // 分享标题
      desc: desc, // 分享描述
      link: links, // 分享链接
      imgurl: imgurl, // 分享图标
      success: function() {
       // alert("成功分享给qq")
//       toast({
//        message: "成功分享到qq"
//       });
      },
      cancel: function() {
       // alert("分享失败,您取消了分享!")
//       toast({
//        message: "分享失败,您取消了分享!"
//       });
      }
     });
     wx.onmenushareweibo({
      title: title, // 分享标题
      desc: desc, // 分享描述
      link: links, // 分享链接
      imgurl: imgurl, // 分享图标
      success: function() {
       // alert("成功分享给朋友")
//       toast({
//        message: "成功分享到腾讯微博"
//       });
      },
      cancel: function() {
       // alert("分享失败,您取消了分享!")
//       toast({
//        message: "分享失败,您取消了分享!"
//       });
      }
     });
     wx.onmenushareqzone({
      title: title, // 分享标题
      desc: desc, // 分享描述
      link: links, // 分享链接
      imgurl: imgurl, // 分享图标
      success: function() {
       // alert("成功分享给朋友")
//       toast({
//        message: "成功分享到qq空间"
//       });
      },
      cancel: function() {
       // alert("分享失败,您取消了分享!")
//       toast({
//        message: "分享失败,您取消了分享!"
//       });
      }
     });

    });
    wx.error(function(err) {
     alert(json.stringify(err))
    });
   }
  }
 }

index.php页面代码

// 官方实例,生成wx.config需要的配置信息
class jssdk {
 private $appid;
 private $appsecret;

 public function __construct($appid, $appsecret) {
  $this->appid = $appid;
  $this->appsecret = $appsecret;
 }

 public function getsignpackage() {
  $jsapiticket = $this->getjsapiticket();

  // 注意 url 一定要动态获取,不能 hardcode.
  $protocol = (!empty($_server['https']) && $_server['https'] !== 'off' || $_server['server_port'] == 443) ? "https://" : "http://";
  // 注意这里是重点
  $url = !empty($_get['url']) ? $_get['url'] : "$protocol$_server[http_host]$_server[request_uri]";

  $timestamp = time();
  $noncestr = $this->createnoncestr();

  // 这里参数的顺序要按照 key 值 ascii 码升序排序
  $string = "jsapi_ticket=$jsapiticket&noncestr=$noncestr&timestamp=$timestamp&url=$url";

  $signature = sha1($string);

  $signpackage = array(
   "appid"   => $this->appid,
   "noncestr" => $noncestr,
   "timestamp" => $timestamp,
   "url"    => $url,
   "signature" => $signature,
   "rawstring" => $string
  );
  return $signpackage; 
 }

 private 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;
 }

 private function getjsapiticket() {
  // jsapi_ticket 应该全局存储与更新,以下代码以写入到文件中做示例
  $data = json_decode($this->get_php_file("jsapi_ticket.php"));
  if ($data->expire_time < time()) {
   $accesstoken = $this->getaccesstoken();
   // 如果是企业号用以下 url 获取 ticket
   // $url = "https://qyapi.weixin.qq.com/cgi-bin/get_jsapi_ticket?access_token=$accesstoken";
   $url = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?type=jsapi&access_token=$accesstoken";
   $res = json_decode($this->httpget($url));
   $ticket = $res->ticket;
   if ($ticket) {
    $data->expire_time = time() + 7000;
    $data->jsapi_ticket = $ticket;
    $this->set_php_file("jsapi_ticket.php", json_encode($data));
   }
  } else {
   $ticket = $data->jsapi_ticket;
  }

  return $ticket;
 }

 private function getaccesstoken() {
  // access_token 应该全局存储与更新,以下代码以写入到文件中做示例
  $data = json_decode($this->get_php_file("access_token.php"));
  if ($data->expire_time < time()) {
   // 如果是企业号用以下url获取access_token
   // $url = "https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid=$this->appid&corpsecret=$this->appsecret";
   $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=$this->appid&secret=$this->appsecret";
   $res = json_decode($this->httpget($url));
   $access_token = $res->access_token;
   if ($access_token) {
    $data->expire_time = time() + 7000;
    $data->access_token = $access_token;
    $this->set_php_file("access_token.php", json_encode($data));
   }
  } else {
   $access_token = $data->access_token;
  }
  return $access_token;
 }

 private function httpget($url) {
  $curl = curl_init();
  curl_setopt($curl, curlopt_returntransfer, true);
  curl_setopt($curl, curlopt_timeout, 500);
  // 为保证第三方服务器与微信服务器之间数据传输的安全性,所有微信接口采用https方式调用,必须使用下面2行代码打开ssl安全校验。
  // 如果在部署过程中代码在此处验证失败,请到 http://curl.haxx.se/ca/cacert.pem 下载新的证书判别文件。
  curl_setopt($curl, curlopt_ssl_verifypeer, true);
  curl_setopt($curl, curlopt_ssl_verifyhost, true);
  curl_setopt($curl, curlopt_url, $url);

  $res = curl_exec($curl);
  curl_close($curl);

  return $res;
 }

 private function get_php_file($filename) {
  return trim(substr(file_get_contents($filename), 15));
 }
 private function set_php_file($filename, $content) {
  $fp = fopen($filename, "w");
  fwrite($fp, "<?php exit();?>" . $content);
  fclose($fp);
 }
}



// 逻辑代码
$appid = '你的appid';
$appsecret = '你的appsecret';
$jssdk = new jssdk($appid, $appsecret);
$signpackage = $jssdk->getsignpackage();
echo json_encode($signpackage);

看到上面的类中使用$_get[‘url']接收前段传过来的数据

以上所述是小编给大家介绍的vue开发中调用微信jssdk的问题详解整合,希望对大家有所帮助

《详解vue开发中调用微信jssdk的问题.doc》

下载本文的Word格式文档,以方便收藏与打印。