| 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027 |
- <?php
- // +----------------------------------------------------------------------
- // | LARAVEL8.0 框架 [ LARAVEL ][ RXThinkCMF ]
- // +----------------------------------------------------------------------
- // | 版权所有 2017~2021 LARAVEL研发中心
- // +----------------------------------------------------------------------
- // | 官方网站: http://www.laravel.cn
- // +----------------------------------------------------------------------
- // | Author: laravel开发员 <laravel.qq.com>
- // +----------------------------------------------------------------------
- namespace App\Services;
- use App\Models\AccountLogModel;
- use App\Models\MemberModel;
- use App\Models\OrderModel;
- use App\Models\PaymentModel;
- use App\Models\PayOrdersModel;
- use App\Services\Api\SettleService;
- use Illuminate\Support\Facades\DB;
- use Yansongda\Pay\Pay;
- use Yansongda\Pay\Provider\Wechat;
- /**
- * 支付-服务类
- * @author laravel开发员
- * @since 2020/11/11
- * Class PaymentService
- * @package App\Services\Api
- */
- class PaymentService extends BaseService
- {
- protected static $instance = null;
- private $config = [];
- /**
- * 构造函数
- * @author laravel开发员
- * @since 2020/11/11
- * PaymentService constructor.
- */
- public function __construct()
- {
- $this->model = new PaymentModel();
- }
- /**
- * 静态入口
- * @return static|null
- */
- public static function make()
- {
- if (!self::$instance) {
- self::$instance = (new static());
- }
- return self::$instance;
- }
- /**
- * 创建支付
- * @param string $scene 场景,store-购物消费,pay-生活充值,refund-退款
- * @param int $payType
- * @param int $isMin 是否是小程序
- * @return false|\Yansongda\Pay\Provider\Alipay|Wechat
- */
- public function createPay($scene, $payType = 10, $payPt = '')
- {
- $config = ConfigService::make()->getConfigOptionByGroup(6);
- if ($payType == 10) {
- $appid = isset($config['wxpay_appid']) ? $config['wxpay_appid'] : '';
- $mpAppid = isset($config['wxpay_mp_appid']) ? $config['wxpay_mp_appid'] : '';
- $minAppid = isset($config['wxpay_min_appid']) ? $config['wxpay_min_appid'] : '';
- $mchid = isset($config['wxpay_mchd']) ? $config['wxpay_mchd'] : '';
- $secretV3Key = isset($config['wxpay_key_v3']) ? $config['wxpay_key_v3'] : '';
- $secretV2Key = isset($config['wxpay_key_v2']) ? $config['wxpay_key_v2'] : '';
- $wxpaySecretCert = isset($config['wxpay_secret_cert']) ? $config['wxpay_secret_cert'] : '';
- $wxpayPublicCert = isset($config['wxpay_public_cert']) ? $config['wxpay_public_cert'] : '';
- if (empty($appid) || empty($mchid) || empty($secretV3Key)) {
- $this->error = 2616;
- return false;
- }
- // 支付参数
- $payConfig = config('payment.wechat');
- $payConfig['wechat']['default']['mch_id'] = $mchid;
- if ($payPt == 'min') {
- // 小程序支付
- $payConfig['wechat']['default']['mini_app_id'] = $minAppid ? $minAppid : $appid;
- } else if ($payPt == 'mp') {
- // 公众号
- $payConfig['wechat']['default']['mp_app_id'] = $mpAppid ? $mpAppid : $appid;
- } else {
- // APP支付
- $payConfig['wechat']['default']['app_id'] = $appid;
- }
- if ($secretV3Key) {
- $payConfig['wechat']['default']['mch_secret_key'] = $secretV3Key;
- } else if ($secretV2Key) {
- $payConfig['wechat']['default']['mch_secret_key_v2'] = $secretV2Key;
- }
- if ($wxpaySecretCert) {
- $payConfig['wechat']['default']['mch_secret_cert'] = $wxpaySecretCert;
- }
- if ($wxpayPublicCert) {
- $payConfig['wechat']['default']['mch_public_cert_path'] = $wxpayPublicCert;
- }
- //$payConfig['wechat']['default']['notify_url'] = url('/api/notify/' . $scene . '/10');
- $payConfig['wechat']['default']['notify_url'] = url(env('APP_URL') . 'api/notify/' . $scene . '/10');
- $this->config = $payConfig;
- //var_dump($payConfig);
- return Pay::wechat($payConfig);
- } else if ($payType == 20) {
- $appid = isset($config['alipay_appid']) ? $config['alipay_appid'] : '';
- $appSecretCert = isset($config['alipay_secret_cert']) ? $config['alipay_secret_cert'] : '';
- $appPublicCert = isset($config['alipay_app_public_cert_path']) ? $config['alipay_app_public_cert_path'] : '';
- $alipayPublicCert = isset($config['alipay_public_cert_path']) ? $config['alipay_public_cert_path'] : '';
- $alipayRootCert = isset($config['alipay_root_cert_path']) ? $config['alipay_root_cert_path'] : '';
- if (empty($appid) || empty($appSecretCert)) {
- $this->error = 2619;
- return false;
- }
- // 支付参数
- $payConfig = config('payment.alipay');
- $payConfig['alipay']['default']['app_id'] = $appid;
- $payConfig['alipay']['default']['app_secret_cert'] = $appSecretCert;
- if ($appPublicCert) {
- $payConfig['alipay']['default']['app_public_cert_path'] = $appPublicCert;
- }
- if ($alipayPublicCert) {
- $payConfig['alipay']['default']['alipay_public_cert_path'] = $alipayPublicCert;
- }
- if ($alipayRootCert) {
- $payConfig['alipay']['default']['alipay_root_cert_path'] = $alipayRootCert;
- }
- $payConfig['alipay']['default']['notify_url'] = url('/api/notify/' . $scene . '/20');
- $this->config = $payConfig;
- return Pay::alipay($payConfig);
- } else if ($payType == 30) {
- return true;
- }
- return false;
- }
- /**
- * 微信小程序支付
- * @param $userInfo
- * @param $order
- * @param string $scene
- * @return false|\Yansongda\Supports\Collection
- */
- public function minPay($userInfo, $order, $scene = 'store')
- {
- $amount = isset($order['pay_money']) ? $order['pay_money'] : 0;
- $openid = isset($order['openid']) ? $order['openid'] : '';
- if ($amount < 0) {
- $this->error = 2615;
- return false;
- }
- if (empty($openid)) {
- $this->error = 2614;
- return false;
- }
- $outTradeNo = isset($order['order_no']) && $order['order_no'] ? $order['order_no'] : get_order_num('PR');
- // 是否调用过支付,是则用新的支付单号
- if ($outTradeNo && $this->model->where(['out_trade_no' => $outTradeNo, 'mark' => 1])->value('id')) {
- $outTradeNo = $outTradeNo . date('is') . rand(1, 9);
- }
- $body = isset($order['body']) ? $order['body'] : '';
- $payData = [
- 'out_trade_no' => $outTradeNo,
- 'description' => $body ? $body : '订单支付',
- 'amount' => [
- 'total' => intval($amount * 1000/10),
- 'currency' => 'CNY'
- ],
- 'payer' => [
- 'openid' => $openid,
- ],
- ];
- // 创建支付
- try {
- $pay = $this->createPay($scene, 10, 'min');
- RedisService::set("caches:payments:wechat:minPay_{$scene}_{$outTradeNo}", ['order' => $order, 'config' => $this->config], 7200);
- if (empty($pay)) {
- $this->error = 2616;
- return false;
- }
- $pay = $pay->mini($payData);
- } catch (\Exception $exception) {
- RedisService::set("caches:payments:wechat:minPay_{$scene}_{$outTradeNo}_error", ['order' => $order, 'error' => $exception->getTrace(), 'config' => $this->config], 7200);
- $this->error = $exception->getMessage();
- return false;
- }
- if ($pay->package) {
- $data = [
- 'user_id' => $userInfo['id'],
- 'out_trade_no' => $outTradeNo,
- 'order_no' => $order['order_no'],
- 'params' => json_encode($pay, 256),
- 'total_fee' => $amount,
- 'pay_type' => 10,
- 'create_time' => time(),
- 'status' => 2,
- 'mark' => 1,
- ];
- if ($this->model->insertGetId($data)) {
- $this->error = 2617;
- return $pay;
- }
- }
- $this->error = 2618;
- return false;
- }
- /**
- * 微信公众号支付
- * @param $userInfo
- * @param $order
- * @param string $scene
- * @return false|\Yansongda\Supports\Collection
- */
- public function mpPay($userInfo, $order, $scene = 'store')
- {
- $amount = isset($order['pay_money']) ? $order['pay_money'] : 0;
- $openid = isset($order['openid']) ? $order['openid'] : '';
- if ($amount < 0) {
- $this->error = 2615;
- return false;
- }
- if (empty($openid)) {
- $this->error = 2614;
- return false;
- }
- $outTradeNo = isset($order['order_no']) && $order['order_no'] ? $order['order_no'] : get_order_num('PR');
- // 是否调用过支付,是则用新的支付单号
- if ($outTradeNo && $this->model->where(['out_trade_no' => $outTradeNo, 'mark' => 1])->value('id')) {
- $outTradeNo = $outTradeNo . date('is') . rand(1, 9);
- }
- $body = isset($order['body']) ? $order['body'] : '';
- $payData = [
- 'out_trade_no' => $outTradeNo,
- 'description' => $body ? $body : '订单支付',
- 'amount' => [
- 'total' => intval($amount * 1000/10),
- 'currency' => 'CNY'
- ],
- 'payer' => [
- 'openid' => $openid,
- ],
- ];
- // 创建支付
- try {
- $pay = $this->createPay($scene, 10, 'mp');
- RedisService::set("caches:payments:wechat:mp_{$scene}_{$outTradeNo}", ['order' => $order, 'config' => $this->config], 7200);
- if (empty($pay)) {
- $this->error = 2616;
- return false;
- }
- $pay = $pay->mp($payData);
- } catch (\Exception $exception) {
- RedisService::set("caches:payments:wechat:mp_{$scene}_{$outTradeNo}_error", ['order' => $order, 'error' => $exception->getTrace(), 'config' => $this->config], 7200);
- $this->error = $exception->getMessage();
- return false;
- }
- if ($pay->package) {
- $data = [
- 'user_id' => $userInfo['id'],
- 'out_trade_no' => $outTradeNo,
- 'order_no' => $order['order_no'],
- 'params' => json_encode($pay, 256),
- 'total_fee' => $amount,
- 'pay_type' => 10,
- 'create_time' => time(),
- 'status' => 2,
- 'mark' => 1,
- ];
- if ($this->model->insertGetId($data)) {
- $this->error = 2617;
- return $pay;
- }
- }
- $this->error = 2618;
- return false;
- }
- /**
- * 微信APP支付
- * @param $userInfo
- * @param $order
- * @param string $scene
- * @return false|\Yansongda\Supports\Collection
- */
- public function wechatPay($userInfo, $order, $scene = 'store')
- {
- $amount = isset($order['pay_money']) ? $order['pay_money'] : 0;
- if ($amount < 0) {
- $this->error = 2615;
- return false;
- }
- $outTradeNo = isset($order['order_no']) && $order['order_no'] ? $order['order_no'] : get_order_num('PR');
- // 是否调用过支付,是则用新的支付单号
- if ($outTradeNo && $this->model->where(['out_trade_no' => $outTradeNo, 'mark' => 1])->value('id')) {
- $outTradeNo = $outTradeNo . date('is') . rand(1, 9);
- }
- $body = isset($order['body']) ? $order['body'] : '';
- $type = isset($order['type']) ? $order['type'] : 0;
- $payData = [
- 'out_trade_no' => $outTradeNo,
- 'attach' => "order-{$type}",
- 'description' => $body ? $body : '订单支付',
- 'amount' => [
- 'total' => intval($amount * 1000/10),
- 'currency' => 'CNY'
- ],
- ];
- // 创建支付
- try {
- $pay = $this->createPay($scene, 10);
- RedisService::set("caches:payments:wechat:{$scene}_{$outTradeNo}", ['order' => $order, 'config' => $this->config], 7200);
- if (empty($pay)) {
- $this->error = 2616;
- return false;
- }
- $pay = $pay->app($payData);
- } catch (\Exception $exception) {
- RedisService::set("caches:payments:wechat:{$scene}_{$outTradeNo}_error", ['order' => $order, 'error' => $exception->getTrace(), 'config' => $this->config], 7200);
- $this->error = $exception->getMessage();
- return false;
- }
- if ($pay->prepayid) {
- $data = [
- 'user_id' => $userInfo['id'],
- 'out_trade_no' => $outTradeNo,
- 'order_no' => $order['order_no'],
- 'params' => json_encode($pay, 256),
- 'total_fee' => $amount,
- 'pay_type' => 10,
- 'create_time' => time(),
- 'status' => 2,
- 'mark' => 1,
- ];
- if ($this->model->insertGetId($data)) {
- $this->error = 2617;
- return $pay;
- }
- }
- $this->error = 2618;
- return false;
- }
- /**
- * 支付宝支付
- * @param $userInfo
- * @param $order
- * @return bool
- */
- public function aliPay($userInfo, $order, $scene = 'shop')
- {
- $amount = isset($order['pay_money']) ? $order['pay_money'] : 0;
- if ($amount < 0) {
- $this->error = 2615;
- return false;
- }
- // 是否调用过支付,是则用新的支付单号
- $outTradeNo = isset($order['order_no']) && $order['order_no'] ? $order['order_no'] : get_order_num('PY');
- if ($outTradeNo && $this->model->where(['out_trade_no' => $outTradeNo, 'mark' => 1])->value('id')) {
- $outTradeNo = $outTradeNo . date('is') . rand(1, 9);
- }
- $body = isset($order['body']) ? $order['body'] : '';
- $payData = [
- 'out_trade_no' => $outTradeNo,
- 'subject' => $body ? $body : '订单支付',
- 'total_amount' => $amount,
- ];
- // 创建支付
- $pay = $this->createPay($scene, 20);
- RedisService::set("caches:payments:alipay:{$scene}_{$outTradeNo}", ['order' => $order, 'config' => $this->config], 7200);
- if (empty($pay)) {
- $this->error = 2619;
- return false;
- }
- $pay = $pay->app($payData);
- if ($pay->getStatusCode() == 200) {
- $data = [
- 'user_id' => $userInfo['id'],
- 'out_trade_no' => $outTradeNo,
- 'order_no' => $order['order_no'],
- 'params' => json_encode($pay, 256),
- 'total_fee' => $amount,
- 'pay_type' => 20,
- 'create_time' => time(),
- 'status' => 2,
- 'mark' => 1,
- ];
- if ($this->model->insertGetId($data)) {
- $this->error = 2620;
- return $pay->getBody()->getContents();
- }
- }
- $this->error = 2621;
- return false;
- }
- /**
- * 订单支付回调处理
- * @param string $scene 场景 store-购物消费,pay-充值,refund-退款
- * @param int $payType 支付方式,10-微信支付,20-支付宝支付
- * @param array $data 回调数据
- * @return bool
- */
- public function catchNotify($scene, $payType, $data)
- {
- $outTradeNo = '';
- $payTotal = 0;
- $transactionId = '';
- $payAt = '';
- $notifyData = [];
- try {
- // 微信支付
- if ($payType == 10) {
- $resource = isset($data['resource']) ? $data['resource'] : [];
- $ciphertext = isset($resource['ciphertext']) ? $resource['ciphertext'] : [];
- $tradeStatus = isset($ciphertext['trade_state']) ? $ciphertext['trade_state'] : '';
- if ($tradeStatus != 'SUCCESS') {
- $this->error = 2622;
- return false;
- }
- $outTradeNo = isset($ciphertext['out_trade_no']) ? $ciphertext['out_trade_no'] : '';
- $transactionId = isset($ciphertext['transaction_id']) ? $ciphertext['transaction_id'] : '';
- if (empty($outTradeNo)) {
- $this->error = 2623;
- return false;
- }
- $payAt = isset($ciphertext['success_time']) ? date('Y-m-d H:i:s', strtotime($ciphertext['success_time'])) : date('Y-m-d H:i:s');
- $amount = isset($ciphertext['amount']) ? $ciphertext['amount'] : [];
- $payTotal = isset($amount['total']) ? moneyFormat($amount['total'] / 100, 3) : 0;
- $notifyData = $ciphertext;
- if ($payTotal <= 0) {
- $this->error = 2624;
- return false;
- }
- } // 支付宝支付
- else if ($payType == 20) {
- // TRADE_SUCCESS
- $tradeStatus = isset($data['trade_status']) ? $data['trade_status'] : '';
- if ($tradeStatus != 'TRADE_SUCCESS' && $tradeStatus != 'TRADE_FINISHED') {
- $this->error = 2622;
- return false;
- }
- $outTradeNo = isset($data['out_trade_no']) ? $data['out_trade_no'] : '';
- if (empty($outTradeNo)) {
- $this->error = 2623;
- return false;
- }
- $payTotal = isset($data['total_amount']) ? floatval($data['total_amount']) : 0;
- $transactionId = isset($data['trade_no']) ? trim($data['trade_no']) : '';
- $payAt = isset($data['send_pay_date']) ? trim($data['send_pay_date']) : date('Y-m-d H:i:s');
- $notifyData = $data;
- if ($payTotal <= 0) {
- $this->error = 2624;
- return false;
- }
- }
- // 支付信息
- $paymentInfo = $this->model->with(['user'])->where(['out_trade_no' => $outTradeNo, 'mark' => 1])
- ->select(['user_id', 'order_no', 'pay_type', 'total_fee', 'status'])
- ->first();
- $status = isset($paymentInfo['status']) ? $paymentInfo['status'] : 0;
- $totalFee = isset($paymentInfo['total_fee']) ? $paymentInfo['total_fee'] : 0;
- $paymentPayType = isset($paymentInfo['pay_type']) ? $paymentInfo['pay_type'] : 0;
- $orderNo = isset($paymentInfo['order_no']) ? $paymentInfo['order_no'] : '';
- $payUserId = isset($paymentInfo['user_id']) ? $paymentInfo['user_id'] : 0;
- if (empty($paymentInfo) || empty($orderNo) || $payUserId <= 0) {
- $this->error = 2625;
- return false;
- }
- // 验证支付状态
- if ($status == 1) {
- $this->error = 2626;
- return false;
- }
- // 验证支付方式
- if ($paymentPayType != $payType) {
- $this->error = 2627;
- return false;
- }
- if ($payTotal != $totalFee || $payTotal <= 0) {
- $this->error = 2628;
- return false;
- }
- // 删除久远旧记录
- $this->model->where(['mark' => 1])->where('create_time', '<=', time() - 60 * 86400)->delete();
- // 更新订单数据
- DB::beginTransaction();
- $updateData = ['transaction_id' => $transactionId, 'result' => json_encode($notifyData, 256), 'pay_at' => $payAt, 'status' => 1, 'update_time' => time()];
- if (!$this->model->where(['out_trade_no' => $outTradeNo, 'mark' => 1])->update($updateData)) {
- $this->error = 2632;
- DB::rollBack();
- return false;
- }
- /* TODO 订单验证和状态处理 */
- $orderInfo = [];
- // 商城订单支付
- if ($scene == 'store') {
- $orderInfo = OrderModel::with(['user'])->where(['order_no' => $orderNo, 'mark' => 1])
- ->select(['id as order_id', 'user_id', 'order_no', 'total as pay_money', 'pay_at as pay_time', 'remark', 'status'])
- ->first();
- $orderStatus = isset($orderInfo['status']) ? $orderInfo['status'] : 0;
- // 验证订单
- if (empty($orderInfo)) {
- DB::rollBack();
- $this->error = 2629;
- return false;
- }
- // 订单状态
- if ($orderStatus != 1) {
- DB::rollBack();
- $this->error = 2630;
- return false;
- }
- $updateData = ['pay_at' => $payAt, 'transaction_id' => $transactionId, 'status' => 2, 'update_time' => time()];
- if (!OrderModel::where(['order_no' => $orderNo, 'mark' => 1])->update($updateData)) {
- $this->error = 2633;
- DB::rollBack();
- return false;
- }
- }
- // 生活充值
- else if ($scene == 'pay') {
- $orderInfo = PayOrdersModel::with(['meal'])->where(['order_no' => $orderNo, 'mark' => 1])
- ->select(['id as order_id', 'user_id','meal_id','product_id', 'order_no','transaction_id','account', 'total as pay_money','area','ytype','city','id_card_no','pay_total', 'pay_at as pay_time', 'remark', 'status'])
- ->first();
- $orderStatus = isset($orderInfo['status']) ? $orderInfo['status'] : 0;
- // 验证订单
- if (empty($orderInfo)) {
- DB::rollBack();
- $this->error = 2629;
- return false;
- }
- // 订单状态
- if ($orderStatus != 1) {
- DB::rollBack();
- $this->error = 2630;
- return false;
- }
- $updateData = ['pay_at' => $payAt, 'transaction_id' => $transactionId, 'status' => 2, 'update_time' => time()];
- if (!PayOrdersModel::where(['order_no' => $orderNo, 'mark' => 1])->update($updateData)) {
- $this->error = 2633;
- DB::rollBack();
- return false;
- }
- }
- // 退款
- else if ($scene == 'refund') {
- $orderInfo = OrderModel::where(['order_no' => $orderNo, 'mark' => 1])
- ->select(['id as order_id', 'user_id', 'order_no', 'total as pay_money', 'remark', 'refund_remark', 'pay_at as pay_time', 'refund_status as status'])
- ->first();
- $refundRemark = isset($orderInfo['refund_remark']) ? $orderInfo['refund_remark'] : 'refund_remark';
- $orderStatus = isset($orderInfo['status']) ? $orderInfo['status'] : 0;
- // 验证订单
- if (empty($orderInfo)) {
- DB::rollBack();
- $this->error = 2629;
- return false;
- }
- // 订单状态
- if ($orderStatus != 2) {
- DB::rollBack();
- $this->error = 2639;
- return false;
- }
- // 订单打款状态
- if ($orderStatus == 1) {
- DB::rollBack();
- $this->error = 2630;
- return false;
- }
- $updateData = ['refund_status' => 1, 'refund_remark' => $refundRemark ? $refundRemark . ' 已退款成功' : '已退款成功', 'update_time' => time()];
- if (!OrderModel::where(['order_no' => $orderNo, 'mark' => 1])->update($updateData)) {
- $this->error = 2633;
- DB::rollBack();
- return false;
- }
- }
- // TODO 场景业务回调处理
- $orderUserId = isset($orderInfo['user_id']) ? $orderInfo['user_id'] : 0;
- $this->saveLog("caches:payments:notify_{$scene}:catch_{$orderNo}_{$orderUserId}", ['order' => $orderInfo, 'notify' => $data]);
- switch ($scene) {
- case 'store': //
- break;
- case 'pay': //
- // 调起 接口充值
- $orderId = isset($orderInfo['order_id'])? $orderInfo['order_id'] : 0;
- $productId = isset($orderInfo['product_id'])? $orderInfo['product_id'] : '';
- $orderNo = isset($orderInfo['order_no'])? $orderInfo['order_no'] : '';
- $account = isset($orderInfo['account'])? $orderInfo['account'] : '';
- $total = isset($orderInfo['pay_money'])? $orderInfo['pay_money'] : 0;
- $payTotal = isset($orderInfo['pay_total'])? $orderInfo['pay_total'] : 0;
- $mealData = isset($orderInfo['meal'])? $orderInfo['meal'] : [];
- $orderType = isset($orderInfo['type'])?$orderInfo['type']:1;
- $electricType = isset($mealData['electric_type'])?$mealData['electric_type']:0;
- $city = isset($orderInfo['city'])?$orderInfo['city']:'';
- $amount = $total;
- $params = [
- 'price'=>$payTotal,
- 'ytype'=>isset($orderInfo['ytype'])?$orderInfo['ytype']:0,
- 'id_card_no'=>isset($orderInfo['id_card_no'])?$orderInfo['id_card_no']:'',
- 'area'=>isset($orderInfo['area'])?$orderInfo['area']:'',
- ];
- if($orderType==2 && $electricType!= 3 && $city){
- $params['city'] = $city;
- }
- $result = DyrPayService::make()->recharge($orderNo, $account, $productId, $amount, $params);
- $errno = isset($result['errno'])?$result['errno'] : -1;
- $errmsg = isset($result['errmsg'])?$result['errmsg'] : '';
- $res = isset($result['data'])?$result['data']:[];
- $order_number = isset($res['order_number'])?$res['order_number']:'';
- if(empty($result) || $errno != 0 || empty($order_number)){
- $this->error = '充值调用失败:'.$errmsg;
- // 退款
- $orderInfo['money'] = $payTotal;
- $orderInfo['transaction_id'] = $transactionId;
- $orderInfo['remark'] = '充值失败退款';
- $refundStatus = PaymentService::make()->refund($orderInfo,'pay');
- $updateData = ['refund_status'=> $refundStatus?1:3,'status'=>5,'transaction_id'=>$transactionId,'pay_at'=>$payAt,'result'=>json_encode(['amount'=>$amount,'params'=>$params,'msg'=>$this->error,'result'=>$result],256),'failed_remark'=> $errmsg,'refund_at'=>date('Y-m-d H:i:s'),'refund_money'=>$refundStatus?$payTotal:0,'update_time'=>time()];
- $this->saveLog("caches:payments:notify_{$scene}:pay_failed_{$orderNo}_{$orderUserId}", ['error'=>$this->error,'update'=>$updateData,'order' => $orderInfo,'result'=>$result, 'notify' => $data]);
- if(!PayOrdersModel::where(['id'=>$orderId])->update($updateData)){
- $this->error = '订单退款状态更新错误~';
- }
- DB::commit();
- return false;
- }
- $updateData = ['status'=>3,'result'=>json_encode(['amount'=>$amount,'params'=>$params,'result'=>$result],256),'out_trade_no'=>$order_number,'update_time'=>time()+1];
- $this->saveLog("caches:payments:notify_{$scene}:pay_success_{$orderNo}_{$orderUserId}", ['error'=> '充值调用成功','id'=>$orderId,'update'=>$updateData,'order' => $orderInfo,'result'=>$result, 'notify' => $data]);
- if(!PayOrdersModel::where(['id'=>$orderId])->update($updateData)){
- DB::commit();
- $this->error = '更新充值订单失败';
- $this->saveLog("caches:payments:notify_{$scene}:pay_failed_{$orderNo}_{$orderUserId}", ['error'=>$this->error,'update'=>$updateData,'order' => $orderInfo,'result'=>$result, 'notify' => $data]);
- return false;
- }
- DB::commit();
- return true;
- default:
- break;
- }
- $this->error = '回调处理成功';
- DB::commit();
- return true;
- } catch (\Exception $exception) {
- $this->error = $exception->getMessage();
- RedisService::set("caches:payments:notify_{$scene}:catch_" . $orderNo . '_error', ['notify' => $data, 'error' => $exception->getMessage(), 'trace' => $exception->getTrace()], 7200);
- return false;
- }
- }
- /**
- * 充值回调
- * @param $productId
- * @param $data
- * @return bool
- * @throws \Yansongda\Pay\Exception\ContainerException
- * @throws \Yansongda\Pay\Exception\InvalidParamsException
- * @throws \Yansongda\Pay\Exception\ServiceNotFoundException
- */
- public function catchPayNotify($productId, $data)
- {
- $out_trade_num = isset($data['out_trade_num'])?$data['out_trade_num']:'';
- $state = isset($data['state'])? $data['state'] : 0;
- $charge_kami = isset($data['charge_kami'])?$data['charge_kami'] : '';
- $remark = isset($data['remark'])?$data['remark'] : '';
- $amount = isset($data['charge_amount'])?floatval($data['charge_amount']) : 0;
- if($state==0){
- $this->error = '充值处理中~';
- return false;
- }
- $orderInfo = PayOrdersModel::with(['user'])->where(['order_no'=>$out_trade_num,'mark'=>1])->first();
- $orderId = isset($orderInfo['id'])? $orderInfo['id'] : 0;
- $orderUserId = isset($orderInfo['user_id'])? $orderInfo['user_id'] : 0;
- $status = isset($orderInfo['status'])? $orderInfo['status'] : 0;
- $total = isset($orderInfo['pay_total'])? $orderInfo['pay_total'] : 0;
- $recBonusId = isset($orderInfo['rec_bonus_id'])?$orderInfo['rec_bonus_id'] : 0;
- $recBonus = isset($orderInfo['rec_bonus'])?$orderInfo['rec_bonus'] : 0;
- if(empty($orderInfo) || $orderId<=0 || $total<=0){
- $this->error = '充值订单不存在';
- $this->saveLog("caches:payments:payNotify_{$productId}:notify_{$out_trade_num}_error", ['error'=>$this->error,'order' => $orderInfo, 'notify' => $data]);
- return false;
- }
- if($status!=3){
- $this->error = '充值订单状态错误,状态非充值中';
- $this->saveLog("caches:payments:payNotify_{$productId}:notify_{$out_trade_num}_error", ['error'=>$this->error,'order' => $orderInfo, 'notify' => $data]);
- return false;
- }
- // 成功
- $status = 4;
- $refundAmount = 0;
- if($state == 1){
- $this->error = '充值成功~';
- }
- //部分成功,退部分
- else if($state == 3) {
- $status = 6;
- $refundAmount = moneyFormat($total - $amount,2);
- $this->error = '充值成功部分退款';
- }
- //失败,退全款
- else if(in_array($state,[-1,2])){
- $status = 5;
- $refundAmount = $total;
- $this->error = '充值失败退款';
- }
- // 更新订单状态
- DB::beginTransaction();
- $this->saveLog("caches:payments:payNotify_{$productId}:notify_{$out_trade_num}", ['error'=>$this->error,'order' => $orderInfo, 'notify' => $data]);
- if(!PayOrdersModel::where(['id'=>$orderId])->update(['status'=>$status,'charge_kami'=>$charge_kami,'refund_status'=>$status!=4?2:0,'charge_amount'=>$amount,'update_time'=>time()])){
- $this->error = '更新订单状态错误~';
- DB::rollBack();
- return false;
- }
- // 是否要退款
- if($refundAmount>0){
- $orderInfo['money'] = $refundAmount;
- $orderInfo['remark'] = $this->error;
- $orderInfo['out_trade_no'] = '';
- $refundStatus = PaymentService::make()->refund($orderInfo,'pay');
- if(!PayOrdersModel::where(['id'=>$orderId])->update(['refund_status'=> $refundStatus?1:3,'failed_remark'=>$remark,'refund_remark'=>$this->error,'refund_money'=>$refundStatus?$refundAmount:0,'refund_at'=>date('Y-m-d H:i:s'),'update_time'=>time()])){
- $this->saveLog("caches:payments:payNotify_{$productId}:notify_{$out_trade_num}_error", ['error'=>$this->error,'order' => $orderInfo, 'notify' => $data]);
- $this->error = '订单退款状态更新错误~';
- DB::rollBack();
- return false;
- }
- }
- // 订单完成,代理收益结算
- if($status == 4 && $amount>0)
- {
- // 代理佣金结算
- $result = SettleService::make()->agentBonus($orderUserId, $recBonus, $orderInfo, $recBonusId);
- if ($result<0) {
- DB::rollBack();
- $this->error = SettleService::make()->getError();
- $this->saveLog("caches:settle:{$out_trade_num}:agent_{$orderUserId}_error",SettleService::make()->getError());
- return false;
- }
- $this->saveLog("caches:settle:{$out_trade_num}:agent_{$orderUserId}",['msg'=>SettleService::make()->getError(),'result'=>$result]);
- // 更新订单结算状态
- if(!$this->model->where(['id'=>$orderId])->update(['bonus_settle'=>1,'update_time'=>time()])){
- DB::rollBack();
- $this->error = '收益结算状态更新失败';
- return false;
- }
- }
- DB::commit();
- $this->error = '充值订单处理成功~';
- return ['id'=>$orderId,'amount'=>$amount,'status'=>$status,'refund'=>$refundAmount];
- }
- /**
- * 日志
- * @param $key
- * @param $data
- */
- public function saveLog($key, $data)
- {
- if(env('APP_DEBUG')){
- RedisService::set($key,$data,env('DEBUG_EXPIRE',7200));
- }
- }
- /**
- * 退款请求
- * @param $order
- * @param string $scene
- * @return bool
- * @throws \Yansongda\Pay\Exception\ContainerException
- * @throws \Yansongda\Pay\Exception\InvalidParamsException
- * @throws \Yansongda\Pay\Exception\ServiceNotFoundException
- */
- public function refund($order, $scene = 'store')
- {
- $money = isset($order['money']) ? $order['money'] : 0;
- $payType = isset($order['pay_type']) && $order['pay_type']? $order['pay_type'] : 10;
- $orderNo = isset($order['order_no']) ? $order['order_no'] : '';
- $outTradeNo = isset($order['out_trade_no']) ? $order['out_trade_no'] : '';
- $transactionId = isset($order['transaction_id']) ? $order['transaction_id'] : '';
- $remark = isset($order['remark']) && $order['remark'] ? $order['remark'] : '退款';
- $pay = PaymentService::make()->createPay($scene, $payType);
- if (empty($pay)) {
- DB::rollBack();
- $this->error = '创建退款支付失败';
- return false;
- }
- // 保证金退款处理
- $refundStatus = false;
- switch ($payType) {
- case 10: // 微信支付
- $data = [
- 'out_trade_no' => $outTradeNo?$outTradeNo:$orderNo,
- 'out_refund_no' => get_order_num('RF'),
- 'transaction_id' => $transactionId,
- 'notify_url' => url("/api/notify/{$scene}/{$payType}"),
- 'reason' => $remark,
- 'amount' => [
- 'refund' => intval($money * 100),
- 'total' => intval($money * 100),
- 'currency' => 'CNY',
- ],
- ];
- // 请求退款
- $pay = $pay->refund($data);
- RedisService::set("caches:refunds:order:{$orderNo}_wxpay", ['data' => $data, 'pay' => $pay, 'type' => $payType, 'date' => date('Y-m-d H:i:s')], 7200);
- if ($pay->status == 'SUCCESS' || $pay->status == 'PROCESSING') {
- $refundStatus = true;
- } else {
- DB::rollBack();
- $this->errorData = $data;
- $this->error = '微信退款处理失败:'.$pay->message;
- return false;
- }
- break;
- case 20: // 支付宝
- $data = [
- 'out_request_no' => $outTradeNo?$outTradeNo:$orderNo,
- 'trade_no' => $transactionId,
- 'refund_amount' => $money,
- 'query_options' => ['deposit_back_info'],
- 'refund_reason' => $remark,
- ];
- $payResult = $pay->refund($data);
- RedisService::set("caches:refunds:order:{$orderNo}_alipay", ['data' => $data, 'pay' => $payResult, 'type' => $payType, 'date' => date('Y-m-d H:i:s')], 7200);
- if ($payResult->code == 10000 || intval($payResult->code) == 40004) {
- $refundStatus = true;
- } else {
- $this->errorData = $data;
- $this->error = '支付宝退款处理失败:'.$payResult->code;
- return false;
- }
- break;
- default:
- $this->error = '退款支付类型错误';
- return false;
- }
- $this->error = '退款处理成功';
- return $refundStatus;
- }
- /**
- * 企业打款到零钱(商家转账)
- * @param $order 订单参数:order_no-单号,pay_money-打款金额,account-打款账号(微信openid或支付宝账号),body-打款备注
- * @param string $scene
- * @param int $payType
- * @return bool
- */
- public function transfer($order, $scene='withdraw', $payType=10)
- {
- $outTradeNo = isset($order['order_no']) && $order['order_no'] ? $order['order_no'] : get_order_num('WD');
- $body = isset($order['body']) ? $order['body'] : '';
- $amount = isset($order['pay_money']) ? $order['pay_money'] : 0;
- $account = isset($order['account']) ? $order['account'] : ''; // 微信openid或支付宝账号
- $realName = isset($order['real_name']) ? $order['real_name'] : ''; // 实名
- if ($amount < 0) {
- $this->error = '打款金额错误';
- return false;
- }
- if(empty($account)){
- $this->error = $payType == 10? '缺少微信OPENID' : '支付宝账户不为空';
- return false;
- }
- // 创建支付
- $result = [];
- try {
- $config = ConfigService::make()->getConfigOptionByGroup(6);
- if ($payType == 10) {
- $appid = isset($config['wxpay_appid']) ? $config['wxpay_appid'] : '';
- $payData = [
- '_action' => 'mch_transfer', // 微信官方老版本下线后,此部分可省略
- 'appid' => $appid,
- 'out_bill_no' => $outTradeNo,
- 'transfer_scene_id' => '1000',
- 'openid' => $account,
- 'transfer_amount' => intval($amount * 100),
- 'transfer_remark' => $body?$body:'收入提现',
- 'user_recv_perception' => $body? $body : '收入提现',
- "transfer_scene_report_infos"=> [
- [
- "info_type" => "活动名称",
- "info_content" => "收入提现"
- ],
- [
- "info_type" => "奖励说明",
- "info_content" => "用户收入提现"
- ]
- ],
- ];
- $pay = $this->createPay($scene, $payType);
- RedisService::set("caches:payments:wechat:{$scene}_{$outTradeNo}_pay", ['order' => $order, 'config' => $this->config], 7200);
- if (empty($pay)) {
- $this->error = '微信打款失败';
- return false;
- }
- $result = $pay->transfer($payData);
- RedisService::set("caches:payments:wechat:{$scene}_{$outTradeNo}_result", ['order' => $order,'result'=> $result, 'config' => $this->config], 7200);
- $msg = isset($result['message'])? trim($result['message']) : '';
- $batchId = isset($result['batch_id'])? trim($result['batch_id']) : '';
- if(empty($batchId)){
- $this->error = $msg? $msg : '微信打款失败';
- return false;
- }
- $this->error = '微信打款成功';
- return ['order_no'=> $outTradeNo,'batch_id'=> $batchId,'result'=>$result];
- }else if ($payType == 20){
- $payData = [
- 'out_biz_no' => $outTradeNo,//商户订单号,内部订单号
- 'trans_amount' => $amount, //订单总金额,单位为元,精确到小数点后两位,
- 'biz_scene' => 'DIRECT_TRANSFER', //描述特定的业务场景,可传的参数如下:DIRECT_TRANSFER:单笔无密转账到支付宝,B2C现金红包PERSONAL_COLLECTION:C2C现金红包-领红包
- 'product_code' => 'TRANS_ACCOUNT_NO_PWD', //业务产品码,单笔无密转账到支付宝账户固定为:TRANS_ACCOUNT_NO_PWD;收发现金红包固定为:STD_RED_PACKET;
- 'remark' => $body? $body : '提现',//业务备注
- 'order_title' => $body? $body : '提现',//转账业务的标题,用于在支付宝用户的账单里显示
- 'payee_info' => [
- 'identity' => $account,//参与方的唯一标识'208823395231'
- 'name' => $realName,//参与方的唯一标识'208823395231'
- 'identity_type' => 'ALIPAY_LOGON_ID',//参与方的标识类型,目前支持如下类型:1、ALIPAY_USER_ID 支付宝的会员ID2、ALIPAY_LOGON_ID:支付宝登录号,支持邮箱和手机号格式3、ALIPAY_OPEN_ID:支付宝openid
- ],//收款方信息
- ];
- $pay = $this->createPay($scene, $payType);
- RedisService::set("caches:payments:alipay:{$scene}_{$outTradeNo}_pay", ['order' => $order, 'config' => $this->config], 7200);
- if (empty($pay)) {
- $this->error = '支付宝打款失败';
- return false;
- }
- $result = $pay->transfer($payData);
- RedisService::set("caches:payments:alipay:{$scene}_{$outTradeNo}_result", ['order' => $order,'result'=> $result, 'config' => $this->config], 7200);
- $code = isset($result['code'])? intval($result['code']) : '';
- $msg = isset($result['sub_msg'])? trim($result['sub_msg']) : '';
- if($code != 10000){
- $this->error = $msg? $msg : '支付宝打款失败';
- return false;
- }
- $this->error = '支付宝打款成功';
- return $result;
- }else if($payType == 50){
- $this->error = '银行卡打款未开通';
- return false;
- }
- $this->error = '打款失败';
- return false;
- } catch (\Exception $exception) {
- RedisService::set("caches:payments:trabsfer:{$scene}_{$outTradeNo}_error", ['order' => $order,'error'=>$exception->getTrace(), 'config' => $this->config], 7200);
- $this->error = $exception->getMessage();
- return false;
- }
- }
- }
|