vue開發中調用微信jssdk的問題

起因

微信分享網址時無法分享圖片,這個問題需要用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中錨點之前的部分。
比如你的網址是http://domain.com/index.html#/food/1
你只需要把http://domain.com/index.html傳遞到服務端,讓服務端生成簽名就可以了,你在調用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’]接收前段傳過來的數據

發佈了91 篇原創文章 · 獲贊 40 · 訪問量 39萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章