1)首先是官方接口文檔:php
一、批量添加卡券接口:https://mp.weixin.qq.com/wiki?action=doc&id=mp1421141115&t=0.08619731531288366&token=&lang=zh_CN#wxkq3 ;json
二、卡券擴展字段cardExt說明:https://mp.weixin.qq.com/wiki?action=doc&id=mp1421141115&t=0.08619731531288366&token=&lang=zh_CN#fl4api
2)坑一:接入準備安全
一、須要在微信公衆號平臺裏配置「JS接口安全域名」,位置:公衆號設置-》功能設置-》JS接口安全域名;微信
二、配置「網頁受權域名」(獲取openid時須要用到,怎麼獲取這裏就不說了),位置同上:公衆號設置-》功能設置-》網頁受權域名session
3)坑二:api_ticket、signatureapp
一、添加卡券須要的api_ticket和signature(簽名),和默認的 jsapi_ticket、signature 都不一樣,最坑的是,官方的jssdk裏還沒相關的demo,因此要本身寫,獲取方法以下:異步
整合進jssdk.php,大概是這樣子工具
public function getWxCardApiTicket(){ // api_ticket 應該全局存儲與更新,如下代碼以寫入到文件中作示例 $data = json_decode($this->get_php_file("wxcard_api_ticket.php")); if ($data->expire_time < time()) { $accessToken = $this->getAccessToken(); // 若是是企業號用如下 URL 獲取 ticket $url = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token={$accessToken}&type=wx_card"; $res = json_decode($this->httpGet($url)); $ticket = $res->ticket; if ($ticket) { $data->expire_time = time() + 7000; $data->api_ticket = $ticket; $this->set_php_file("wxcard_api_ticket.php", json_encode($data)); } } else { $ticket = $data->api_ticket; } return $ticket; }
二、卡券簽名大概是這樣子,根據本身項目的邏輯異步請求計算簽名(假設是xxx.php)this
$jssdk = new JSSDK("appId", "appSecret"); $api_ticket = $jssdk->getWxCardApiTicket();
$code = '';
$arr = array($api_ticket, $code, $_GET['timestamp'], $_GET['nonceStr'], $_GET['card_id'], $_SESSION['openid']); sort($arr, SORT_STRING); $signature = sha1(implode($arr)); echo json_encode(array('signature'=>$signature)); exit;
簽名驗證、對比工具:http://mp.weixin.qq.com/debug/cgi-bin/sandbox?t=cardsign
4)坑四:js配置
一、js的config配置(jsApiList)須要添加 'addCard';
二、addCard方法裏的cardExt裏須要 'nonce_str' 參數(官方的demo.js裏並無nonce_str參數,但親測沒這個參數會報簽名錯誤!);
三、cardExt裏參數和要後臺計算簽名的參數保持一致(時間戳也要保持一致);
使用card_id異步計算簽名並調用添加卡券方法的示例:
function addCard(card_id){ var data={'opendid':'<{$smarty.session.openid}>','card_id':card_id,'timestamp':'<?php echo $signPackage["timestamp"];?>','nonceStr':'<?php echo $signPackage["nonceStr"];?>'}; $.get('xxxx.php',data,function(res){ wx.addCard({ cardList: [ { cardId: card_id, cardExt: '{"code":"", "openid": "<{$smarty.session.openid}>", "nonce_str":"<?php echo $signPackage["nonceStr"];?>","timestamp": "<?php echo $signPackage["timestamp"]; ?>", "signature":"'+res.signature+'"}' } ], success: function (res) { alert('已添加卡券:' + JSON.stringify(res.cardList)); }, cancel: function (res) { alert(JSON.stringify(res)) } }); },'json'); }
5)坑五:注意變量名大小寫,有無下劃線等等