国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 編程 > JavaScript > 正文

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

2019-11-19 11:46:05
字體:
來源:轉載
供稿:網友

起因

微信分享網址時無法分享圖片,這個問題需要用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: "成功分享給朋友"http://       });      },      cancel: function() {       // alert("分享失敗,您取消了分享!")//       Toast({//        message: "分享失敗,您取消了分享!"http://       });      }     });     wx.onMenuShareQQ({      title: title, // 分享標題      desc: desc, // 分享描述      link: links, // 分享鏈接      imgUrl: imgUrl, // 分享圖標      success: function() {       // alert("成功分享給QQ")//       Toast({//        message: "成功分享到QQ"http://       });      },      cancel: function() {       // alert("分享失敗,您取消了分享!")//       Toast({//        message: "分享失敗,您取消了分享!"http://       });      }     });     wx.onMenuShareWeibo({      title: title, // 分享標題      desc: desc, // 分享描述      link: links, // 分享鏈接      imgUrl: imgUrl, // 分享圖標      success: function() {       // alert("成功分享給朋友")//       Toast({//        message: "成功分享到騰訊微博"http://       });      },      cancel: function() {       // alert("分享失敗,您取消了分享!")//       Toast({//        message: "分享失敗,您取消了分享!"http://       });      }     });     wx.onMenuShareQZone({      title: title, // 分享標題      desc: desc, // 分享描述      link: links, // 分享鏈接      imgUrl: imgUrl, // 分享圖標      success: function() {       // alert("成功分享給朋友")//       Toast({//        message: "成功分享到QQ空間"http://       });      },      cancel: function() {       // alert("分享失敗,您取消了分享!")//       Toast({//        message: "分享失敗,您取消了分享!"http://       });      }     });    });    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×tamp=$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的問題詳解整合,希望對大家有所幫助,如果大家有任何疑問請給我留言,小編會及時回復大家的。在此也非常感謝大家對武林網網站的支持!

發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 泗阳县| 雅安市| 遂川县| 五指山市| 高雄市| 上犹县| 天台县| 逊克县| 洮南市| 牙克石市| 开江县| 兴和县| 巴马| 玛曲县| 留坝县| 自贡市| 颍上县| 额济纳旗| 大英县| 洮南市| 陆川县| 平阳县| 西平县| 灵台县| 乐清市| 铜鼓县| 祁门县| 长宁县| 溆浦县| 彝良县| 晋宁县| 水富县| 衢州市| 抚松县| 浪卡子县| 电白县| 同德县| 吴堡县| 高陵县| 定结县| 随州市|