1)首先是官方接口文档:
1、批量添加卡券接口:https://mp.weixin.qq.com/wiki?action=doc&id=mp1421141115&t=0.08619731531288366&token=&lang=zh_CN#wxkq3 ;
2、卡券扩展字段cardExt说明:https://mp.weixin.qq.com/wiki?action=doc&id=mp1421141115&t=0.08619731531288366&token=&lang=zh_CN#fl4
2)坑一:接入准备
1、需要在微信公众号平台里配置“JS接口安全域名”,位置:公众号设置-》功能设置-》JS接口安全域名;
2、配置“网页授权域名”(获取openid时需要用到,怎么获取这里就不说了),位置同上:公众号设置-》功能设置-》网页授权域名
3)坑二:api_ticket、signature
1、添加卡券需要的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;
}
2、卡券签名大概是这样子,根据自己项目的逻辑异步请求计算签名(假设是xxx.php)
$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配置
1、js的config配置(jsApiList)需要添加 ‘addCard‘;
2、addCard方法里的cardExt里需要 ‘nonce_str‘ 参数(官方的demo.js里并没有nonce_str参数,但亲测没这个参数会报签名错误!);
3、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‘);
}