<?php
namespace app\api\controller;
use app\common\model\Ad;
use app\common\model\Base;
use app\common\model\CapitalLog;
use app\common\controller\Api;
use app\common\model\CouponCollectRecord;
use app\common\model\FundsRecord;
use app\common\model\TaobaoConfig;
use app\common\model\TaobaoCoupon;
use app\common\model\TaobaoFunc;
use think\Db;
use think\Exception;
use think\exception\ErrorException;
use think\Cache;
use think\Request;
/**
* 淘宝客php接口
* @author Administrator
*
*/
class Tbao extends Api
{
protected $noNeedLogin=['test','taobao_index', 'taobao_item_coupon'];
protected $noNeedRight = ['*'];
protected $inputs;
protected static $expire = null;
public function __construct(Request $request = null){
parent::__construct($request);
$this->inputs = $this->request->request();
$tbk_expire = Cache::get('tbk_expire','');
if(!$tbk_expire)
{
self::clearCache();
}
}
private $taobao_appkey=['24703018','24751961'],
$taobao_appsecret=['69f271db4adf88ad166fe06e21dc4b09','2a1805383c2c28ff880e16e1b353b8fd'],
$taobao_adzoneid=['156126650','179314415'];
private $taobao_offset = 0;
private $taobao_config;
private $eUidBidArr=['xc'];
/**
* 好券清单API【导购】
* @param $top
* @param $adZoneId mm_xxx_xxx_xxx的第三位
* @param int $platForm 1:PC,2:无线,默认:1
* @param string $q 查询词
* @param string $cat 后台类目ID,用,分割,最大10个,该ID可以通过taobao.itemcats.get接口获取到
* @param int $page_no 第几页,默认:1(当后台类目和查询词均不指定的时候,最多出10000个结果,即page_no*page_size不能超过10000;当指定类目或关键词的时候,则最多出100个结果)
* @param int $page_size/最大100,否则淘宝获获取默认20
* @return false|mixed|string
*/
public function getDgItemCoupon($top,$adZoneId, $platForm=2, $q='' , $cat='' , $page_no= 1 , $page_size = 20){
$req = load_tbk_req('TbkDgItemCouponGet',$adZoneId,$platForm);
$req->setCat($cat);
$req->setPageSize($page_size);
$req->setQ($q);
$req->setPageNo($page_no);
$resp = $top->execute($req);
return self::returnFormat($resp , 'results,tbk_coupon');
}
/**
* 阿里妈妈推广券信息查询
* @param \TopClient $top
* @param string $me
* @param string $itemId
* @param string $activityId
* @return mixed|string
*/
public function getTbkCoupon($top,$me='' , $itemId ='' , $activityId = ''){
if($me || $itemId || $activityId){
$req = load_tbk_req('TbkCouponGet');
$me && $req->setMe($me);
$itemId && $req->setItemId($itemId);
$activityId && $req->setActivityId($activityId);
$resp = $top->execute($req);
return self::returnFormat($resp , 'tbk_coupon_get_response');
}
}
public static function returnFormat($xml ,$keys = ''){
$xml = json_encode($xml);
$xml = json_decode($xml , TRUE);
if($keys){
$keys = explode(',', $keys);
foreach($keys as $k=>$v){
isset($xml[$v]) && $xml = $xml[$v];
}
}
return $xml;
}
public function test(){
$tb = load_top('24703018','69f271db4adf88ad166fe06e21dc4b09');
// $req = load_tbk_req('TbkDgItemCouponGet','156126650',2);
// $res = $tb->execute($req);
// $list = self::returnFormat($res,'results,tbk_coupon');
// $req = load_tbk_req('TbkCouponGet');
// $req->setMe('Tp6dHUe7ERIGQASttHIRqVgWROSJPm0Nk0K1S5%2FWSyHyi1aSyqbpmonyxSZXp4Mu2P356kJe9XPU8Tfc129ECps1ZZX0A1cpDfqEFBOhTcwRyfS9lbS6UA0npquaVbj%2Ftymm5TtsxcyQqbxTIKOSamPfrr0N2WBeD0L6ZZ%2F72J77J8FmRkgg%2BK1hbRgwYUOf');
// $res = $tb->execute($req);
// $info = self::returnFormat($res,'tbk_coupon_get_response');
$req = load_tbk_req('TbkOrderGet');
$res = $tb->execute($req);
$order = self::returnFormat($res);
$this->success("OK",$order);
}
/**
* 设置appkey信息
* @param null $bzinfo 客户端类型
* @throws \think\db\exception\DataNotFoundException
* @throws \think\db\exception\ModelNotFoundException
* @throws \think\exception\DbException
*/
private function setAppkeyInfo($bzinfo=NULL){
if(empty($bzinfo)){
$model = new TaobaoConfig();
$configs = $model->select();
$bzinfo = [];
foreach ($configs as $config)
{
if(strtolower($config['pv'])=='android')
{
$index = 0;
}
else
{
$index = 1;
}
$bzinfo['taobao_appkey'][$index] = $config['taobao_appkey'];
$bzinfo['taobao_appsecret'][$index] = $config['taobao_appsecret'];
$bzinfo['taobao_adzoneid'][$index] = $config['taobao_adzoneid'];
if(isset($config['taobao_q']) && !isset($bzinfo['taobao_q']))
{
$bzinfo['taobao_q'] = $config['taobao_q'];
}
if(isset($config['taobao_cat']) && !isset($bzinfo['taobao_cat']))
{
$bzinfo['taobao_cat'] = $config['taobao_cat'];
}
if(isset($config['taobao_sort']) && !isset($bzinfo['taobao_sort']))
{
$bzinfo['taobao_sort'] = $config['taobao_sort'];
}
if(isset($config['taobao_coupon_amount']) && !isset($bzinfo['taobao_coupon_amount']))
{
$bzinfo['taobao_coupon_amount'] = $config['taobao_coupon_amount'];
}
if(isset($config['taobao_convert_msg']) && !isset($bzinfo['taobao_convert_msg']))
{
$bzinfo['taobao_convert_msg'] = $config['taobao_convert_msg'];
}
}
}
$this->taobao_config = $bzinfo;
if(isset($bzinfo['taobao_appkey']) && $bzinfo['taobao_appkey'] && !in_array($bzinfo['taobao_appkey'], ['',','])){
foreach(['taobao_appkey' , 'taobao_appsecret' , 'taobao_adzoneid'] as $k=>$v){
$this->{$v} = $bzinfo[$v];
}
}
}
/**
* 淘宝客首页
*/
public function taobao_index(){
$pv = input('mobileType');
$page = input('post.page', 1, 'intval');
$this->setAppkeyInfo();
//商品分类
$returnData['category'] = Db::name('taobaoFunc')
->select();
$time = time();
$where = [
'ai.position' => 5,
'ai.begin_time' => ['elt', $time],
'ai.end_time' => ['egt', $time],
];
//轮播图
$returnData['banner'] = $indexAds = Db::name('appIndex')->alias('ai')
->join('appClass ac', 'ai.app_class_id = ac.id', 'left')
->where($where)
->field('ai.position, ai.app_image, ai.name, ai.url, ai.param_id, ai.login, ac.ios_class, ac.android_class')
->order(['ai.sort' => 'ASC'])
->select();
$returnData['coupon_list'] = $this->taobao_item_coupon($this->taobao_config['taobao_q'] , '' , $this->taobao_config['taobao_sort'] , $page , 20 , $pv , TRUE);
$this->success("OK",$returnData);
}
/**
* 获取淘宝客优惠券信息
* @param string $q 搜索关键字
* @param string $cat 分类
* @param string $sort 排序
* @param int $page_no 页数
* @param int $page_size 每页数量
* @param string $pv
* @param bool $return
* @return bool|false|null|\PDOStatement|string|\think\Collection
* @throws \think\db\exception\DataNotFoundException
* @throws \think\db\exception\ModelNotFoundException
* @throws \think\exception\DbException
*/
public function taobao_item_coupon( $q = '' , $cat = '' , $sort = 'zk_final_price_asc' , $page_no=1 , $page_size=20 ,$pv='' ,$return = FALSE){
$pv = $pv ? $pv : input('mobileType');
if(strtolower($pv)=='ios'){
$this->taobao_offset = 1;
}
if($q){
$q = urldecode($q);
}
$this->setAppkeyInfo();
$appkey_adzone = $this->taobao_appkey[$this->taobao_offset].$this->taobao_adzoneid[$this->taobao_offset];
//查找数据库数量
$count = TaobaoCoupon::number(['appkey_adzone'=>$appkey_adzone , 'q'=>$q]);
$order = preg_replace('/^(.+)_(\w+)$/is','\\1 \\2',trim($sort));
$whereMap = ['appkey_adzone'=>$appkey_adzone] ;
if($q){
$whereMap['q'] = $q;
}
//数量大于5000从数据库获取,否则对接接口
$list = $count>5000 ? TaobaoCoupon::search($whereMap ,['order_by'=>$order,'page'=>['num'=>$page_no,'size'=>$page_size]]) : NULL;
if(empty($list)){
$tb = load_top($this->taobao_appkey[$this->taobao_offset],$this->taobao_appsecret[$this->taobao_offset]);
$newlist = self::getDgItemCoupon($tb, $this->taobao_adzoneid[$this->taobao_offset],2, $q , $cat , $page_no , $page_size);
//dump($newlist);die;
if($newlist){
foreach($newlist as $k=>$v){
//如果有优惠券,匹配优惠券金额
if(isset($v['coupon_info']) && $v['coupon_info']){
preg_match('/(?P<start>\d+).\D+(?P<amount>\d+)/is', $v['coupon_info'] , $r);
$v['coupon_amount'] = isset($r['amount']) ? sprintf('%.2f', $r['amount']) : 0;
$v['coupon_start_fee'] = isset($r['start']) ? sprintf('%.2f', $r['start']) : 0;
}else{
continue;
}
$perc = isset($this->taobao_config['taobao_coupon_amount']) ? $this->taobao_config['taobao_coupon_amount'] : 1;
$v['me_alert'] = sprintf($this->taobao_config['taobao_convert_msg'] , sprintf('%.2f',$v['coupon_amount']*$perc) , $v['coupon_amount']);
$url=parse_url($v['coupon_click_url']);
if($url['query']){
parse_str($url['query'] , $argvs);
$v['me'] = isset($argvs['e']) ? $argvs['e'] : '';
}
$v['small_images'] = json_encode(isset($v['small_images']) && $v['small_images'] ? $v['small_images'] : []);
$v['appkey_adzone'] = $appkey_adzone;
$v['item_description'] = is_array($v['item_description']) ? implode('', $v['item_description']) : $v['item_description'] ;
if($q){
$v['q'] = $q;
}
if(!TaobaoCoupon::number(['num_iid'=>$v['num_iid'] , 'appkey_adzone'=>$v['appkey_adzone']])){
TaobaoCoupon::add($v);
}
}
}
}
if(empty($list)){
$list = Db::name('taobaoCoupon')->where($whereMap)->order($order)->page($page_no, $page_size)->select();
}
if($list){
foreach($list as $k=>$v){
$list[$k]['small_images'] = json_decode($v['small_images'], true);
}
}
if($return){
return $list;
}
$this->success("OK",$list);
}
/**
* 兑换优惠券信息
* @param string $user_id
* @param string $me
* @param string $pv
* @return array
*/
public function taobao_coupon_info($user_id , $me , $pv=''){
$pv = $pv ? $pv : input('mobileType');
$uid = $user_id;
if(strtolower($pv)=='ios'){
$this->taobao_offset = 1;
}
$this->setAppkeyInfo();
$tb = load_top($this->taobao_appkey[$this->taobao_offset],$this->taobao_appsecret[$this->taobao_offset]);
$data = self::getTbkCoupon($tb,$me);
return isset($data['data']) ? $data['data'] : [];
}
/**
* 领券操作
*/
public function taobao_coupon_convert(){
$me = input('post.me');
$pv = input('post.mobileType', 'ios');
$itemUrl = input('post.item_url');
if(!$me || !$itemUrl) {
$this->error('参数错误');
}
$arr = parse_url($itemUrl);
$params = $arr['query'];
$paramsArr = explode('=', $params);
if(isset($paramsArr['0']) && $paramsArr['0'] == 'id' && isset($paramsArr[1]) && !empty($paramsArr[1])) {
$goodsId = $paramsArr[1];
} else {
$this->error('itemUrl格式错误');
}
$uid = $this->auth->id;
$userInfo = Db::name('user')->find($uid);
$me = input("me",$me);
$coupon_info = $this->taobao_coupon_info($uid , $me, $pv);
if(!$coupon_info){
$this->error('优惠券不存在');
}
if(!$coupon_info['coupon_total_count']){
$this->error('优惠券已失效');
}
$perc = $this->taobao_config['taobao_coupon_amount'];
if($perc<0){
$this->error('扣优惠券不能为负数');
}
if($perc>0){
//添加优惠券流水
$leftMoney = intval($userInfo['voucher_balance']-$coupon_info['coupon_amount']*$perc);
if($leftMoney<0){
$leftMsg = sprintf('优惠券扣优惠券%s,当前优惠券:%s,优惠券不足' , $coupon_info['coupon_amount']*$perc,$userInfo['voucher_balance']);
$this->error($leftMsg);
}
Db::startTrans();
try{
$totalAmount = $coupon_info['coupon_amount'] * $perc;
$userRes = Db::name('user')->where(['id' => $uid])->setDec('voucher_balance', $totalAmount);
if(!$userRes)
{
throw new Exception('扣除优惠券出错');
}
$logModel = new FundsRecord();
$res = $logModel->addRecord($uid, $totalAmount,$userInfo['voucher_balance'],$logModel::ACCOUNT_TYPE_VOUCHER, $logModel::OPE_TYPE_LESS, $logModel::TYPE_VOUCHER_EXCHANGE,'','兑换淘宝客优惠券');
if(!$res)
{
throw new Exception('添加兑换流水出错');
}
//添加用户领券记录
$recordRes = Db::name('CouponCollectRecord')
->insert([
'user_id' => $uid,
'goods_id' => $goodsId,
'create_time' => time()
]);
if(!$recordRes) {
throw new Exception('添加领取记录出错');
}
Db::commit();
$this->success('兑换成功');
}
catch (Exception $e)
{
Db::rollback();
$this->error($e->getMessage());
}
}
}
/**
* 一天清除一次优惠券的记录
*/
public static function clearCache(){
TaobaoCoupon::clear();
self::$expire = strtotime(date("Ymd000000",strtotime("+1 day")))-time();
Cache::set("tbk_expire",'1',self::$expire);
}
}
<?php
/**
* Created by PhpStorm.
* User: Administrator
* Date: 2018/12/17
* Time: 9:35
* 淘宝客优惠券
*/
namespace app\api\controller;
use app\common\controller\Api;
use app\common\model\CommissionRebate;
use app\common\model\CouponCollectRecord;
use app\common\model\FundsRecord;
use app\common\model\OrderTbk;
use app\common\model\PromotionPosition;
use think\Db;
use think\Request;
class Tbk extends Api {
protected $noNeedRight = ['*'];
protected $topClient = null;
protected $adzoneid = '';
protected $noNeedLogin = ['tbksettlementorder', 'tbkneworder'];
private $tbkAppkey='24703018',
$tbkSecret='69f271db4adf88ad166fe06e21dc4b09',
$taobaoAdzoneid='156126650';
public function __construct(Request $request = null)
{
parent::__construct($request);
vendor('taobao.TopSdk');
$this->topClient = new \TopClient();
//查找商户是否配置淘宝客信息,没有使用默认信息
$config = Db::name('taobaoConfig')
->find();
if($config) {
$appkey = $config['taobao_appkey'];
$secretKey = $config['taobao_appsecret'];
$adzoneId = $config['taobao_adzoneid'];
} else {
$appkey = $this->tbkAppkey;
$secretKey = $this->tbkSecret;
$adzoneId = $this->taobaoAdzoneid;
}
$this->topClient->appkey = $appkey;
$this->topClient->secretKey = $secretKey;
$this->adzoneid = $adzoneId;
}
/**
* 淘宝客物料下行-导购(推荐商品)
*/
public function dgOptimusMaterial () {
$page = input('post.page', 1, 'intval');
$time = time();
$where = [
'ai.position' => 5,
'ai.begin_time' => ['elt', $time],
'ai.end_time' => ['egt', $time],
];
$returnData['banner'] = Db::name('appIndex')->alias('ai')
->join('appClass ac', 'ai.app_class_id = ac.id', 'left')
->where($where)
->field('ai.position, ai.app_image, ai.name, ai.url, ai.param_id, ai.login, ac.ios_class, ac.android_class')
->order(['ai.sort' => 'ASC'])
->select();
//商品分类
$where['ai.position'] = 12;
$returnData['category'] = Db::name('appIndex')->alias('ai')
->join('appClass ac', 'ai.app_class_id = ac.id', 'left')
->where($where)
->field('ai.position, ai.app_image, ai.name, ai.url, ai.param_id, ai.login, ac.ios_class, ac.android_class')
->order(['ai.sort' => 'ASC'])
->select();
$returnData['goods'] = [];
$c = $this->topClient;
$req = new \TbkDgOptimusMaterialRequest();
$req->setPageSize("20");
$req->setAdzoneId($this->adzoneid);
$req->setPageNo($page);
$req->setMaterialId("9660");
// $req->setDeviceValue("xxx");
// $req->setDeviceEncrypt("MD5");
// $req->setDeviceType("IMEI");
// $req->setContentId("323");
// $req->setContentSource("xxx");
$resp = $c->execute($req);
$res = json_encode($resp);
$result = \GuzzleHttp\json_decode($res, true);
if(isset($result['result_list']['map_data'])) {
$coupons = $result['result_list']['map_data'];
$goods = [];
if(!empty($coupons)) {
$rebateModel = new CommissionRebate();
$config = $rebateModel->where([
'rebate_type' => $rebateModel::REBATE_TYPE_TBK
])->find();
foreach ($coupons as $coupon) {
$commissionAmount = 0;
if($config) {
if($config['self_type'] == 1) {
$commissionAmount = floor($coupon['commission_rate']*$coupon['zk_final_price']*$config['self'])/100;
} else {
$commissionAmount = $config['self'];
}
}
$goods[] = [
'goods_img' => $this->checkUrl($coupon['pict_url']),
'goods_title' => $coupon['title'],
'goods_id' => $coupon['item_id'],
'shop_title' => '',
'sale_number' => $coupon['volume'],
'coupon_info' => '',
'coupon_amount' => floatval($coupon['coupon_amount']),
'coupon_after_price' => floatval($coupon['zk_final_price']-$coupon['coupon_amount']),
'coupon_remain_count' => '',
'coupon_total_count' => $coupon['coupon_total_count'],
'goods_price' => floatval($coupon['zk_final_price']),
'commission_amount' => floatval($commissionAmount),
'commission_rate' => $coupon['commission_rate'],
'coupon_click_url' => $this->checkUrl($coupon['coupon_click_url']),
'item_url' => $this->checkUrl($coupon['click_url']),
'small_images' => [],
'user_type' => $coupon['user_type'],
'goods_type' => $coupon['user_type'] == 1 ? 'tmall' : 'taobao',
'exchange_tips' => $coupon['coupon_amount'] > 0 ? '确定使用抵扣券兑换该现金券吗?' : '',
'isPinGou' => '',
'planId' => '',
'requestId' => '',
];
}
}
$returnData['goods'] = $goods;
}
$this->success('查询成功', $returnData);
}
/**
* 通用物料搜索API(导购)
*/
public function dgMaterialOptional () {
$keyword = input('post.keyword', '女装');
$page = input('post.page', 1, 'intval');
$sort = input('post.sort', 'tk_rate_des');
$c = $this->topClient;
$req = new \TbkDgMaterialOptionalRequest();
$req->setAdzoneId($this->adzoneid); //mm_xxx_xxx_xxx的第三位
// $req->setStartDsr("10");//店铺dsr评分,筛选高于等于当前设置的店铺dsr评分的商品0-50000之间
// $req->setPageSize("20"); //页大小,默认20,1~100
$req->setPageNo($page); //第几页,默认:1
// $req->setPlatform("1"); //链接形式:1:PC,2:无线,默认:1
// $req->setEndTkRate("1234"); //淘客佣金比率上限,如:1234表示12.34%
// $req->setStartTkRate("1234"); //淘客佣金比率下限,如:1234表示12.34%
// $req->setEndPrice("10"); //折扣价范围上限,单位:元
// $req->setStartPrice("10"); //折扣价范围下限,单位:元
// $req->setIsOverseas("false"); //是否海外商品,设置为true表示该商品是属于海外商品,设置为false或不设置表示不判断这个属性
// $req->setIsTmall("true"); //是否商城商品,设置为true表示该商品是属于淘宝商城商品,设置为false或不设置表示不判断这个属性
$req->setSort($sort); //排序_des(降序),排序_asc(升序),销量(total_sales),淘客佣金比率(tk_rate), 累计推广量(tk_total_sales),总支出佣金(tk_total_commi),价格(price)
// $req->setItemloc("杭州"); // 所在地
// $req->setCat("16,18"); //后台类目ID,用,分割,最大10个,该ID可以通过taobao.itemcats.get接口获取到
$req->setQ($keyword); //查询词
// $req->setMaterialId("2836"); // 官方的物料Id(详细物料id见:https://tbk.bbs.taobao.com/detail.html?appId=45301&postId=8576096),不传时默认为2836
$req->setHasCoupon("true"); //是否有优惠券,设置为true表示该商品有优惠券,设置为false或不设置表示不判断这个属性
// $req->setIp("13.2.33.4"); //ip参数影响邮费获取,如果不传或者传入不准确,邮费无法精准提供
// $req->setNeedFreeShipment("true"); //是否包邮,true表示包邮,空或false表示不限
// $req->setNeedPrepay("true"); //是否加入消费者保障,true表示加入,空或false表示不限
// $req->setIncludePayRate30("true"); //成交转化是否高于行业均值
// $req->setIncludeGoodRate("true"); //好评率是否高于行业均值
// $req->setIncludeRfdRate("true"); //退款率是否低于行业均值
// $req->setNpxLevel("2"); //牛皮癣程度,取值:1:不限,2:无,3:轻微
// $req->setEndKaTkRate("1234"); //KA媒体淘客佣金比率上限,如:1234表示12.34%
// $req->setStartKaTkRate("1234"); //KA媒体淘客佣金比率下限,如:1234表示12.34%
// $req->setDeviceEncrypt("MD5"); //设备号加密类型:MD5
// $req->setDeviceValue("xxx"); //设备号加密后的值
// $req->setDeviceType("IMEI"); //设备号类型:IMEI,或者IDFA,或者UTDID
$resp = $c->execute($req);
$res = json_encode($resp);
$result = \GuzzleHttp\json_decode($res, true);
// dump($result);die;
if(isset($result['result_list']['map_data'])) {
$coupons = $result['result_list']['map_data'];
$goods = [];
if(!empty($coupons)) {
$rebateModel = new CommissionRebate();
$config = $rebateModel->where([
'rebate_type' => $rebateModel::REBATE_TYPE_TBK
])->find();
foreach ($coupons as $coupon) {
$couponAmount = 0;
if($coupon['coupon_info']) {
preg_match('/减(.*?)元/is', $coupon['coupon_info'] , $r);
$couponAmount = isset($r[1]) ? sprintf('%.2f', $r[1]) : 0;
}
$coupon['commission_rate'] = $coupon['commission_rate']/10000;
$commissionAmount = 0;
if($config) {
if($config['self_type'] == 1) {
$commissionAmount = floor($coupon['commission_rate']*$coupon['zk_final_price']*$config['self']*100)/100;
} else {
$commissionAmount = $config['self'];
}
}
$goods[] = [
'goods_img' => $this->checkUrl($coupon['pict_url']),
'goods_title' => $coupon['title'],
'goods_id' => $coupon['num_iid'],
'shop_title' => $coupon['shop_title']?:'',
'sale_number' => $coupon['volume'],
'coupon_info' => $coupon['coupon_info'],
'coupon_amount' => floatval($couponAmount),
'coupon_after_price' => floatval($coupon['zk_final_price']-$couponAmount),
'coupon_remain_count' => $coupon['coupon_remain_count'],
'coupon_total_count' => $coupon['coupon_total_count'],
'goods_price' => floatval($coupon['zk_final_price']),
'commission_amount' => floatval($commissionAmount),
'commission_rate' => $coupon['commission_rate'],
'coupon_click_url' => isset($coupon['coupon_share_url']) ? $this->checkUrl($coupon['coupon_share_url']):'',
'item_url' => $this->checkUrl($coupon['item_url']),
'user_type' => $coupon['user_type'],
'goods_type' => $coupon['user_type'] == 1 ? 'tmall' : 'taobao',
'small_images' => isset($coupon['small_images']['string']) ? $coupon['small_images']['string'] : [],
'exchange_tips' => $couponAmount > 0 ? '确定使用抵扣券兑换该现金券吗?' : '',
'isPinGou' => '',
'planId' => '',
'requestId' => '',
];
}
}
$this->success('查询成功', $goods);
} else {
$this->success('查询成功', []);
}
}
/**
* 兑换优惠券
* @param $goodsId
* @param $amount
* @return array
* @throws \think\Exception
* @throws \think\db\exception\DataNotFoundException
* @throws \think\db\exception\ModelNotFoundException
* @throws \think\exception\DbException
*/
public function exchange($goodsId, $amount){
!$goodsId && $this->error('商品ID不能为空');
//扣除券金额
$userId = $this->auth->id;
$user = Db::name('user')->find($userId);
if($amount > 0 && $user['voucher_balance'] < $amount) {
$this->error('抵扣券不足,当前抵扣券【'.$user['voucher_balance'].'】');
}
Db::startTrans();
try {
if($amount > 0) {
$userRes = Db::name('user')->where(['id' => $userId])->setDec('voucher_balance', $amount);
if(!$userRes) {
throw new Exception('扣除抵扣券出错');
}
//记录资金流水
$logModel = new FundsRecord();
$logRes = $logModel->addRecord($userId, $amount, $user['voucher_balance'], $logModel::ACCOUNT_TYPE_VOUCHER, $logModel::OPE_TYPE_LESS, $logModel::TYPE_VOUCHER_EXCHANGE);
if(!$logRes) {
throw new Exception('记录资金流水出错');
}
}
//添加用户领券记录
$recordRes = Db::name('CouponCollectRecord')
->insert([
'user_id' => $userId,
'goods_id' => $goodsId,
'create_time' => time()
]);
if(!$recordRes) {
throw new Exception('添加领取记录出错');
}
Db::commit();
return [
'status' => true,
'info' => ''
];
} catch (Exception $e) {
Db::rollback();
return [
'status' => false,
'info' => $e->getMessage()
];
}
}
/**
* 检查URL
* @param $url
* @return string
*/
public function checkUrl($url) {
if($url && !preg_match('/^http/', $url)){
return 'https:'.$url;
} else {
return $url;
}
}
/**
* 匹配淘宝订单号
*/
public function pregOrder(){
$orderNo = input('post.order_no');
!$orderNo && $this->error('订单号不能为空');
$model = new OrderTbk();
$row = $model->where(['taobaoTradeParentId' => $orderNo])->find();
!$row && $this->error('订单不存在');
if($row['user_id']) {
$this->error('该订单已匹配其它用户');
}
$userId = $this->auth->id;
//查找该用户是否领过这个商品
$record = Db::name('couponCollectRecord')
->where([
'goods_id' => $row['auctionId'],
'user_id' => $userId,
'type' => CouponCollectRecord::TYPE_TBK,
'status' => CouponCollectRecord::STATUS_W,
'create_time' => ['elt', strtotime($row['createTime'])]
])
->find();
if(!$record) {
$this->error('你没有领取过此商品优惠券');
}
$res = Db::name('orderTbk')
->where(['id' => $row['id']])
->update([
'user_id' => $userId,
'status' => $model::STATUS_W
]);
if($res) {
$this->success('匹配成功,等待返利');
} else {
$this->error('匹配出错');
}
}
/**
* @param $text
* @param $url
* @param string $logo
* @return mixed
*/
public function taobaoTbkTpwdCreate ($text, $url, $logo = '') {
$c = $this->topClient;
$req = new \TbkTpwdCreateRequest();
// $req->setUserId("123");
$req->setText($text);
$req->setUrl($url);
$logo && $req->setLogo($logo);
$req->setExt("{}");
$resp = $c->execute($req);
$res = json_encode($resp);
$result = \GuzzleHttp\json_decode($res, true);
return $result;
}
/**
* 查询当天付款成功的订单
*/
public function tbkNewOrder() {
if($this->request->isAjax()) {
$postData = $this->request->request();
$orders = isset($postData['data']['paymentList']) ? $postData['data']['paymentList']: [];
if($orders) {
$model = new OrderTbk();
foreach($orders as $order) {
$where['taobaoTradeParentId'] = $order['taobaoTradeParentId'];
$row = Db::name('orderTbk')
->where($where)
->find();
if($row) {
$res = $model->allowField(true)->save($order, ['id' => $row['id']]);
} else {
$order['status'] = $model::STATUS_P;
$res = $model->allowField(true)->isUpdate(false)->insert($order);
}
}
}
$this->success('操作成功');
}
}
/**
* 处理淘宝客已经结算的订单
*/
public function tbkSettlementOrder () {
if($this->request->isAjax()) {
$postData = $this->request->request();
$orders = isset($postData['data']['paymentList']) ? $postData['data']['paymentList']: [];
if($orders) {
$model = new OrderTbk();
foreach($orders as $order) {
$where['taobaoTradeParentId'] = $order['taobaoTradeParentId'];
//查找成交的订单数据
$row = Db::name('orderTbk')
->where($where)
->find();
if($row && $row['status'] == $model::STATUS_W) {
//如果数据存在,且状态为待结算,更改状态为待返利
$data['status'] = $model::STATUS_S;
$res = $model->allowField(true)->save($data, ['id' => $row['id']]);
} else {
$order['status'] = $model::STATUS_S;
$res = $model->allowField(true)->isUpdate(false)->insert($order);
}
}
}
}
$this->success('操作成功');
}
}
模型
<?php
namespace app\common\model;
use think\Db;
use think\Model;
class Taobao extends Model
{
// 自动写入时间戳字段
protected $autoWriteTimestamp = 'int';
// 定义时间戳字段名
protected $createTime = 'createtime';
protected $updateTime = 'updatetime';
public static $modelCoupon = 'a_taobao_coupon';
public static $modelConfig = 'mall_admin';
public static $modelCategory = 'a_taobao_func';
public static $modelAd = 'a_ad';
public static function getTabaoCouponList($map , $order = [] , $page =1 , $pageSize =20){
$result = Db::table(self::$modelCoupon)->where($map);
if(isset($map['q']) && $map['q']){
$result = $result->whereLike('title', '%'.$map['q'].'%');
}
$result = $result->page($page , $pageSize);
if($order){
foreach($order as $k=>$v){
$result = $result->order($k , $v);
}
}
$result = $result->select();
if($result)
{
return $result;
}else{
return array();
}
}
public static function addTabaoCoupon($data){
$result = Db::table(self::$modelCoupon)->insert($data,false,true);
if($result)
{
return $result ;
}else{
return false;
}
}
public static function getTabaoCoupon($map){
$result = Db::table(self::$modelCoupon)->where($map)->find();
if($result)
{
return $result ;
}else{
return array();
}
}
public static function getTabaoCouponCount($map){
return Db::table(self::$modelCoupon)->where($map)->count(1);
}
public static function getTabaoCategoryList($map , $order = [] ){
$result = Db::table(self::$modelCategory)->where($map);
if($order){
foreach($order as $k=>$v){
$result = $result->order($k , $v);
}
}
$result = $result->select();
if($result)
{
return $result;
}else{
return array();
}
}
public static function getTabaoCategory($map , $column = '' ){
$result = Db::table(self::$modelCategory)->where($map);
return $column ? $result->value($column) : $result->find();
}
public static function getTabaoAdList($map,$order = []){
$result = Db::table(self::$modelAd)->where($map);
if($order){
foreach($order as $k=>$v){
$result = $result->order($k , $v);
}
}
$result = $result->select();
if($result)
{
return $result;
}else{
return array();
}
}
public static function getTaobaoConfig($map = ['uid'=>101]){
return Db::table(self::$modelConfig)->where($map)->find();
}
public static function clearCache(){
return Db::table(self::$modelCoupon)->execute("TRUNCATE `a_taobao_coupon`");
}
}
<?php
namespace app\common\model;
use think\Model;
class TaobaoConfig extends Model
{
// 表名
protected $name = 'taobao_config';
// 自动写入时间戳字段
protected $autoWriteTimestamp = false;
// 定义时间戳字段名
protected $createTime = false;
protected $updateTime = false;
// 追加属性
protected $append = [
'pv_text'
];
CONST PV_ANDROID = 0;
const PV_IOS = 1;
public static $pvList = [
self::PV_IOS => '苹果平台',
self::PV_ANDROID => '安卓平台',
];
public function getPvTextAttr($value, $data) {
$value = $value ? $value : $data['pv'];
$list = self::$pvList;
return isset($list[$value]) ? $list[$value] : '';
}
}
程序员交流qq群:782974737 点击加入