优惠券的核销,主要是通过jssdk调用摄像头扫描优惠券的二维码,获取二维码编号到后端调用微信接口核销的过程
前端
前端页面代码,调用起摄像头,扫描优惠券二维码
<div class="hx" @click="userScan">
<i class="iconfont hexiao"></i> 核销卡券
<i class="iconfont jiantou-you icon"></i>
<i class="iconfont shaomiao icon"></i>
</div>
userScan事件
userScan:function(){
let that = this
// that.checkIsShopCoupon('274049434570')
wx.scanQRCode({
needResult: 1, // 默认为0,扫描结果由微信处理,1则直接返回扫描结果,
scanType: ["qrCode","barCode"], // 可以指定扫二维码还是一维码,默认二者都有
success: function (res) {
if(res.errMsg=='scanQRCode:ok'){
let _code = res.resultStr;
that.checkIsShopCoupon(_code)
}
}
})
},
checkIsShopCoupon:function(code){
let that = this
axios.post('/api/coupon/user/checkIsShopCoupon',{
code:code,
user_id:that.userInfo.user_id
}).then(res=>{
if(res.data.code==400){
alert('该卡券不能在本店使用')
return
} else {
/*--进行核销--*/
that.couponConsume(code)
}
})
},
/**
* 卡券核销
* @param {*} code
*/
couponConsume:function(code) {
let that = this
axios.post('/api/coupon/user/couponConsume',{
code:code,
user_id:that.userInfo.user_id
}).then(res=>{
if(res.data.errcode == 0) {
alert('核销成功')
} else {
alert('核销失败,该未到使用时间或已核销!')
}
})
},
后端
后端主要是接口/api/coupon/user/couponConsume,详细说一下这个接口
function couponConsume(){
$code = input('code');
$user_id = input('user_id');
$rs = user_coupon::get(['code'=>$code]);
$wx = new wxhelper(config('wx')['AppID'],config('wx')['AppSecret']);
$result = $wx->doCouponConsume($rs['code'],$rs['card_id']);
$res = json_decode($result);
if($res->errcode==0) { //核销成功
$rs->is_use=1;
$rs->consume_user_id = $user_id;//设置核销员
$rs->update_time=time();
$rs->save();
}
return $result;// $this->buildSuccess();
}
其中"doCouponConsume"方法
参考官方文档https://developers.weixin.qq.com/doc/offiaccount/Cards_and_Offer/gift_card.html#11.3%20%E6%A0%B8%E9%94%80%E7%94%A8%E6%88%B7%E7%A4%BC%E5%93%81%E5%8D%A1%E6%8E%A5%E5%8F%A3
public function doCouponConsume($code,$card_id) {
$token= $this->getAccessToken(); //参考上一篇
$url = "https://api.weixin.qq.com/card/code/consume?access_token=".$token;
$data = '{ "code": "'.$code.'", "card_id": "'.$card_id.'"}';
$result = $this->http_post($url,$data);
return $result;
}
这样,就完成了优惠券的核销了。