love_php/app/Http/Controllers/App/OrderController.php
2026-04-09 13:52:20 +08:00

1733 lines
78 KiB
PHP
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

<?php
namespace App\Http\Controllers\App;
use App\Jobs\AddVirtualMember;
use App\Jobs\SaasEarningMPNotice;
use App\Jobs\SendEarningMessage;
use App\Jobs\SendEarningMessageV2;
use App\Jobs\SendTemplateMsg;
use App\Jobs\SyncClientComment;
use App\Models\ConsultAccount;
use App\Models\Course\CourseVideo;
use App\Models\Dma\DmaServiceUserRole;
use App\Models\Dma\S2Customer;
use App\Models\SaasReservationConsultScheduling;
use App\Models\Server\MerchantApplyment;
use App\Models\Server\MerchantEvaluate;
use App\Models\Server\SaasMemberBuyInfo;
use App\Models\Server\SaasMemberLevel;
use App\Models\Server\SaasMemberUser;
use App\Models\Server\ShopAgentOrder;
use App\Models\Wechat;
use App\Services\EvaluateService;
use App\Services\OrderService;
use App\Services\SaasVipGainService;
use App\Services\SaasVipNoticeService;
use App\Services\SaasVipSpreadEarningService;
use App\Services\SaasVipSpreadEarningTestService;
use App\Services\SaasVipSpreadService;
use App\Services\WechatService;
use App\Utils\Messenger as Messengers;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Models\Activity;
use App\Http\Response\ResponseJson;
use App\Models\Order;
use Illuminate\Support\Carbon;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Redis;
use App\Models\Course\UserCourses;
use App\Models\PayOrder;
use App\Models\ConsultationRecords;
use App\Models\Live\AssetLog;
use App\Models\PayLog;
use App\Models\SubRank;
use App\Models\UserCoupon;
use App\Models\Appointment;
use App\Models\AppointmentHistory;
use App\Models\User;
use App\Models\Message;
use App\Models\Live\Anchor;
use App\Repositories\Eloquent\SmsRepository as Sms;
use App\Contracts\OrderContract;
use App\Models\ActivityMember;
use App\Models\SingleService;
use App\Models\Community;
use App\Models\RatioCoin;
use App\Jobs\StoreOrderWorthShare;
use App\Models\CommunityActivity;
use App\Models\Consultation;
use App\Models\Course\Course;
use App\Models\FamilyOrder;
use App\Models\Live\Viewer;
use App\Models\Match\AccessRecord;
use App\Models\MerchantAccount;
use App\Models\MerchantShop;
use App\Models\Server\CollageGroup;
use App\Models\Server\CollageGroupBatch;
use App\Models\Server\CollageGroupHistories;
use App\Models\Server\EvaluateList;
use App\Models\Server\MerchantShareChannel;
use App\Models\Server\MerchantUser;
use App\Models\Server\SaasNotice;
use App\Services\JpushService;
use App\Models\TouristOrder;
use App\Models\UserMember;
use App\Utils\Messenger;
use EasyWeChat\Kernel\Support\XML;
class OrderController extends Controller
{
use ResponseJson;
protected $sms;
protected $orderCon;
public function __construct(Sms $sms, OrderContract $orderCon)
{
$this->sms = $sms;
$this->orderCon = $orderCon;
}
/**
* 回调订单
* @param Request $request [description]
* @param [type] $trade_no [description]
* @return [type] [description]
*/
public function callbackOrder(Request $request, $trade_no)
{
try {
if (empty($trade_no)) {
throw new \Exception("回调接口没有订单号", 1);
}
$order = Order::where('trade_no', $trade_no)->first();
$pay_order = PayOrder::where('trade_no', $trade_no)->first();
if (empty($pay_order)) {
$message = '订单不存在,订单号:' . $trade_no;
throw new \Exception($message, 1);
}
if ($pay_order->is_hooked) {
return $this->failure('订单已经回调');
}
if ($pay_order->cash > 0) {//现金支付
//当前时间大于订单时间30天不能查询
$now_time = date('Y-m-d H:i:s');
$order_time = $pay_order->created_at->toDateTimeString();
$compare_result = $this->compareTime($now_time, $order_time);
if ($compare_result) {
if ($order->pay_type === 'wechat') {
$result = \WechatService::orderPaid($trade_no);
$PayLog = new PayLog;
$PayLog->type = 'activity';
$PayLog->user_id = $order->user_id ?? 0;
$PayLog->trade_no = $trade_no;
$PayLog->remark = '回调监听' . $result;
$PayLog->save();
// $result = true;
} elseif ($order->pay_type === 'alipay') {
//todo 支付宝查询订单
$result = true;
} else {
throw new \Exception("订单检查失败", 1);
}
if (empty($result))
return $this->failure('订单检查失败');
$result = $this->markOrder($order, $pay_order);
if (empty($result))
return $this->failure('分类回调订单失败');
} else {
throw new \Exception("订单时间超过30天", 1);
}
}
$user = User::where('id', $order->user_id)->first();
\CommonUtilsService::sendMiniBuySuccessNoticeToUser($order->goods, 'oPC_2vudkf3stdiNgjA-e2n6t9_M', 'merchant', $order->price, $user->mobile, $user->nickname);
return $this->success('ok');
} catch (\Exception $e) {
$this->getError($e);
return $this->failure('订单回调失败');
}
}
public function callbackBusinessOrder(Request $request, $trade_no)
{
try {
if (empty($trade_no)) {
throw new \Exception("回调接口没有订单号", 1);
}
$order = TouristOrder::where('trade_no', $trade_no)->first();
//$pay_order = PayOrder::where('trade_no', $trade_no)->first();
if (empty($order)) {
$message = '订单不存在,订单号:' . $trade_no;
throw new \Exception($message, 1);
}
if ($order->pay_status) {
return $this->failure('订单已经回调');
}
if ($order->price > 0) {//现金支付
//当前时间大于订单时间30天不能查询
$now_time = date('Y-m-d H:i:s');
$order_time = $order->created_at->toDateTimeString();
$compare_result = $this->compareTime($now_time, $order_time);
if ($compare_result) {
if ($order->pay_type === 'wechat') {
$result = \WechatService::orderPaid($trade_no);
$PayLog = new PayLog;
$PayLog->type = 'activity';
$PayLog->user_id = $order->user_id ?? 0;
$PayLog->trade_no = $trade_no;
$PayLog->remark = '回调监听' . $result;
$PayLog->save();
// $result = true;
TouristOrder::where('trade_no', $order->trade_no)->update(['pay_status' => 1]);
// 给嘉宾编号
if ($order->account_id) {
$remark = $this->numMember($order);
if ($remark)
TouristOrder::where('trade_no', $order->trade_no)->update(['remark' => $remark]);
}
} elseif ($order->pay_type === 'alipay') {
//todo 支付宝查询订单
$result = true;
} else {
throw new \Exception("订单检查失败", 1);
}
if (empty($result))
throw new \Exception("微信端没有订单 订单未支付成功", 1);
if (empty($result))
throw new \Exception("订单回调失败 订单未支付成功", 1);
} else {
throw new \Exception("订单时间超过30天", 1);
}
}
} catch (\Exception $e) {
$this->getError($e);
return $this->failure('订单回调失败');
}
}
public function compareTime($time1, $time2)
{
$str_time1 = strtotime($time1);
$str_time2 = strtotime($time2) + 30 * 24 * 3600;
if ($str_time1 >= $str_time2) {//已過期
return false;
} else {
return true;
}
}
/**
* 分类回调订单
* @param [type] $order [description]
* @param [type] $pay_order [description]
* @return [type] [description]
*/
public function markOrder($order, $pay_order)
{
try {
//会员订单
if ($order->type === 'rank') {
$result = $this->markRankOrder($order, $pay_order);
if (empty($result))
throw new \Exception("回调会员订单失败", 1);
} elseif ($order->type === 'activity') {
$PayLog = new PayLog;
$PayLog->type = 'activity';
$PayLog->user_id = $order->user_id ?? 0;
$PayLog->trade_no = $order->trade_no ?? 0;
$PayLog->remark = '回调活动监听';
$PayLog->save();
$result = $this->markActivityOrder($order, $pay_order);
if (empty($result))
throw new \Exception("回调活动订单失败", 1);
} elseif ($order->type === 'community') {
$result = $this->markCommunityOrder($order, $pay_order);
if (empty($result))
throw new \Exception("回调社群订单失败", 1);
} elseif ($order->type === 'single_service') {
$result = $this->markSingleServiceOrder($order, $pay_order);
if (empty($result))
throw new \Exception("回调单身服务订单失败", 1);
} elseif ($order->type === 'coin') {//福币充值订单
$result = $this->markCoinOrder($order, $pay_order);
if (empty($result))
throw new \Exception("回调福币充值订单失败,订单号:" . $order->trade_no, 1);
} elseif ($order->type === 'course') {//购买课程
$result = $this->markCourses($order, $pay_order);
if (empty($result))
throw new \Exception("回调购买课程订单失败", 1);
}
\DB::beginTransaction();
PayOrder::where('trade_no', $order->trade_no)->update(['is_hooked' => 1, 'pay_status' => 'PAID']);
Order::where('trade_no', $order->trade_no)->update(['pay_status' => 'PAID']);
\DB::commit();
StoreOrderWorthShare::dispatch($order, $pay_order)->onQueue('love');
return true;
} catch (\Exception $e) {
\DB::rollback();
$this->getError($e);
return false;
}
}
/**
* 回调福币充值订单
* @param [type] $order 订单
* @param [type] $pay_order 支付订单
* @return [type] [description]
*/
public function markCoinOrder($order, $pay_order)
{
try {
$ratio_coin = RatioCoin::where('id', $order->type_id)->first();
if (empty($ratio_coin))
throw new \Exception("福币比例不存在", 1);
$user = User::find($order->user_id);
if (empty($user))
throw new \Exception("订单用户不存在", 1);
\DB::beginTransaction();
//增加福币充值记录
$coin = $order->pay_type == 'ios' ? $ratio_coin->ios_coin : $ratio_coin->coin;
$result = $user->addCoinLog('RECHARGE', $order->type_id, $coin);
if (empty($result))
throw new \Exception("增加福币记录失败", 1);
//增加福币余额
$result = $user->updateCoinInfo('add', $coin);
\DB::commit();
return true;
} catch (\Exception $e) {
\DB::rollback();
$this->getError($e);
return false;
}
}
// 回调家与味道
public function familyOrder(Request $request, $trade_no)
{
if (empty($trade_no))
return $this->failure('没有回调订单号');
$PayLog = new PayLog;
$PayLog->type = 'family';
$PayLog->trade_no = $trade_no;
$result = FamilyOrder::where('trade_no', $trade_no)->first();
if (!$result) {
$PayLog->remark = '订单号不存在:' . $trade_no;
$PayLog->save();
return $this->failure('没有回调订单号');
}
if ($result->pay_status == 1) {
$PayLog->remark = '订单已经回调';
$PayLog->save();
return $this->failure('订单已经回调');
}
if ($result->price > 0) {
$PayLog->remark = '订单回调成功';
$PayLog->save();
$result->pay_status = 1;
$result->save();
}
$message = '就在刚刚有位会员购买了《家的味道》礼盒赶紧用电脑访问love.ufutx.com/admin 跟进吧!';
$mobile = 13825210868;
Message::create([
'phone' => $mobile,
'message' => $message,
'confirmed' => 1,
'code' => '家的味道购买通知',
'ip' => request() ? request()->ip() : '127.0.0.1',
]);
Messenger::sendSMS($mobile, $message);
return $this->success('订单回调成功');
}
// 回调 社群-参与活动
public function CommunityOrder(Request $request, $trade_no)
{
try {
if (empty($trade_no)) {
return $this->failure('没有回调订单号');
}
$PayLog = new PayLog;
$result = TouristOrder::where('trade_no', $trade_no)->first();
if (!$result) {
$PayLog->remark = '订单号不存在:' . $trade_no;
$PayLog->save();
return $this->failure('没有回调订单号');
}
if ($result->pay_status != 0) {
$PayLog->trade_no = $trade_no;
$PayLog->remark = '订单已经回调';
$PayLog->save();
return $this->success('订单已经回调');
}
\Log::info('para:' . $request->getcontent());
if (!$result->wechat_transaction_id) {
if ($request->getcontent()) {
try {
$xml = $request->getcontent();
$message = XML::parse($xml);
if ($message && $message['transaction_id']) {
$result->wechat_transaction_id = $message['transaction_id'];
$result->save();
}
} catch (\Exception $e) {
\Log::info('回调出错,信息:' . $request->getcontent());
}
}
}
if ($result->pay_type == "partner") {
$applyment = MerchantApplyment::where('m_id', $result->merchant_id)->first();
$pay_result = \WechatService::partnerOrderPaid($trade_no, $applyment->sub_mch_id);
if (empty($pay_result) || $pay_result->trade_state != "SUCCESS")
return $this->failure("支付回调失败");
} else {
$pay_result = \WechatService::orderPaid($trade_no);
if (empty($pay_result))
return $this->failure("支付回调失败");
}
$merchant = MerchantAccount::where('id', $result->merchant_id)->first();
$merchant_openid = $merchant->openid ?? '';
$usermember = new UserMember();
$usermember->type = $result->type ?? '';
$usermember->type_id = $result->type_id ?? '';
$usermember->m_id = $result->merchant_id ?? '';
$usermember->m_user_id = $result->account_id ?? '';
$usermember->pay_type = 'wechat';
$usermember->trade_no = $trade_no ?? '';
$usermember->save();
if ($result->price > 0 && $result->type == 'community') {
$remark = $this->numMember($result);
$result->remark = $remark;
$PayLog->type = 'Community';
$PayLog->trade_no = $trade_no;
$PayLog->remark = '订单回调成功';
$PayLog->save();
$result->pay_status = 1;
$result->save();//社群活动回调
//发送通知
//判断是服务还是活动
$res = CommunityActivity::where('id', $result->type_id)->first();
if ($res->class == 'one')
$class = 'activity';
if ($res->class == 'many')
$class = 'service';
$merchant_openid = $merchant->openid ?? '';
//多人报名增加手动签到
if ($result->linkmen && count(json_decode($result->linkmen, true)) >= 1) {
AddVirtualMember::dispatch(json_decode($result->linkmen, true), $res, $result)->onQueue('love');
}
// 商家
if (!$merchant_openid) {
$merchant_openid = Anchor::where('id', $res->anchor_id)->value('openid');
}
// 发送给渠道
$channel_openid = null;
if ($result->share_channel_id && $result->share_channel_id != 'null') {
$bind_m_user_id = MerchantShareChannel::where('id', $result->share_channel_id)
->value('bind_m_user_id');
if ($bind_m_user_id) {
$channel_openid = MerchantUser::where('id', $bind_m_user_id)->value('openid');
}
}
// 友福活动将被邀请人添加到客户
$orderService = new OrderService();
$orderService->storeUftxCustomer($result);
}
if ($result->price > 0 && $result->type == 'course') {//课程回调
$PayLog->type = 'course';
$PayLog->trade_no = $trade_no;
$PayLog->remark = '订单回调成功';
$PayLog->save();
\DB::table('courses')->increment('user_count');
UserCourses::where('trade_no', $trade_no)->update(['status' => 1]);
$result->pay_status = 1;
$result->save();
//发送通知
$res = Course::where('id', $result->type_id)->first();
$class = $result->type;
//商户
$merchant_openid = Course::where('id', $result->type_id)->value('open_id');
// 发送给渠道
$channel_openid = null;
if ($result->share_channel_id && $result->share_channel_id != 'null') {
$bind_m_user_id = MerchantShareChannel::where('id', $result->share_channel_id)
->value('bind_m_user_id');
if ($bind_m_user_id) {
$channel_openid = MerchantUser::where('id', $bind_m_user_id)->value('openid');
}
}
}
if ($result->price > 0 && $result->type == 'member') {//saas会员回调
$pay_result = \WechatService::orderPaid($trade_no);
if ($pay_result) {
$member_user = SaasMemberUser::where('merchant_id', $result->merchant_id)
->where('member_level_id', $result->type_id)
->where('merchant_user_id', $result->account_id)
->first();
$level = SaasMemberLevel::where('merchant_id', $result->merchant_id)
->where('id', $result->type_id)
->first();
if ($member_user) {
$expire = Carbon::parse($member_user->expire_time)->timestamp;
if ($expire > Carbon::now()->timestamp) {
$member_user_expire = Carbon::parse($member_user->expire_time)
->addYear($level->level_years)
->addMonths($level->level_month)->toDateTimeString();
$member_user->expire_time = $member_user_expire;
} else {
$member_user->expire_time = Carbon::now()->addYear($level->level_years)
->addMonths($level->level_month)->toDateTimeString();
;
}
$member_user->save();
} else {
$member_user = new SaasMemberUser();
$member_user->merchant_id = $result->merchant_id;
$member_user->merchant_user_id = $result->account_id;
$member_user->member_level_id = $result->type_id;
$member_user_expire = Carbon::parse($result->created_at)->addYear($level->level_years)
->addMonths($level->level_month)->toDateTimeString();
$member_user->expire_time = $member_user_expire;
$member_user->save();
}
$result->pay_status = 1;
$result->save();
//天路合一
if ($result->merchant_id == 1094 || $result->merchant_id == 596) {
//发放未领取权益
$s1 = new SaasVipGainService();
$s1->grantNotUseGain($result);
//收益逻辑
// if($result->merchant_id == 1094){
$s2 = new SaasVipSpreadEarningService();
// }else{
// //测试
// $s2 = new SaasVipSpreadEarningTestService();
// }
$s2->earningLogic($result->id);
}
return 'success';
} else {
\Log::info('回调出错,确认支付异常,信息:' . $request->getcontent());
return $this->failure('回调出错');
}
}
if ($result->price > 0 && $result->type == 'shop') {//商城商品回调
$PayLog->type = 'shop';
$PayLog->trade_no = $trade_no;
$PayLog->remark = '订单回调成功';
$PayLog->save();
$result->pay_status = 1;
$result->save();
//发送通知
$res = MerchantShop::where('id', $result->type_id)->first();
//给用户
$class = $result->type;
//给商户
$merchant_openid = $merchant->openid ?? '';
if (!$merchant_openid) {
$merchant_openid = Anchor::where('m_id', $res->merchant_id)->value('openid');
}
// 发送给渠道
$channel_openid = null;
// 发送给渠道
if ($result->share_channel_id && $result->share_channel_id != 'null') {
$bind_m_user_id = MerchantShareChannel::where('id', $result->share_channel_id)
->value('bind_m_user_id');
if ($bind_m_user_id) {
$channel_openid = MerchantUser::where('id', $bind_m_user_id)->value('openid');
}
}
}
if ($result->price > 0 && $result->type == 'evaluate') {//评测回调
$res = MerchantEvaluate::where('id', $result->type_id)->first();
$PayLog->remark = '订单回调成功';
$PayLog->type = 'evaluate';
$PayLog->trade_no = $trade_no;
$PayLog->save();
$result->pay_status = 1;
$result->save();
EvaluateService::testUpdate($trade_no);
$class = 'evaluate';
// 发送给渠道
$channel_openid = null;
// 发送给渠道
if ($result->share_channel_id && $result->share_channel_id != 'null') {
$bind_m_user_id = MerchantShareChannel::where('id', $result->share_channel_id)
->value('bind_m_user_id');
if ($bind_m_user_id) {
$channel_openid = MerchantUser::where('id', $bind_m_user_id)->value('openid');
}
}
}
if ($result->price > 0 && $result->type == 'consult') {//评测拼团回调
$res = Consultation::where('id', $result->type_id)->first();
$PayLog->remark = '订单回调成功';
$PayLog->type = 'consult';
$PayLog->trade_no = $trade_no;
$PayLog->save();
$result->pay_status = 1;
$result->save();
$class = 'consult';
// 发送给渠道
$channel_openid = null;
// 发送给渠道
if ($result->share_channel_id && $result->share_channel_id != 'null') {
$bind_m_user_id = MerchantShareChannel::where('id', $result->share_channel_id)
->value('bind_m_user_id');
if ($bind_m_user_id) {
$channel_openid = MerchantUser::where('id', $bind_m_user_id)->value('openid');
}
}
}
if ($result->merchant_id != 388) {
//发送收益通知(未到账)
SendEarningMessageV2::dispatch($result->id)->onqueue('order');
}
//同步备注
SyncClientComment::dispatch($result)->onQueue('love');
if ($result->group_id) {//是否成团
$history = CollageGroupHistories::where('m_order_id', $result->id)->first();
$group = CollageGroup::where('id', $result->group_id)->first();
if (!$history || !$group) {
//出错了
}
$param = $this->getGroupParams($result, $group, $history->deadline, 0);
if ($history->is_initiator == 1) {//是团长 发送开团通知
CollageGroupBatch::create(['history_id' => $history->id, 'batch' => $history->id]);
\WechatService::stratGroupNotice($param);
} else {//是团员 发送参团通知
$history_i_id = CollageGroupHistories::where('group_id', $result->group_id)->where('is_initiator', 1)
->where('deadline', $history->deadline)->value('id');
CollageGroupBatch::create(['history_id' => $history->id, 'batch' => $history_i_id]);
\WechatService::sendJoinGroupNotice($param);
}
$m_order_ids = CollageGroupHistories::where('group_id', $history->group_id)
->where('deadline', $history->deadline)->pluck('m_order_id')->toArray();
// 目前参与人员数量
$num = TouristOrder::whereIn('id', $m_order_ids)->whereIn('pay_status', [1, 4])->get()->count();
if ($group->require_num == $num) {
CollageGroupHistories::whereIn('m_order_id', $m_order_ids)->update(['status' => 1]);
//本次拼团成功(给所有拼团人员发)
$notice_users = TouristOrder::whereIn('id', $m_order_ids)->whereIn('pay_status', [1, 4])->get();
foreach ($notice_users as $notice_user) {
$param = $this->getGroupParams($notice_user, $group, $history->deadline, 1);
\WechatService::sendJoinGroupNotice($param);
}
}
}
// 给用户
\CommonUtilsService::sendBuySuccessNoticeToUser($res, $result->open_id, $class, $trade_no, $result->price);
if ($result->channel == 0) {
//发送商户
\CommonUtilsService::sendBuySuccessNoticeToBusiness($res, $merchant_openid, 'merchant', $result->price, $result->mobile, $result->name);
}
if ($result->merchant_id == 491) {
//给客服脱单姐 管理员
$openids = [
"oPC_2vn6Q3M5jQpw9xAS7NNCMfjs",
"oPC_2vudkf3stdiNgjA-e2n6t9_M",
"oPC_2vtrwOLgWHLwVEFTFsJ7N7fw",
"oPC_2vt7nGwKk_OFzJL70SlVuTiU",
"oPC_2vg_Eur-Wa_Vwnx9JiyRVn9Q
"
];
foreach ($openids as $openid) {
\CommonUtilsService::sendBuySuccessNoticeToBusiness($res, $openid, 'merchant', $result->price, $result->mobile, $result->name);
}
}
//发送推荐人
if ($result->from_openid && $result->from_openid != 'null') {
\CommonUtilsService::sendBuySuccessNoticeToBusiness($res, $result->from_openid, 'recommend', $result->price, $result->mobile, $result->name);
}
// 首邀
$first_invitation = AccessRecord::where('open_id', $result->open_id)->where('account_id', $result->merchant_id)->value('from_openid');
if ($first_invitation && $first_invitation != $result->from_openid) {
\CommonUtilsService::sendBuySuccessNoticeToBusiness($res, $first_invitation, 'first_invitation', $result->price, $result->mobile, $result->name);
}
// 渠道
if ($result->channel == 0 && $channel_openid) {
\CommonUtilsService::sendBuySuccessNoticeToBusiness($res, $channel_openid, 'channel', $result->price, $result->mobile, $result->name);
}
// app消息推送
if (isset($merchant->info->android_id)) {
// 推送平台 ios android
$params['platform'] = 'android';
// 推送标题
$params['title'] = '收到新订单提醒通知';
// 推送内容
$params['content'] = $res->title . '收到付款' . $result->price . '元';
// 通知栏样式 ID
$params['builderId'] = 1;
// 唤醒APP
$params['intent'] = ['url' => 'intent:#Intent;action=com.love.ufutx.saas.ui.main.MainActivity;component=com.love.ufutx.saas/com.love.ufutx.saas.ui.main.MainActivity;end'];
$params['uri_activity'] = 'com.love.ufutx.saas.ui.main.MainActivity';
$params['uri_action'] = 'com.love.ufutx.saas.ui.main.MainActivity';
// 附加字段(这里自定义 Key / value 信息,以供业务使用)
$params['extras'] = [
'url' => 'https://love.ufutx.com/pu_m/#/orderDetail/' . $result->id . '?type=' . $result->type . '&equipmentType=android',
];
// 推送类型 1-别名 2-注册id 3-全部
$params['type'] = 2;
// 注册ID 可以是单个 也可以是 数组
$params['registrationId'] = $merchant->info->android_id;
// 开始推送
JpushService::androidOrIosPushByAlias($params);
}
$redis = Redis::connection('big_data');
Log::info('checkEarningOrder earning:order:ids ' . $result->id);
$redis->lpush('earning:order:ids', $result->id);
//短信通知商家
$jump_url = env('APP_URL') . '/pu_m/#/earningsRecord?merchant_id=' . $merchant->id;
$short_url = \CommonUtilsService::shortUrl(env('APP_URL') . '/h5/#/jump_url?url=' . $jump_url);
$title = $res->title;
if (mb_strlen($title) > 5) {
$title = mb_substr($title, 0, 5, 'utf-8') . '...';
}
$message = '有用户下单了~ ' . $result->name . '购买了平台的《' . $title . '》' . $result->price . '元,点击' . $short_url['url'] . ' 查看详情';
if ($merchant->mobile) {
Messenger::sendSMS($merchant->mobile, $message);
//增加记录
Message::create([
'phone' => $merchant->mobile,
'message' => $message,
'confirmed' => 1,
'code' => '购买通知',
'ip' => request() ? request()->ip() : '127.0.0.1',
]);
}
// 发送短信给渠道分享人
if ($result->share_channel_id && $result->share_channel_id != 'null') {
$share_channel = MerchantShareChannel::where('id', $result->share_channel_id)->first();
if (!empty($share_channel)) {
$merchant_user = MerchantUser::where('id', $share_channel->bind_m_user_id)->first();
if ($merchant_user && $merchant_user->mobile) {
$share_message = 'Hi' . $merchant_user->nickname . ',刚刚有人通过你的渠道「' . $share_channel->title . '」购买了' . $res->title;
Messenger::sendSMS($merchant_user->mobile, $share_message);
}
}
}
//插入购买通知
// $pay_name = $result->user ? $result->user->nickname : '匿名用户';
$content = $result->name . '购买了【' . $res->title . '】查看订单详情>>';
SaasNotice::addRecord($result->merchant_id, $result->account_id, 'order', $result->id, $content, 0);
if ($result->user_coupon_id) {
$user_coupon = UserCoupon::where('id', $result->user_coupon_id)->update(['status' => 1]);
}
Log::info("订单类型:{$result->type}, 类型id:{$result->type_id}");
if ($result->type == "community" && $result->type_id == 2451) {//通知企业微信
Log::info("活动报名通知企业微信");
$this->wechatWorkNotice($result);
}
return $this->success('ok');
} catch (\Exception $e) {
$this->getError($e);
return $this->failure();
}
}
public function wechatWorkNotice($order)
{
$header = "2024开年餐宴·早鸟票\r\n";
$line = "-----------------------\r\n";
$omit = "...\r\n";
$orders = TouristOrder::whereIn("pay_status", [1, 4])->where("type", $order->type)->where('type_id', $order->type_id)
->where('id', '<=', $order->id)->orderByDesc('id')->limit(3)->get();
$count = TouristOrder::whereIn("pay_status", [1, 4])->where("type", $order->type)->where('type_id', $order->type_id)->where('id', '<=', $order->id)->count();
if (empty($orders))
return;
$index = 0;
foreach ($orders as $order) {
$linkmen = json_decode($order->linkmen, true);
$linkmen_num = $linkmen ? count($linkmen) : 0;
$num = $count - $index;
$name = $linkmen[0]['name'] ?? $order->name;
$introduce_name = MerchantUser::where('openid', $order->from_openid)->value('nickname');
$name_arr[] = "{$num}:{$name} {$linkmen_num} 介绍人 {$introduce_name}\r\n";
$index++;
}
$name_arr = array_reverse($name_arr);
$name_str = implode('', $name_arr);
$img = "[使用微信扫码报名](https://images.ufutx.com/202401/20/17057172010lSjM8preview.png)\r\n";
$url = "[查看订单列表](https://health.ufutx.com/work/#/h5/activityOrder?id={$order->type_id})\r\n";
$send_data = [
'msgtype' => 'markdown',
'markdown' => [
'content' => $header . $line . $omit . $omit . $omit . $name_str . $line . $img . $url,
]
];
//正式
$url = "https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=905fe4d1-a681-4133-b847-0be2d290477c";
//测试
// $url = "https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=ec3c5836-42cf-4a7d-98c4-4e5c544d0612";
$response = \App\Utils\Http::post($url, json_encode($send_data));
}
public function getGroupParams($order, $group, $deadline, $status = 0)
{
$history_id = CollageGroupHistories::where('m_order_id', $order->id)->value('id');
$param['openid'] = $order->open_id;
$param['order_id'] = $order->id;
$param['title'] = $order->desc;
$param['price'] = $order->price . '元';
$param['num'] = $group->require_num . '人';
$param['deadline'] = $deadline;
//发送给团员的温馨提示
$param['team_desc'] = '您已成功参与拼团,具体拼团成败请留意通知';
//发送给团张的温馨提示
$param['lead_desc'] = '本团有效期为' . $group->expire_in . '小时 赶紧邀请好友来拼团吧';
$param['desc'] = '恭喜你,本次拼团已成功';
$param['status'] = $status;
$param['history_id'] = $history_id;
return $param;
}
//拼团订单回调
public function groupOrder(Request $request, $trade_no)
{
if (empty($trade_no)) {
return $this->failure('没有回调订单号');
}
$result = TouristOrder::where('trade_no', $trade_no)->first();
$log = new PayLog;
$log->type = 'group';
$log->trade_no = $trade_no;
if (!$result) {
$log->remark = '订单号不存在:' . $trade_no;
$log->save();
return $this->failure('没有回调订单号');
}
if ($result->pay_status == 1 || $result->pay_status == 4) {
$log->remark = '订单已经回调';
$log->save();
return $this->failure('订单已经回调');
}
if ($result->price <= 0) {
$log->remark = '订单回调成功';
$log->save();
$result->pay_status = 1;
$result->save();
}
if ($result->pay_type == "partner") {
$applyment = MerchantApplyment::where('m_id', $result->merchant_id)->first();
$pay_result = \WechatService::partnerOrderPaid($trade_no, $applyment->sub_mch_id);
if (empty($pay_result) || $pay_result->trade_state != "SUCCESS")
return $this->failure("支付回调失败");
} else {
$pay_result = \WechatService::orderPaid($trade_no);
if (empty($pay_result))
return $this->failure("支付回调失败");
}
$log->remark = '订单回调成功';
$log->save();
$result->pay_status = 1;
$result->save();
$history = CollageGroupHistories::where('m_order_id', $result->id)->first();
if ($history->is_initiator) {
$collageGroupBatch = new CollageGroupBatch();
$collageGroupBatch->history_id = $history->id;
$collageGroupBatch->batch = $history->id;
$collageGroupBatch->save();
} else {
$collageGroupBatch = new CollageGroupBatch();
$collageGroupBatch->history_id = $history->id;
$collageGroupBatch->batch = $history->group_master_id;
$collageGroupBatch->save();
}
$history_ids = CollageGroupBatch::where('batch', $history->group_master_id)->pluck('history_id')->toArray();
$num = sizeof($history_ids);
$group = CollageGroup::where('id', $result->group_id)->first();
if ($num >= $group->require_num) {
CollageGroupHistories::whereIn('id', $history_ids)->update(['status' => 1]);
$order_ids = CollageGroupHistories::whereIn('id', $history_ids)->pluck('m_order_id');
$orders = TouristOrder::whereIn('id', $order_ids)->whereIn('pay_status', [1, 4])
->where('group_id', $history->group_id)
->get();
foreach ($orders as $order) {
if ($result->type == 'course') {
if (!$history->group_master_id) {
continue;
}
switch ($order->channel) {
case 0:
$jump_url = urlencode(env('APP_URL') . '/pu/#/courseDetail/' . $group->type_id);
$url = env('APP_URL') . '/api/official/live/wechat/FamilyAuth?merchant_id=' . $order->merchant_id .
'&anchor_openid=&url=' . $jump_url;
$first = "您的拼团订单已成功拼团!";
$param = [
'touser' => $order->open_id,
'template_id' => config('wechat.tpls.buy_success_notice'),
'url' => $url,
'data' => [
'first' => $first,
'keyword1' => $order->desc,
'keyword2' => $order->trade_no,
'keyword3' => "" . $order->price,
'keyword4' => $order->created_at->toDateTimeString(),
'remark' => '点击详情可查看课程',
]
];
Log::info('订单ID=' . $trade_no . '发起拼团通知');
//通知用户
SendTemplateMsg::dispatch($param)->onQueue("love");
break;
}
}
}
switch ($group->type) {
case 'course':
foreach ($orders as $order) {
UserCourses::where('trade_no', $order->trade_no)->update(['status' => 1]);
}
break;
}
}
if ($result->price > 0 && $result->type == 'community') {
$res = CommunityActivity::where('id', $result->type_id)->first();
}
if ($result->price > 0 && $result->type == 'course') {//课程回调
$res = Course::where('id', $result->type_id)->first();
}
if ($result->merchant_id == 491) {
//给客服脱单姐
// \CommonUtilsService::sendBuySuccessNoticeToBusiness($res,'oPC_2vudkf3stdiNgjA-e2n6t9_M','merchant',$result->price,$result->mobile,$result->name);
$openids = [
"oPC_2vn6Q3M5jQpw9xAS7NNCMfjs",
"oPC_2vudkf3stdiNgjA-e2n6t9_M",
"oPC_2vtrwOLgWHLwVEFTFsJ7N7fw",
"oPC_2vt7nGwKk_OFzJL70SlVuTiU",
"oPC_2vg_Eur-Wa_Vwnx9JiyRVn9Q
"
];
foreach ($openids as $openid) {
\CommonUtilsService::sendBuySuccessNoticeToBusiness($res, $openid, 'merchant', $result->price, $result->mobile, $result->name);
}
}
return $this->success('ok');
}
// 回调咨询订单
public function consultation(Request $request, $trade_no)
{
if (empty($trade_no))
return $this->failure('没有回调订单号');
$PayLog = new PayLog;
$PayLog->type = 'Consultation';
$PayLog->trade_no = $trade_no;
$result = ConsultationRecords::where('trade_no', $trade_no)->first();
$config = TouristOrder::where('trade_no', $trade_no)->first();
if ($config->pay_type == "partner") {
$applyment = MerchantApplyment::where('m_id', $config->merchant_id)->first();
$pay_result = \WechatService::partnerOrderPaid($trade_no, $applyment->sub_mch_id);
if (empty($pay_result) || $pay_result->trade_state != "SUCCESS")
return $this->failure("支付回调失败");
} else {
$pay_result = \WechatService::orderPaid($trade_no);
if (empty($pay_result))
return $this->failure("支付回调失败");
}
$scheduling = SaasReservationConsultScheduling::where('id', $result->scheduling_id)
->where('merchant_id', $result->merchant_id)
->first();
if (!$result) {
$PayLog->remark = '订单号不存在:' . $trade_no;
$PayLog->save();
return $this->failure('没有回调订单号');
}
if ($result->pay_status == 1) {
$PayLog->remark = '订单已经回调';
$PayLog->save();
return $this->failure('订单已经回调');
}
if ($result->price > 0) {
$PayLog->remark = '订单回调成功';
$PayLog->save();
$result->pay_status = 1;
// $result->save();
$config->pay_status = 1;
$config->save();
}
//是否有选择指定预约时间段
if ($scheduling) {
$scheduling->decrement('residue_num', 1);
$result->reservation_time = "{$scheduling->date} {$scheduling->date_range}";
}
$result->save();
if ($config->user_coupon_id) {
$user_coupon = UserCoupon::query()->find($config->user_coupon_id);
if ($user_coupon) {
$user_coupon->status = 1;
$user_coupon->save();
}
}
if ($config->group_id) {//是否成团
$history = CollageGroupHistories::where('m_order_id', $config->id)->first();
$group = CollageGroup::where('id', $config->group_id)->first();
if (!$history || !$group) {
//出错了
}
$param = $this->getGroupParams($config, $group, $history->deadline, 0);
if ($history->is_initiator == 1) {//是团长 发送开团通知
CollageGroupBatch::create(['history_id' => $history->id, 'batch' => $history->id]);
\WechatService::stratGroupNotice($param);
} else {//是团员 发送参团通知
$history_i_id = CollageGroupHistories::where('group_id', $config->group_id)->where('is_initiator', 1)
->where('deadline', $history->deadline)->value('id');
CollageGroupBatch::create(['history_id' => $history->id, 'batch' => $history_i_id]);
\WechatService::sendJoinGroupNotice($param);
}
$m_order_ids = CollageGroupHistories::where('group_id', $history->group_id)
->where('deadline', $history->deadline)->pluck('m_order_id')->toArray();
// 目前参与人员数量
$num = TouristOrder::whereIn('id', $m_order_ids)->whereIn('pay_status', [1, 4])->get()->count();
if ($group->require_num == $num) {
CollageGroupHistories::whereIn('m_order_id', $m_order_ids)->update(['status' => 1]);
//本次拼团成功(给所有拼团人员发)
$notice_users = TouristOrder::whereIn('id', $m_order_ids)->whereIn('pay_status', [1, 4])->get();
foreach ($notice_users as $notice_user) {
$param = $this->getGroupParams($notice_user, $group, $history->deadline, 1);
\WechatService::sendJoinGroupNotice($param);
}
}
}
$redis = Redis::connection('big_data');
Log::info('checkEarningOrder earning:order:ids ' . $config->id);
$redis->lpush('earning:order:ids', $config->id);
$way = 'consulation';
$type = 'merchant';
//通知用户
$res = Consultation::where('id', $result->consulation_id)->first();
$user_openid = $config->open_id;
$merchant = MerchantAccount::where('id', $result->merchant_id)->first();
$merchant_openid = $merchant->openid;
if (empty($merchant_openid))
$merchant_openid = Anchor::where('m_id', $merchant->id)->value('openid');
\CommonUtilsService::sendBuySuccessNoticeToUser($res, $user_openid, $way, $trade_no, $result->price);
//通知商户
\CommonUtilsService::sendBuySuccessNoticeToBusiness($res, $merchant_openid, $type, $result->price, $result->phone, $result->name);
//发送推荐人
if ($result->from_open_id && $result->from_open_id != 'null') {
$type = 'recommend';
\CommonUtilsService::sendBuySuccessNoticeToBusiness($res, $result->from_open_id, $type, $result->price, $result->mobile, $result->name);
}
// 首邀
$first_invitation = AccessRecord::where('open_id', $result->open_id)->where('account_id', $result->merchant_id)->value('from_openid');
if ($first_invitation && $first_invitation != $result->from_openid) {
$way = 'first_invitation';
\CommonUtilsService::sendBuySuccessNoticeToBusiness($res, $first_invitation, $way, $result->price, $result->mobile, $result->name);
}
// 发送给渠道
if ($result->share_channel_id && $result->share_channel_id != 'null') {
$way = 'channel';
$share_channel = MerchantShareChannel::where('id', $result->share_channel_id)->first();
$bind_m_user_id = $share_channel->bind_m_user_id;
if ($bind_m_user_id) {
$merchant_user = MerchantUser::where('id', $bind_m_user_id)->first();
if ($merchant_user->openid) {
\CommonUtilsService::sendBuySuccessNoticeToBusiness($res, $merchant_user->openid, $way, $result->price, $result->mobile, $result->name);
}
if ($merchant_user->mobile) {
$share_message = 'Hi' . $merchant_user->nickname . ',刚刚有人通过你的渠道「' . $share_channel->title . '」购买了' . $res->title;
$this->sentMessage($merchant_user->mobile, $share_message);
}
}
}
// app消息推送
if (isset($merchant->info->android_id)) {
// 推送平台 ios android
$params['platform'] = 'android';
// 推送标题
$params['title'] = '收到新订单提醒通知';
// 推送内容
$params['content'] = $res->title . '收到付款' . $result->price . '元';
// 通知栏样式 ID
$params['builderId'] = 1;
// 唤醒APP
$params['intent'] = ['url' => 'intent:#Intent;action=com.love.ufutx.saas.ui.main.MainActivity;component=com.love.ufutx.saas/com.love.ufutx.saas.ui.main.MainActivity;end'];
$params['uri_activity'] = 'com.love.ufutx.saas.ui.main.MainActivity';
$params['uri_action'] = 'com.love.ufutx.saas.ui.main.MainActivity';
// 附加字段(这里自定义 Key / value 信息,以供业务使用)
$params['extras'] = [
'url' => 'https://love.ufutx.com/pu_m/#/orderDetail/' . $config->id . '?type=' . $config->type . '&equipmentType=android',
];
// 推送类型 1-别名 2-注册id 3-全部
$params['type'] = 2;
// 注册ID 可以是单个 也可以是 数组
$params['registrationId'] = $merchant->info->android_id;
// 开始推送
JpushService::androidOrIosPushByAlias($params);
}
//短信通知商家
$jump_url = env('APP_URL') . '/pu_m/#/earningsRecord?merchant_id=' . $merchant->id;
$short_url = \CommonUtilsService::shortUrl(env('APP_URL') . '/h5/#/jump_url?url=' . $jump_url);
$title = $res->title;
if (mb_strlen($title) > 5) {
$title = mb_substr($title, 0, 5, 'utf-8') . '...';
}
$message = '有用户下单了~ ' . $config->name . '购买了平台的《' . $title . '》' . $config->price . '元,点击' . $short_url['url'] . ' 查看详情';
if ($merchant->mobile) {
Messenger::sendSMS($merchant->mobile, $message);
//增加记录
Message::create([
'phone' => $merchant->mobile,
'message' => $message,
'confirmed' => 1,
'code' => '购买通知',
'ip' => request() ? request()->ip() : '127.0.0.1',
]);
}
//插入购买通知
// $pay_name = $result->user ? $result->user->nickname : '匿名用户';
$content = $result->name . '购买了【' . $res->title . '】查看订单详情>>';
SaasNotice::addRecord($result->merchant_id, $result->account_id, 'order', $result->id, $content, 0);
//通知老师
// if ($result->merchant_id != 596){
// return;
// }
$consult_account = ConsultAccount::find($res->consult_account_id);
if ($consult_account && $consult_account->mobile) {
//公众号
$content = "有用户下单了【{$res->title}】咨询。";
$teacher = MerchantUser::where('mobile', $consult_account->mobile)->first();
if ($teacher && $teacher->openid) {
\CommonUtilsService::consultCustomNotice(
$teacher->openid,
'',
$config->name,
"{$scheduling->date} {$scheduling->date_range}",
$content
);
}
//短信
$content = "咨询预约通知:有用户下单了【{$res->title}】咨询。";
if ($scheduling) {
$content .= "预约时间{$scheduling->date} {$scheduling->date_range}";
}
Message::create([
'phone' => $consult_account->mobile,
'message' => $content,
'confirmed' => 1,
'ip' => request() ? request()->ip() : '127.0.0.1',
]);
Messengers::sendSMS($consult_account->mobile, $content);
}
}
/**
* 回调会员订单
* @param [type] $order [description]
* @param [type] $pay_order [description]
* @return [type] [description]
*/
public function markRankOrder($order, $pay_order)
{
try {
\DB::beginTransaction();
$user = User::find($order->user_id);
if ($pay_order->score > 0) {
//扣除对应积分
$score = $pay_order->score;
$result = $this->orderCon->changeAsset($user, $score);
if (empty($result)) {
\DB::rollback();
throw new \Exception("订单回调失败,福气溢出,订单号:" . $order->trade_no, 1);
}
}
//更改会员
$month = SubRank::where('id', $order->type_id)->value('month');
$result = $user->addSuperRank($day = 0, $month, $type = 'RECSYSTEM');
if (empty($result)) {
\DB::rollback();
throw new \Exception("订单回调失败,更改会员等级失败,订单号:" . $order->trade_no, 1);
}
\DB::commit();
return true;
} catch (\Exception $e) {
\DB::rollback();
$this->getError($e);
return false;
}
}
/**
* 回调活动订单
* @param [type] $order [description]
* @param [type] $pay_order [description]
* @return [type] [description]
*/
public function markActivityOrder($order, $pay_order)
{
try {
\DB::beginTransaction();
$user = User::where('id', $order->user_id)->first();
//扣除福气
if ($pay_order->score > 0) {
//扣除对应积分
$score = $pay_order->score;
$result = $this->orderCon->changeAsset($user, $score);
if (empty($result)) {
\DB::rollback();
throw new \Exception("订单回调失败,福气溢出,订单号:" . $order->trade_no, 1);
}
}
//生成活动成员
$member = new ActivityMember;
$member->user_id = $order->user_id;
$member->activity_id = $order->type_id;
$member->is_joined = 1;
$member->name = $user->name;
$member->mobile = $user->mobile;
$member->avatar = $user->photo;
$member->linkmen = $order->linkmen;
$member->sex = $user->sex;
$member->save();
//通知给管理员
$activity = Activity::findOrFail($order->type_id);
$this->sendActivityNotice($activity, $user);
\DB::commit();
return true;
} catch (\Exception $e) {
\DB::rollback();
$this->getError($e);
return false;
}
}
/**
* 公众号模板消息通知管理员
*/
public function sendActivityNotice($activity, $user)
{
$param['title'] = $activity->theme;
$param['user_name'] = $user->nickname;
$param['user_mobile'] = $user->mobile;
$param['start_time'] = $activity->start_time;
$param['address'] = $activity->province . $activity->city . $activity->dist . $activity->address;
$param['openid'] = 'oPC_2vudkf3stdiNgjA-e2n6t9_M';
$param['activity_id'] = $activity->id;
\WechatService::activitySuccessNotice($param);
return;
}
/**
* 回调社群接口
* @param [type] $order [description]
* @param [type] $pay_order [description]
* @return [type] [description]
*/
public function markCommunityOrder($order, $pay_order)
{
try {
\DB::beginTransaction();
$user = User::where('id', $order->user_id)->first();
//扣除福气
if ($pay_order->score > 0) {
//扣除对应积分
$score = $pay_order->score;
$result = $this->orderCon->changeAsset($user, $score);
if (empty($result)) {
\DB::rollback();
throw new \Exception("订单回调失败,福气溢出,订单号:" . $order->trade_no, 1);
}
}
$community = Community::find($order->type_id);
if (empty($community)) {
\DB::rollback();
throw new \Exception("社区不存在,订单号:" . $order->trade_no, 1);
}
//生成社群成员并且邀请进入IM群
$member = $community->members()->firstOrCreate([
'user_id' => $user->id,
'status' => 1
]);
//添加会员数
$community->increment('member_num', 1);
//拉入群聊
$result = $community->addIntoIMGroup([$user->id]);
if (empty($result)) {
\DB::rollback();
throw new \Exception("加入IM群失败订单号:" . $order->trade_no, 1);
}
\DB::commit();
return true;
} catch (\Exception $e) {
\DB::rollback();
$this->getError($e);
return false;
}
}
/**
* 回调购买课程
*/
public function markCourses($order, $pay_order)
{
try {
\DB::beginTransaction();
$user = User::where('id', $order->user_id)->first();
//更新订单表信息
$order->pay_status = 'PAID';
//扣除优惠券
if ($order->remark && $order->price == 0) {
UserCoupon::where('id', $order->type_id)->Where('user_id', $user->id)->update(['status' => 1]);
}
$order->save();
$pay_order->pay_status = 'PAID';
$pay_order->save();
\DB::table('courses')->increment('user_count');
UserCourses::where('trade_no', $pay_order->trade_no)->update(['status' => 1]);
\DB::commit();
return true;
} catch (\Exception $e) {
\DB::rollback();
$this->getError($e);
return false;
}
}
/**
* 回调单身服务套餐订单
* @param [type] $order [description]
* @param [type] $pay_order [description]
* @return [type] [description]
*/
public function markSingleServiceOrder($order, $pay_order)
{
try {
\DB::beginTransaction();
$user = User::where('id', $order->user_id)->first();
//扣除福气
if ($pay_order->score > 0) {
//扣除对应积分
$score = $pay_order->score;
$result = $this->orderCon->changeAsset($user, $score);
if (empty($result)) {
\DB::rollback();
throw new \Exception("订单回调失败,福气溢出,订单号:" . $order->trade_no, 1);
}
}
//查询服务
$service = SingleService::where('id', $order->type_id)->first();
if (empty($service)) {
throw new \Exception("单身服务不存在,订单号:" . $order->trade_no, 1);
}
// //生成服务记录
// $this->addServiceHistory($user->id, $service->type, $service->type_id);
//添加会员期限
$month = $service->rank_month;
$result = $user->addSuperRank($day = 0, $month);
if (empty($result)) {
throw new \Exception("修改用户会员失败,订单号:" . $order->trade_no, 1);
}
//短信通知艳斌
if (config('app.env') == 'production') {
if ($service->type == 'active' || $service->type == 'passive') {
$user_name = $user->nickname;
$message = '用户' . $user_name . '购买了' . $service->title . '服务';
$this->sms->sentMessage('13377553550', $message);
//短信通知购买服务用户
$notice = '您已成功购买【' . $service->title . '】服务套餐福恋工作人员将尽快联系您为您服务请耐心等待。如有问题请联系18922809346';
$this->sms->sentMessage($user->mobile, $notice);
}
}
\DB::commit();
return true;
} catch (\Exception $e) {
\DB::rollback();
$this->getError($e);
return false;
}
}
/**
* 添加购买服务记录
*/
public function addServiceHistory($user_id, $type, $type_id)
{
$appointment = Appointment::where('type', $type)->where('id', $type_id)->first();
if (empty($appointment)) {
return;
}
AppointmentHistory::create([
'user_id' => $user_id,
'point_id' => $appointment->id,
'price' => $appointment->price,
'type' => $type,
'num' => $appointment->num,
]);
return;
}
/**
* 充值福币
* @param Request $request [description]
* @param [type] $coin_id [description]
* @return [type] [description]
*/
public function rechargeCoin(Request $request, $coin_id)
{
try {
$ratio_coin = RatioCoin::find($coin_id);
if (empty($ratio_coin))
throw new \Exception("福币比例不存在", 1);
$os = request()->header('client_os');
if ($os == 'IOS') {
$goods = '充值' . $ratio_coin->ios_coin . '个福币';
} else {
$goods = '充值' . $ratio_coin->coin . '个福币';
}
$result = $this->orderCon->makeAppOrder($request, $ratio_coin->price, $type = 'coin', $coin_id, $goods, $linkmen = [], $detail = '');
if (empty($result))
throw new \Exception("支付订单生成失败", 1);
return $this->success('ok', $result);
} catch (\Exception $e) {
$this->getError($e);
return $this->failure('充值福币失败,请稍后再试');
}
}
/**
* @param Request $request
* @return \Illuminate\Http\JsonResponse
* @des ios内购支付回调
*/
public function iosNotify(Request $request)
{
try {
//苹果内购的验证收据
$receipt_data = $request->input('apple_receipt');
$trade_no = $request->input('trade_no');
$order = Order::where('trade_no', $trade_no)->first();
$pay_order = PayOrder::where('trade_no', $trade_no)->first();
if (empty($order) || empty($pay_order)) {
return $this->failure('订单不存在');
}
if (empty($receipt_data)) {
return $this->failure('参数错误');
}
if (!$order || $order->pay_status != 'UNPAID') {
return $this->failure('订单状态异常');
}
if ($receipt_data) {
$result = PayOrder::where('id', $pay_order->id)->update(['receipt' => $receipt_data]);
}
\DB::beginTransaction();
$ios_sandBox = $request->input('ios_sandBox');//判断生产环境,开发环境
// 获取校验结果
$result = $this->validate_apple_pay($receipt_data, $ios_sandBox);
if (!$result || !is_array($result) || !isset($result['status'])) {
return $this->failure('获取数据失败,请重试');
}
//如果校验失败
if ($result['status'] != 0) {
\DB::commit();
return $this->failure('miss [apple_receipt]');
}
if ($result['status'] == 0) {
$transaction_ids = [];//用来收集需要关闭的transaction_id
//遍历未结束交易的列表in_app
foreach ($result['receipt']['in_app'] as $v) {
$order_product_id = $this->getOrderProductId($order);
$product_id = $v['product_id'];
if ($order_product_id != $product_id)
throw new \Exception("产品id不一致", 1);
$transaction_ids[] = $v['transaction_id'];//不管当前交易是否已经处理过,都要返回给客户端结束交易
$is_exist = \DB::table('ios_transaction_ids')->where('transaction_id', $v['transaction_id'])->first();
if ($is_exist) {
//如果已经处理过该订单 直接跳过
continue;
}
//否则在此处理业务逻辑
//回调订单
$result = $this->markOrder($order, $pay_order);
if (empty($result))
throw new \Exception("回调内购订单失败", 1);
//然后记录下此transaction_id标记为已处理过
\DB::table('ios_transaction_ids')->insert([
'trade_no' => $trade_no,
'transaction_id' => $v['transaction_id'],
'created_at' => date('Y-m-d H:i:s'),
'updated_at' => date('Y-m-d H:i:s')
]);
}
\DB::commit();
//返回给客户端需要结束交易的transaction_id列表
return $this->success('ok', $transaction_ids);
}
\DB::commit();
} catch (\Exception $e) {
\DB::rollback();
$this->getError($e);
return $this->failure('内购回调失败');
}
}
public function getOrderProductId($order)
{
$order_product_id = '';
switch ($order->type) {
case 'rank':
$order_product_id = 'com.ufutx.love.buyVip' . (int) $order->price . 'yuan';
break;
case 'coin':
$order_product_id = 'com.ufutx.love.recharge' . (int) $order->price . 'yuan';
break;
default:
# code...
break;
}
return $order_product_id;
}
/**
* 验证AppStore内付
* @param string $receipt_data 付款后凭证
* @return array 验证是否成功
*/
protected function validate_apple_pay($receipt_data, $ios_sandBox)
{
/**
* 21000 App Store不能读取你提供的JSON对象
* 21002 receipt-data域的数据有问题
* 21003 receipt无法通过验证
* 21004 提供的shared secret不匹配你账号中的shared secret
* 21005 receipt服务器当前不可用
* 21006 receipt合法但是订阅已过期。服务器接收到这个状态码时receipt数据仍然会解码并一起发送
* 21007 receipt是Sandbox receipt但却发送至生产系统的验证服务
* 21008 receipt是生产receipt但却发送至Sandbox环境的验证服务
*/
$POSTFIELDS = ["receipt-data" => $receipt_data];
// if(!$ios_sandBox){
// // 请求验证
// $data = \App\Utils\Http::http('https://sandbox.itunes.apple.com/verifyReceipt', $POSTFIELDS, 'POST');
// }else{
// 请求验证
$data = \App\Utils\Http::http('https://buy.itunes.apple.com/verifyReceipt', $POSTFIELDS, 'POST');
// }
return json_decode($data, true);
}
// 回调 社群-参与活动
public function VideoOrder(Request $request, $trade_no)
{
try {
if (empty($trade_no)) {
return $this->failure('没有回调订单号');
}
$PayLog = new PayLog;
$result = TouristOrder::where('trade_no', $trade_no)->first();
if (!$result) {
$PayLog->remark = '订单号不存在:' . $trade_no;
$PayLog->save();
return $this->failure('没有回调订单号');
}
if ($result->pay_status != 0) {
$PayLog->trade_no = $trade_no;
$PayLog->remark = '订单已经回调';
$PayLog->save();
return $this->success('订单已经回调');
}
\Log::info('para:' . $request->getcontent());
if (!$result->wechat_transaction_id) {
if ($request->getcontent()) {
try {
$xml = $request->getcontent();
$message = XML::parse($xml);
if ($message && $message['transaction_id']) {
$result->wechat_transaction_id = $message['transaction_id'];
$result->save();
}
} catch (\Exception $e) {
\Log::info('回调出错,信息:' . $request->getcontent());
}
}
}
$pay_result = \WechatService::orderPaid($trade_no);
if (empty($pay_result))
return $this->failure("支付回调失败");
$merchant = MerchantAccount::where('id', $result->merchant_id)->first();
$merchant_openid = $merchant->openid ?? '';
$usermember = new UserMember();
$usermember->type = $result->type ?? '';
$usermember->type_id = $result->type_id ?? '';
$usermember->m_id = $result->merchant_id ?? '';
$usermember->m_user_id = $result->account_id ?? '';
$usermember->pay_type = 'wechat';
$usermember->trade_no = $trade_no ?? '';
$usermember->save();
if ($result->price > 0 && $result->type == 'video') {//课程回调
$PayLog->type = 'video';
$PayLog->trade_no = $trade_no;
$PayLog->remark = '订单回调成功';
$PayLog->save();
$result->pay_status = 1;
$result->save();
//发送通知
$res = CourseVideo::where('id', $result->type_id)->first();
$class = $result->type;
//商户
$merchant_openid = Course::where('id', $result->type_id)->value('open_id');
// 发送给渠道
$channel_openid = null;
if ($result->share_channel_id && $result->share_channel_id != 'null') {
$bind_m_user_id = MerchantShareChannel::where('id', $result->share_channel_id)
->value('bind_m_user_id');
if ($bind_m_user_id) {
$channel_openid = MerchantUser::where('id', $bind_m_user_id)->value('openid');
}
}
}
if ($result->merchant_id != 388) {
//发送收益通知(未到账)
SendEarningMessageV2::dispatch($result->id)->onqueue('order');
}
//同步备注
SyncClientComment::dispatch($result)->onQueue('love');
// 给用户
\CommonUtilsService::sendBuySuccessNoticeToUser($res, $result->open_id, $class, $trade_no, $result->price);
if ($result->channel == 0) {
//发送商户
\CommonUtilsService::sendBuySuccessNoticeToBusiness($res, $merchant_openid, 'merchant', $result->price, $result->mobile, $result->name);
}
if ($result->merchant_id == 491) {
//给客服脱单姐
// \CommonUtilsService::sendBuySuccessNoticeToBusiness($res,'oPC_2vudkf3stdiNgjA-e2n6t9_M','merchant',$result->price,$result->mobile,$result->name);
$openids = [
"oPC_2vn6Q3M5jQpw9xAS7NNCMfjs",
"oPC_2vudkf3stdiNgjA-e2n6t9_M",
"oPC_2vtrwOLgWHLwVEFTFsJ7N7fw",
"oPC_2vt7nGwKk_OFzJL70SlVuTiU",
"oPC_2vg_Eur-Wa_Vwnx9JiyRVn9Q
"
];
foreach ($openids as $openid) {
\CommonUtilsService::sendBuySuccessNoticeToBusiness($res, $openid, 'merchant', $result->price, $result->mobile, $result->name);
}
}
//发送推荐人
if ($result->from_openid && $result->from_openid != 'null') {
\CommonUtilsService::sendBuySuccessNoticeToBusiness($res, $result->from_openid, 'recommend', $result->price, $result->mobile, $result->name);
}
// 首邀
$first_invitation = AccessRecord::where('open_id', $result->open_id)->where('account_id', $result->merchant_id)->value('from_openid');
if ($first_invitation && $first_invitation != $result->from_openid) {
\CommonUtilsService::sendBuySuccessNoticeToBusiness($res, $first_invitation, 'first_invitation', $result->price, $result->mobile, $result->name);
}
// 渠道
if ($result->channel == 0 && $channel_openid) {
\CommonUtilsService::sendBuySuccessNoticeToBusiness($res, $channel_openid, 'channel', $result->price, $result->mobile, $result->name);
}
// app消息推送
if (isset($merchant->info->android_id)) {
// 推送平台 ios android
$params['platform'] = 'android';
// 推送标题
$params['title'] = '收到新订单提醒通知';
// 推送内容
$params['content'] = $res->title . '收到付款' . $result->price . '元';
// 通知栏样式 ID
$params['builderId'] = 1;
// 唤醒APP
$params['intent'] = ['url' => 'intent:#Intent;action=com.love.ufutx.saas.ui.main.MainActivity;component=com.love.ufutx.saas/com.love.ufutx.saas.ui.main.MainActivity;end'];
$params['uri_activity'] = 'com.love.ufutx.saas.ui.main.MainActivity';
$params['uri_action'] = 'com.love.ufutx.saas.ui.main.MainActivity';
// 附加字段(这里自定义 Key / value 信息,以供业务使用)
$params['extras'] = [
'url' => 'https://love.ufutx.com/pu_m/#/orderDetail/' . $result->id . '?type=' . $result->type . '&equipmentType=android',
];
// 推送类型 1-别名 2-注册id 3-全部
$params['type'] = 2;
// 注册ID 可以是单个 也可以是 数组
$params['registrationId'] = $merchant->info->android_id;
// 开始推送
JpushService::androidOrIosPushByAlias($params);
}
$redis = Redis::connection('big_data');
Log::info('checkEarningOrder earning:order:ids ' . $result->id);
$redis->lpush('earning:order:ids', $result->id);
//短信通知商家
$jump_url = env('APP_URL') . '/pu_m/#/earningsRecord?merchant_id=' . $merchant->id;
$short_url = \CommonUtilsService::shortUrl(env('APP_URL') . '/h5/#/jump_url?url=' . $jump_url);
$title = $res->title;
if (mb_strlen($title) > 5) {
$title = mb_substr($title, 0, 5, 'utf-8') . '...';
}
$message = '有用户下单了~ ' . $result->name . '购买了平台的《' . $title . '》' . $result->price . '元,点击' . $short_url['url'] . ' 查看详情';
Messenger::sendSMS($merchant->mobile, $message);
//增加记录
Message::create([
'phone' => $merchant->mobile,
'message' => $message,
'confirmed' => 1,
'code' => '购买通知',
'ip' => request() ? request()->ip() : '127.0.0.1',
]);
// 发送短信给渠道分享人
if ($result->share_channel_id && $result->share_channel_id != 'null') {
$share_channel = MerchantShareChannel::where('id', $result->share_channel_id)->first();
if (!empty($share_channel)) {
$merchant_user = MerchantUser::where('id', $share_channel->bind_m_user_id)->first();
if ($merchant_user && $merchant_user->mobile) {
$share_message = 'Hi' . $merchant_user->nickname . ',刚刚有人通过你的渠道「' . $share_channel->title . '」购买了' . $res->title;
Messenger::sendSMS($merchant_user->mobile, $share_message);
}
}
}
//插入购买通知
// $pay_name = $result->user ? $result->user->nickname : '匿名用户';
$content = $result->name . '购买了【' . $res->title . '】查看订单详情>>';
SaasNotice::addRecord($result->merchant_id, $result->account_id, 'order', $result->id, $content, 0);
if ($result->user_coupon_id) {
$user_coupon = UserCoupon::where('id', $result->user_coupon_id)->update(['status' => 1]);
}
return $this->success('ok');
} catch (\Exception $e) {
$this->getError($e);
return $this->failure();
}
}
}