123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338 |
- <?php
- namespace app\api\controller\v1;
- use app\BaseController;
- use app\model\api\Member;
- use app\model\api\Order;
- use app\model\api\OrderInfo;
- use app\model\api\Product;
- use app\model\api\Recharge;
- use app\Request;
- use EasyWeChat\Factory;
- use library\lib\weixina;
- use library\services\UtilService;
- use library\services\MiniProgramService;
- use think\db\exception\DbException;
- use think\db\exception\PDOException;
- use think\Exception;
- use think\facade\Db;
- class Weixin extends BaseController
- {
- public function jssdk(Request $request){
- $config = [
- 'app_id' => config('weixin')['APPID'],
- 'secret' => config('weixin')['APPSECRET'],
- // 指定 API 调用返回结果的类型:array(default)/collection/object/raw/自定义类名
- 'response_type' => 'array'
- ];
- $app = Factory::officialAccount($config);
- $apiList = ['openAddress','updateAppMessageShareData','updateTimelineShareData','onMenuShareAppMessage','onMenuShareTimeline'];
- $jssdk = $app->jssdk->buildConfig($apiList, $debug = false, $beta = false, $json = false, [], $url = $request->get('url'));
- return app('json')->success($jssdk);
- }
- /**
- * 公众号获取微信信息
- */
- public function getInfo(Request $request)
- {
- $code = trim($request->get('code'));
- $weixinA = new weixina;
- $token = $weixinA->oauth_reuslt($code);
- if (!empty($token['access_token'])) {
- $userInfo = $weixinA->userinfo($token['access_token']);
- $member = (new Member)->where('uid',$request->user['uid'])->find();
- if($member['routine_openid']){
- (new Member)->where('uid',$request->user['uid'])->save(['openid' => $userInfo['openid']]);
- }else{
- $data['openid'] = $userInfo['openid'];
- $data['nickname'] = $userInfo['nickname'];
- $data['sex'] = $userInfo['sex'];
- $data['language'] = $userInfo['language'];
- $data['city'] = $userInfo['city'];
- $data['province'] = $userInfo['province'];
- $data['country'] = $userInfo['country'];
- $data['avatar'] = $userInfo['headimgurl'];
- (new Member)->where('uid',$request->user['uid'])->save($data);
- }
- return app('json')->success([
- 'nickname' => $data['nickname'],
- 'avatar' => $data['avatar']
- ]);
- }
- }
- /**
- * 小程序获取手机号
- */
- public function getPhone(Request $request)
- {
- $post = UtilService::getMore([
- ['code', '', 'empty', '参数错误'],
- ['iv', ''],
- ['encryptedData', '']
- ]);
- $mini = Factory::miniProgram(config('weixin')['mini_program']);
- $new_mini = $mini->auth->session($post['code']);
- $decryptData = $mini->encryptor->decryptData($new_mini['session_key'], $post['iv'], $post['encryptedData']);
- return app('json')->success($decryptData['phoneNumber']);
- }
- /**
- * 小程序授权登录
- * @param Request $request
- * @return mixed
- * @throws \Psr\SimpleCache\InvalidArgumentException
- * @throws \think\db\exception\DataNotFoundException
- * @throws \think\db\exception\ModelNotFoundException
- * @throws \think\exception\DbException
- */
- public function mp_auth(Request $request){
- $post = UtilService::getMore([
- ['code', '', 'empty', '参数错误'],
- ['iv', ''],
- ['encryptedData', '']
- ]);
- try {
- $mini = Factory::miniProgram(config('weixin')['mini_program']);
- $new_mini = $mini->auth->session($post['code']);
- $member = (new Member)->where('uid',$request->user['uid'])->find();
- if($member['openid']){
- (new Member)->where('uid',$request->user['uid'])->save(['routine_openid' => $new_mini['openid']]);
- }else{
- $userInfo = $mini->encryptor->decryptData($new_mini['session_key'], $post['iv'], $post['encryptedData']);
- $data['routine_openid'] = $new_mini['openid'];
- $data['nickname'] = $userInfo['nickName'];
- $data['sex'] = $userInfo['gender'];
- $data['language'] = $userInfo['language'];
- $data['city'] = $userInfo['city'];
- $data['province'] = $userInfo['province'];
- $data['country'] = $userInfo['country'];
- $data['avatar'] = $userInfo['avatarUrl'];
- (new Member)->where('uid',$request->user['uid'])->save($data);
- return app('json')->success([
- 'nickname' => $data['nickname'],
- 'avatar' => $data['avatar']
- ]);
- }
- } catch (\Exception $e) {
- return app('json')->fail('获取session_key失败', ['line' => $e->getLine(), 'message' => $e->getMessage()]);
- }
- }
- /**
- * @param Request $request
- */
- public function result(Request $request)
- {
- $state = trim($request->get('state'));
- $code = trim($request->get('code'));
- if (empty($state)) {
- exit('error');
- }
- $weixinA = new weixina;
- $data = $weixinA->oauth_reuslt($code);
- if (!empty($data['access_token'])) {
- $userInfo = $weixinA->userinfo($data['access_token']);
- $userInfo['access_token'] = $data['access_token'];
- $userInfo['expires_in'] = $data['expires_in'];
- $userInfo['time'] = time();
- cookie("weix_userinfo", serialize($userInfo));
- $url = setParam(cookie('w_url'), ['data' => json_encode($userInfo, \JSON_UNESCAPED_UNICODE)]);
- redirect($url)->send();
- } else {
- exit('微信授权登录失败,关闭页面重新,重新扫描!');
- }
- }
- public function pay(Request $request)
- {
- [$orderId, $from] = UtilService::getMore([
- ['order_id', '', 'empty', '参数错误'],
- ['from', '', 'empty', '参数错误'],
- ], $request, true);
- $order = Order::where('order_id', $orderId)->find();
- if (empty($order)) {
- return app('json')->fail('找不到订单信息');
- }
- //订单已付款
- if (!empty($order['is_pay'])) {
- return app('json')->fail('订单已经支付成功');
- }
- $data['out_trade_no'] = $order['order_id'];
- $data['money'] = $order['all_price'];
- $data['type'] = 'order';
- $data['time'] = time();
- Db::name('wx_notify')->insert($data);
- if ($from == 'weixin') {
- $app = Factory::payment(config('weixin')['wxPay']);
- $result = $app->order->unify([
- 'body' => '支付订单',
- 'out_trade_no' => $order['order_id'],
- 'total_fee' => $order['all_price'] * 100,
- 'notify_url' => 'https://www.boofly.cn/api/weixin/notify', // 支付结果通知网址,如果不设置则会使用配置里的默认地址
- 'trade_type' => 'JSAPI', // 请对应换成你的支付方式对应的值类型
- 'openid' => $request->user['openid']
- ]);
- $jssdk = $app->jssdk;
- $jsConfig = $jssdk->bridgeConfig($result['prepay_id'], false);
- $json['result'] = $jsConfig;
- $json['type'] = 'WECHAT_PAY';
- }
- if ($from == 'h5') {
- $app = Factory::payment(config('weixin')['wxPay']);
- $result = $app->order->unify([
- 'body' => '支付订单',
- 'out_trade_no' => $order['order_id'],
- 'total_fee' => $order['all_price'] * 100,
- 'notify_url' => 'https://www.boofly.cn/api/weixin/notify', // 支付结果通知网址,如果不设置则会使用配置里的默认地址
- 'trade_type' => 'MWEB' // 请对应换成你的支付方式对应的值类型
- ]);
- $jssdk = $app->jssdk;
- $jsConfig = $jssdk->bridgeConfig($result['prepay_id'], false);
- $json['result'] = $jsConfig;
- $json['type'] = 'WECHAT_H5_PAY';
- }
- if ($from == 'routine') {
- $app = Factory::payment(config('weixin')['routinePay']);
- $result = $app->order->unify([
- 'body' => '支付订单',
- 'out_trade_no' => $order['order_id'],
- 'total_fee' => $order['all_price'] * 100,
- 'notify_url' => 'https://www.boofly.cn/api/weixin/notify', // 支付结果通知网址,如果不设置则会使用配置里的默认地址
- 'trade_type' => 'JSAPI', // 请对应换成你的支付方式对应的值类型
- 'openid' => $request->user['routine_openid']
- ]);
- $jssdk = $app->jssdk;
- $jsConfig = $jssdk->bridgeConfig($result['prepay_id'], false);
- $json['result'] = $jsConfig;
- $json['type'] = 'ROUTINE_PAY';
- }
- return app('json')->success($json);
- }
- public function recharge(Request $request)
- {
- [$money, $from] = UtilService::getMore([
- ['money', '', 'empty', '请选择充值金额'],
- ['from', '', 'empty', '参数错误']
- ], $request, true);
- try {
- Recharge::beginTrans();
- $recharge = new Recharge();
- $d = [];
- $d['order_id'] = 'RE' . time() . sprintf('%04d', rand(0, 1000)) . $request->user['uid'];
- $d['v'] = $money;
- $d['time'] = time();
- $d['uid'] = $request->user['uid'];
- $recharge->insert($d);
- //生成支付凭证
- $data['out_trade_no'] = $d['order_id'];
- $data['money'] = $money;
- $data['type'] = 'recharge';
- $data['time'] = time();
- Db::name('wx_notify')->insert($data);
- Recharge::commitTrans();
- $app = Factory::payment(config('weixin')['wxPay']);
- if ($from == 'weixin') {
- $result = $app->order->unify([
- 'body' => '充值余额',
- 'out_trade_no' => $d['order_id'],
- 'total_fee' => $money * 100,
- 'notify_url' => 'https://www.boofly.cn/api/weixin/notify', // 支付结果通知网址,如果不设置则会使用配置里的默认地址
- 'trade_type' => 'JSAPI', // 请对应换成你的支付方式对应的值类型
- 'openid' => $request->user['openid'],
- ]);
- $jssdk = $app->jssdk;
- $jsConfig = $jssdk->bridgeConfig($result['prepay_id'], false);
- $json['result'] = $jsConfig;
- $json['type'] = 'WECHAT_PAY';
- } else {
- $result = $app->order->unify([
- 'body' => '充值余额',
- 'out_trade_no' => $d['order_id'],
- 'total_fee' => $money * 100,
- 'notify_url' => 'https://www.boofly.cn/api/weixin/notify', // 支付结果通知网址,如果不设置则会使用配置里的默认地址
- 'trade_type' => 'MWEB' // 请对应换成你的支付方式对应的值类型
- ]);
- $json['result'] = $result;
- $json['type'] = 'WECHAT_H5_PAY';
- }
- return app('json')->success($json);
- } catch (DbException $db) {
- Recharge::rollbackTrans();
- return app('json')->fail("充值失败,请联系客服人员");
- }
- }
- /**
- * @throws \Exception
- */
- public function notify()
- {
- // 获取微信回调的数据
- $notifiedData = file_get_contents('php://input');
- //XML格式转换
- $xmlObj = simplexml_load_string($notifiedData, 'SimpleXMLElement', LIBXML_NOCDATA);
- $xmlObj = json_decode(json_encode($xmlObj), true);
- // 当支付通知返回支付成功时
- if ($xmlObj['return_code'] == "SUCCESS" && $xmlObj['result_code'] == "SUCCESS") {
- try {
- $data['appid'] = $xmlObj['appid'];
- $data['bank_type'] = $xmlObj['bank_type'];
- $data['cash_fee'] = $xmlObj['cash_fee'];
- $data['fee_type'] = $xmlObj['fee_type'];
- $data['is_subscribe'] = $xmlObj['is_subscribe'];
- $data['mch_id'] = $xmlObj['mch_id'];
- $data['nonce_str'] = $xmlObj['nonce_str'];
- $data['openid'] = $xmlObj['openid'];
- $data['result_code'] = $xmlObj['result_code'];
- $data['return_code'] = $xmlObj['return_code'];
- $data['sign'] = $xmlObj['sign'];
- $data['time_end'] = $xmlObj['time_end'];
- $data['total_fee'] = $xmlObj['total_fee'];
- $data['trade_type'] = $xmlObj['trade_type'];
- $data['transaction_id'] = $xmlObj['transaction_id'];
- $data2 = Db::name('wx_notify')->where('out_trade_no', $xmlObj['out_trade_no'])->find();
- if (empty($data2)) {
- echo 'SUCCESS';
- exit;
- }
- $res = Db::name('wx_notify')->where('out_trade_no',$xmlObj['out_trade_no'])->save($data);
- if($res){
- if ($data2['type'] == 'order') {
- $order = Order::where('order_id', $xmlObj['out_trade_no'])->find();
- //减库存加销量
- Product::where('id', $order['pro_id'])->dec('stock', $order['num'])->inc('sales', $order['num'])->update();
- Db::name('ProductAttrValue')->where('product_id', $order['pro_id'])->where('unique', $order['unique'])->dec('stock', $order['num'])->inc('sales', $order['num'])->update();
- //改订单状态
- Order::where('order_id', $xmlObj['out_trade_no'])->save([
- 'status' => 1,
- 'is_pay' => 1,
- 'pay_type' => 'weixin',
- 'pay_time' => time()
- ]);
- //改子订单状态
- OrderInfo::where('o_id', $order['id'])->save(['status' => 1,]);
- Member::where('uid', $order['uid'])->save(['last_con_time' => time()]);
- }
- if ($data2['type'] == 'recharge') {
- $recharge = new Recharge();
- $recharge->rechargeSuccess($xmlObj['out_trade_no']);
- }
- echo 'SUCCESS';
- exit;
- }
- } catch (Exception $e) {
- @file_put_contents('error.txt', '[' . date('Y-m-d') . ']Exception:' . json_encode(['Msg' => $e->getMessage(), 'File' => $e->getFile(), 'Line' => $e->getLine(), 'Trance' => $e->getTrace()]) . PHP_EOL, FILE_APPEND);
- } catch (DbException $e) {
- @file_put_contents('error.txt', '[' . date('Y-m-d') . ']DbException:' . json_encode(['Msg' => $e->getMessage(), 'File' => $e->getFile(), 'Line' => $e->getLine(), 'Trance' => $e->getTrace()]) . PHP_EOL, FILE_APPEND);
- } catch (\Exception $e) {
- @file_put_contents('error.txt', '[' . date('Y-m-d') . ']\Exception:' . json_encode(['Msg' => $e->getMessage(), 'File' => $e->getFile(), 'Line' => $e->getLine(), 'Trance' => $e->getTrace()]) . PHP_EOL, FILE_APPEND);
- }
- }
- }
- }
|