Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

微信 JSSDK 在 SPA html5 history 的坑爹之旅 #22

Open
luckyyyyy opened this issue Sep 10, 2017 · 0 comments
Open

微信 JSSDK 在 SPA html5 history 的坑爹之旅 #22

luckyyyyy opened this issue Sep 10, 2017 · 0 comments
Labels

Comments

@luckyyyyy
Copy link
Owner

话说这问题其实早在2016年末就已经遇到过了,没想到时隔接近一年,这次又重回微信开发,遇到了更坑爹的情况。
下文所有的情况都是基于SPA html5 history所讨论,其他情况不列入在内,比如终结方案就是不用 history 路由。
首先吐槽一下微信文档,我认为微信团队根本没把心思花在这个上面,包括小程序也是一样,不管API还是文档,都写的很烂。

配置签名步骤

说实话配置签名还算是简单,不过官方给的demo质量也也太差了,相信大部分人都是复制粘贴的,下面贴一个质量稍微高一点的php签名算法。
客户端只需要把window.location.href发来即可。

$sParams = [
  'noncestr' => uniqid('wjs_'),
  'jsapi_ticket' => $jsapi_ticket,
  'timestamp' => time(),
  'url' => $url,
];
if (($pos = strpos($sParams['url'], '#')) !== false) {
    $sParams['url'] = substr($sParams['url'], 0, $pos);
}
ksort($sParams);
$rawData = '';
foreach ($sParams as $k => $v) {
    $rawData .= '&' . $k . '=' . $v;
}
$signature = sha1(substr($rawData, 1));
return [
  'appId' => WECHAT_APPID,
  'nonceStr' => $sParams['noncestr'],
  'timestamp'=> $sParams['timestamp'],
  'url' => $url,
  'signature' => $signature,
  // 'rawString' => $rawData,
];

调用接口

接口都必须在wx.config后的wx.ready执行,首先吐槽官方的SDK,绝对可以让新手写出回调地狱。

$.ajax({
  success: function({
    // ...
    wx.config()
  })
})

wx.ready(function(){
  //...
  wx.xxx(function(){
    success: function() {
      // ...  
    }
  })
})

对于SPA的注意点

  • wx.ready只会执行一次,即无论是否多次调用wx.config,均只执行一次。
  • 就算config ok了,也有概率会出现切页面后无法调用分享的情况。
  • 在用户第一次OAuth2认证进来时,有极大可能是config ok后切页面就无法调用分享的情况。
  • 在上述情况下,页面切换后无法调用分享,但依然可以唤起wx.scanQRCode
  • 页面切换回第一次进入的页面后恢复正常,关闭浏览器再次进入也正常,只有在第一次OAuth2认证时不正常,并且在第一页reload无效,需要切换任意到第二页reload。
  • 在config fail的情况下,基本都是签名错误,这时候只需要reload即可,除此之外别无方法,本人尝试过将所有url发去做签名,均是失败,最后直接调用reload则成功。
  • 在iOS上,config的是第一个进入时的url,在安卓上则是每次pushstate后url。
  • 警告:千万别尝试去找规律,鄙人在此花费的时间 > 24h。
@luckyyyyy luckyyyyy added the FE label Sep 10, 2017
@luckyyyyy luckyyyyy changed the title # 微信 JSSDK 在 SPA html5 history 的坑爹之旅 微信 JSSDK 在 SPA html5 history 的坑爹之旅 Sep 13, 2017
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

1 participant