123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464 |
- <?php
- namespace addons\unishop\controller;
- use addons\unishop\extend\Ali;
- use addons\unishop\extend\Hashids;
- use addons\unishop\extend\Wechat;
- use addons\unishop\model\Config;
- use addons\unishop\model\UserExtend;
- use EasyWeChat\Factory;
- use think\Db;
- use think\Exception;
- use think\Hook;
- use think\Log;
- class Pay extends Base
- {
- protected $noNeedLogin = ['getPayType', 'notify', 'authRedirect', 'alipay', 'alinotify', 'weixinOauth2'];
-
- public function getPayType()
- {
- $platfrom = $this->request->header('platform');
- $type = [];
- $offline = Config::getByName('offline_pay')['value'] == 1 ? true : false;
- switch ($platfrom) {
- case 'APP-PLUS';
- $type = ['alipay' => true, 'wxpay' => true, 'offline' => $offline];
- break;
- case 'H5':
- $type = ['alipay' => true, 'wxpay' => true, 'offline' => $offline];
-
- if (Wechat::h5InWechat()) {
- $type['alipay'] = false;
- }
- break;
- case 'MP-WEIXIN':
- $type = ['alipay' => false, 'wxpay' => true, 'offline' => $offline];
- break;
- case 'MP-ALIPAY':
- $type = ['alipay' => true, 'wxpay' => false, 'offline' => $offline];
- break;
- case 'MP-BAIDU':
- $type = ['alipay' => false, 'wxpay' => false, 'offline' => $offline];
- break;
- case 'MP-TOUTIAO':
- $type = ['alipay' => false, 'wxpay' => false, 'offline' => $offline];
- break;
- }
- $this->success('', $type);
- }
-
- public function unify()
- {
- $orderId = $this->request->request('order_id', 0);
- $orderId = Hashids::decodeHex($orderId);
- $orderModel = new \addons\unishop\model\Order();
- $order = $orderModel->where(['id' => $orderId])->find();
- try {
- if (!$order) {
- $this->error(__('Order does not exist'));
- }
-
- $platfrom = $this->request->header('platform', 'MP-WEIXIN');
- switch ($platfrom) {
- case 'MP-WEIXIN':
- $trade_type = 'JSAPI';
- break;
- case 'H5':
- $trade_type = 'MWEB';
- break;
- case 'APP-PLUS':
- $trade_type = 'APP';
- break;
- }
-
- if (Wechat::h5InWechat()) {
- $trade_type = 'JSAPI';
- }
- $products = $order->products()->select();
- $body = Config::getByName('name')['value'];
- foreach ($products as $product) {
- $body .= '_' . $product['title'];
- }
- $openid = Wechat::getOpenidByUserId($this->auth->id);
- $appid = Config::getByName('app_id')['value'];
-
- if ($trade_type == 'JSAPI' && empty($openid)) {
- $this->success('', array(
- 'weixinOauth2' =>
- "https://open.weixin.qq.com/connect/oauth2/authorize?appid=$appid&redirect_uri=".urlencode("https://$_SERVER[HTTP_HOST]/addons/unishop/pay/weixinOauth2")."&response_type=code&scope=snsapi_base&state=".$this->request->request('order_id', 0)."#wechat_redirect"
- ,'trade_type' => 'JSAPI'));
- }
- $app = Wechat::initEasyWechat('payment');
- $result = $app->order->unify([
- 'body' => $body,
- 'out_trade_no' => $order['out_trade_no'],
- 'total_fee' => bcmul($order['total_price'],100),
- 'spbill_create_ip' => $_SERVER['REMOTE_ADDR'],
- 'trade_type' => $trade_type,
- 'openid' => $openid
- ]);
- if ($result['return_code'] == 'SUCCESS' && $result['result_code'] == 'SUCCESS') {
- if ($trade_type == 'JSAPI') {
-
- $result['timeStamp'] = (string)time();
- $result['paySign'] = Wechat::paySign([
- 'appId' => $appid,
- 'nonceStr' => $result['nonce_str'],
- 'package' => 'prepay_id='.$result['prepay_id'],
- 'timeStamp' => $result['timeStamp'],
- 'signType' => 'MD5'
- ], Config::getByName('key')['value']);
- } elseif ($trade_type == 'MWEB') {
- $page = '/pages/order/order?state=0';
- if ($platfrom == 'APP-PLUS') {
- $page = '/pages/index/index';
- }
- $result['mweb_url'] .= '&redirect_url='. urlencode('https://'.$_SERVER['HTTP_HOST'].'/h5/#'.$page);
- $result['referer'] = 'https://'.$_SERVER['HTTP_HOST'];
- } elseif ($trade_type == 'APP') {
- $result['orderInfo']['appid'] = $result['appid'];
- $result['orderInfo']['noncestr'] = $result['nonce_str'];
- $result['orderInfo']['package'] = "Sign=WXPay";
- $result['orderInfo']['partnerid'] = $result['mch_id'];
- $result['orderInfo']['prepayid'] = $result['prepay_id'];
- $result['orderInfo']['timestamp'] = (string)time();
- $result['orderInfo']['sign'] = Wechat::paySign(
- $result['orderInfo'],
- Config::getByName('key')['value']
- );
- }
- } else {
- $this->error($result['return_msg']);
- }
- } catch (Exception $e) {
- $this->error($e->getMessage());
- }
- $this->success('', $result);
- }
-
- public function notify()
- {
-
- Hook::add('paid_success', 'addons\\unishop\\behavior\\Order');
- Hook::add('paid_fail', 'addons\\unishop\\behavior\\Order');
- $app = Wechat::initEasyWechat('payment');
- $response = $app->handlePaidNotify(function($message, $fail) use ($app){
- try {
-
- $orderModel = new \addons\unishop\model\Order();
- $order = $orderModel->where(['out_trade_no' => $message['out_trade_no']])->find();
- if (!$order || $order->have_paid != \addons\unishop\model\Order::PAID_NO) {
- return true;
- }
-
- $result = $app->order->queryByOutTradeNumber($message['out_trade_no']);
- if ($result['return_code'] == 'FAIL' || empty($result['result_code']) || $result['result_code'] == 'FAIL') {
- return $fail('订单未支付');
- }
-
- if ($message['return_code'] === 'SUCCESS') {
-
- if ($message['result_code'] === 'SUCCESS') {
- Hook::listen('paid_success', $order, ['pay_type' => \addons\unishop\model\Order::PAY_WXPAY]);
- } elseif ($message['result_code'] === 'FAIL') {
-
- Hook::listen('paid_fail', $order);
- }
- } else {
- return $fail('通信失败,请稍后再通知我');
- }
- return true;
- } catch (\Exception $e) {
-
- Log::record('支付回调错误:'. $e->getMessage());
- return $fail('通信失败,请稍后再通知我');
- }
- });
- $response->send();
- }
-
- public function offline()
- {
- $orderId = $this->request->get('order_id', 0);
- $orderId = Hashids::decodeHex($orderId);
- $orderModel = new \addons\unishop\model\Order();
- $order = $orderModel->where(['id' => $orderId])->find();
- if (!$order) {
- $this->error(__('Order does not exist'));
- }
- try {
- Db::startTrans();
- Hook::add('paid_success', 'addons\\unishop\\behavior\\Order');
- Hook::listen('paid_success', $order, ['pay_type' => \addons\unishop\model\Order::PAY_OFFLINE]);
- Db::commit();
- } catch (Exception $e) {
- Db::rollback();
- $this->error($e->getMessage());
- }
- $this->success('', true);
- }
-
- public function jssdkBuildConfig()
- {
- $app = Wechat::initEasyWechat('payment');
- $configData = $app->jssdk->buildConfig(['chooseWXPay'], false, true, false);
- $this->success('', $configData);
- }
-
- public function alipay()
- {
- $orderId = $this->request->request('order_id', 0);
- $orderId = Hashids::decodeHex($orderId);
- $orderModel = new \addons\unishop\model\Order();
- $order = $orderModel->where(['id' => $orderId])->find();
- try {
- if (!$order) {
- $this->error(__('Order does not exist'));
- }
- $products = $order->products()->select();
- $body = Config::getByName('name')['value'];
- foreach ($products as $product) {
- $body .= '_' . $product['title'];
- }
- $platfrom = $this->request->header('platform', 'H5');
- $alipay = Ali::initAliPay();
- $order = [
- 'out_trade_no' => $order->out_trade_no,
- 'total_amount' => $order->total_price,
- 'subject' => $body,
- 'http_method' => 'GET'
- ];
- switch ($platfrom) {
- case 'H5':
-
- $alipay->wap($order)->send();
- break;
- case 'APP-PLUS':
-
- $this->success('', $alipay->app($order)->getContent());
- break;
- case 'MP-ALIPAY':
- break;
- default:
- $this->error('此平台不支持支付宝支付');
- }
- } catch (Exception $e) {
- $this->error($e->getMessage());
- }
- }
-
- public function alinotify()
- {
- $alipay = Ali::initAliPay();
- try{
- $data = $alipay->verify();
-
-
-
-
-
-
- if (in_array($data['trade_status'], ['TRADE_SUCCESS', 'TRADE_FINISHED'])) {
-
-
-
- $orderModel = new \addons\unishop\model\Order();
- $order = $orderModel->where(['out_trade_no' => $data['out_trade_no']])->find();
- if (!$order || $order->have_paid != \addons\unishop\model\Order::PAID_NO) {
- throw new Exception('订单不存在或已完成');
- }
-
- if ($order->total_price > $data['total_amount'] || $order->total_price < $data['total_amount']) {
- throw new Exception('金额不一');
- }
-
- if ($data['app_id'] != Config::getByName('ali_app_id')['value']) {
- throw new Exception('app_id不一');
- }
-
- Hook::add('paid_success', 'addons\\unishop\\behavior\\Order');
- Hook::listen('paid_success', $order, ['pay_type' => \addons\unishop\model\Order::PAY_ALIPAY]);
- }
- } catch (\Exception $e) {
- Log::record('Alipay notify ,支付失败: '. $e->getMessage());
- return $alipay->success()->send();
- }
- return $alipay->success()->send();
- }
-
- public function weixinOauth2()
- {
- $config = [
- 'app_id' => Config::getByName('app_id')['value'],
- 'secret' => Config::getByName('secret')['value'],
-
- 'response_type' => 'array',
-
- ];
- $app = Factory::officialAccount($config);
- $oauth = $app->oauth;
- $user = $oauth->user();
- $order_id = $this->request->request('state', 0);
- $orderId = Hashids::decodeHex($order_id);
- $orderModel = new \addons\unishop\model\Order();
- $order = $orderModel->where(['id' => $orderId])->find();
- if ($order) {
- $userExtend = (new UserExtend())->where(['user_id' => $order->user_id])->find();
- if (!$userExtend) {
-
- (new UserExtend())->save(['user_id' => $order->user_id, 'openid' => $user->getId()]);
- }
-
- $url = 'https://'.$_SERVER['HTTP_HOST'].'/h5/#/pages/money/pay?order_id='.$order_id.'&total='.$order->total_price.'&pay=1';
- header("Location: $url");
- }
- exit;
- }
- }
|