'请输入code'], [['order_amount'], 'required', 'message' => '请输入金额'], [['goods'], 'safe'] ]; $params = Yii::$app->request->post(); $res = Yii::$app->services->validate->validate($params, $rules); if ($res === false) throw new \Exception(Yii::$app->services->validate->getErrorMessage()); // 校验当前系统是否安装了支付宝商家券插件 if (!MallAddons::isInstall($this->mall_id, AddonsEnum::ADDONS_NAME_ALIPAY_MCH_COUPON)) { throw new \Exception('您还未安装当前插件'); } // 先获取token $auth_token = Yii::$app->cache->get(RedisKeyEnum::suffix(RedisKeyEnum::ALIPAY_ACCESS_TOKEN, "voucher:{$this->user_id}")); if (empty($auth_token)) { // 获取token $auth_token = $this->getAccessToken($params['code']); } $res = (new ConsultService([ 'mall_id' => $this->mall_id, 'auth_token' => $auth_token, 'order_amount' => $params['order_amount'], 'goods' => $params['goods'] ]))->exec(); if (empty($res['code']) || $res['code'] != 10000) throw new \Exception($res['msg'] ?? '获取代金券失败'); $ret = $this->formatVoucherList($res['voucher_consult_list'] ?? []); return $this->success('获取成功', $ret); } catch (\Exception $e) { return $this->error($e->getMessage()); } } /** * @param string $code * @return mixed * @throws \Exception */ protected function getAccessToken(string $code) { $res = (new OauthTokenService([ 'mall_id' => $this->mall_id, 'code' => $code ]))->exec(); if (empty($res['access_token'])) throw new \Exception($res['msg'] ?? '获取token失败'); Yii::$app->cache->set(RedisKeyEnum::suffix(RedisKeyEnum::ALIPAY_ACCESS_TOKEN, "voucher:{$this->user_id}"), $res['access_token'], $res['expires_in'] - 10); return $res['access_token']; } /** * 格式化代金券数据 * @param array $ret * @return array */ protected function formatVoucherList(array $ret): array { // voucher_type 1)全场券(ALL) 2)单品券(ITEM) // promo_type 优惠类型: 代金(FIX),折扣(DISCOUNT),减至(SPECIAL,即特价券) $data = []; if (empty($ret)) return $data; foreach ($ret as $key => $value) { // $data[$key] = [ // 'list' => [], // 'voucher_name' => $value['voucher_name'], // 'promo_type' => $value['promo_type'], // 'voucher_type' => $value['voucher_type'], // 'promo_type_txt' => AlipayVoucherEnum::PROMO_TYPE_REMARKS[$value['promo_type']] ?? '未知类型', // 'voucher_type_txt' => AlipayVoucherEnum::VOUCHER_TYPE_REMARKS[$value['voucher_type']] ?? '未知类型', // ]; $list = $value['item_promo_info']['item_consult_list']; if (!empty($list)) { foreach ($list as $item) { $data[$item['item_id']] = [ 'id' => $item['item_id'], 'promo_amount' => $item['promo_amount'], // 商品优惠总金额 'promo_count' => $item['promo_count'], // 商品优惠总数量 'voucher_name' => $value['voucher_name'], 'promo_type' => $value['promo_type'], 'voucher_type' => $value['voucher_type'], 'promo_type_txt' => AlipayVoucherEnum::PROMO_TYPE_REMARKS[$value['promo_type']] ?? '未知类型', 'voucher_type_txt' => AlipayVoucherEnum::VOUCHER_TYPE_REMARKS[$value['voucher_type']] ?? '未知类型', ]; } } } return $data; } }