Api.php
13.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
<?php
namespace addons\epay\controller;
use addons\epay\library\Service;
use addons\epay\library\Wechat;
use addons\third\model\Third;
use app\common\library\Auth;
use Exception;
use think\addons\Controller;
use think\Db;
use think\Response;
use think\Session;
use app\api\controller\Index;
use Yansongda\Pay\Exceptions\GatewayException;
use Yansongda\Pay\Pay;
/**
* API接口控制器
*
* @package addons\epay\controller
*/
class Api extends Controller
{
protected $layout = 'default';
protected $config = [];
/**
* 默认方法
*/
public function index()
{
return;
}
/**
* 外部提交
*/
public function submit()
{
$this->request->filter('trim');
$out_trade_no = $this->request->request("out_trade_no");
$title = $this->request->request("title");
$amount = $this->request->request('amount');
$type = $this->request->request('type', $this->request->request('paytype'));
$method = $this->request->request('method', 'web');
$openid = $this->request->request('openid', '');
$auth_code = $this->request->request('auth_code', '');
$notifyurl = $this->request->request('notifyurl', '');
$returnurl = $this->request->request('returnurl', '');
if (!$amount || $amount < 0) {
$this->error("支付金额必须大于0");
}
if (!$type || !in_array($type, ['alipay', 'wechat'])) {
$this->error("支付类型错误");
}
$params = [
'type' => $type,
'out_trade_no' => $out_trade_no,
'title' => $title,
'amount' => $amount,
'method' => $method,
'openid' => $openid,
'auth_code' => $auth_code,
'notifyurl' => $notifyurl,
'returnurl' => $returnurl,
];
return Service::submitOrder($params);
}
/**
* 微信支付(公众号支付&PC扫码支付)
*/
public function wechat()
{
$config = Service::getConfig('wechat');
$isWechat = stripos($this->request->server('HTTP_USER_AGENT'), 'MicroMessenger') !== false;
$isMobile = $this->request->isMobile();
$this->view->assign("isWechat", $isWechat);
$this->view->assign("isMobile", $isMobile);
//发起PC支付(Scan支付)(PC扫码模式)
if ($this->request->isAjax()) {
$pay = Pay::wechat($config);
$orderid = $this->request->post("orderid");
try {
$result = Service::isVersionV3() ? $pay->find(['out_trade_no' => $orderid]) : $pay->find($orderid, 'scan');
$this->success("", "", ['status' => $result['trade_state'] ?? 'NOTPAY']);
} catch (GatewayException $e) {
$this->error("查询失败(1001)");
}
}
$orderData = Session::get("wechatorderdata");
if (!$orderData) {
$this->error("请求参数错误");
}
if ($isWechat && $isMobile) {
//发起公众号(jsapi支付),openid必须
//如果没有openid,则自动去获取openid
if (!isset($orderData['openid']) || !$orderData['openid']) {
$orderData['openid'] = Service::getOpenid();
}
$orderData['method'] = 'mp';
$type = 'jsapi';
$payData = Service::submitOrder($orderData);
if (!isset($payData['paySign'])) {
$this->error("创建订单失败,请返回重试", "");
}
} else {
$orderData['method'] = 'scan';
$type = 'pc';
$payData = Service::submitOrder($orderData);
if (!isset($payData['code_url'])) {
$this->error("创建订单失败,请返回重试", "");
}
}
$this->view->assign("orderData", $orderData);
$this->view->assign("payData", $payData);
$this->view->assign("type", $type);
$this->view->assign("title", "微信支付");
return $this->view->fetch();
}
/**
* 支付宝支付(PC扫码支付)
*/
public function alipay()
{
$config = Service::getConfig('alipay');
$isWechat = stripos($this->request->server('HTTP_USER_AGENT'), 'MicroMessenger') !== false;
$isMobile = $this->request->isMobile();
$this->view->assign("isWechat", $isWechat);
$this->view->assign("isMobile", $isMobile);
if ($this->request->isAjax()) {
$orderid = $this->request->post("orderid");
$pay = Pay::alipay($config);
try {
$result = $pay->find(['out_biz_no' => $orderid]);
if ($result['code'] == '10000' && $result['trade_status'] == 'TRADE_SUCCESS') {
$this->success("", "", ['status' => $result['trade_status']]);
} else {
$this->error("查询失败");
}
} catch (GatewayException $e) {
$this->error("查询失败(1001)");
}
}
//发起PC支付(Scan支付)(PC扫码模式)
$orderData = Session::get("alipayorderdata");
if (!$orderData) {
$this->error("请求参数错误");
}
$orderData['method'] = 'scan';
$payData = Service::submitOrder($orderData);
if (!isset($payData['qr_code'])) {
$this->error("创建订单失败,请返回重试");
}
$type = 'pc';
$this->view->assign("orderData", $orderData);
$this->view->assign("payData", $payData);
$this->view->assign("type", $type);
$this->view->assign("title", "支付宝支付");
return $this->view->fetch();
}
/**
* 支付成功回调
*/
public function notifyx()
{
$paytype = $this->request->param('paytype');
$pay = Service::checkNotify($paytype);
if (!$pay) {
return json(['code' => 'FAIL', 'message' => '失败'], 500, ['Content-Type' => 'application/json']);
}
// 获取回调数据,V3和V2的回调接收不同
$data = Service::isVersionV3() ? $pay->callback() : $pay->verify();
try {
//微信支付V3返回和V2不同
if (Service::isVersionV3() && $paytype === 'wechat') {
$data = $data['resource']['ciphertext'];
$data['total_fee'] = $data['amount']['total'];
}
\think\Log::record($data);
//获取支付金额、订单号
$payamount = $paytype == 'alipay' ? $data['total_amount'] : $data['total_fee'] / 100;
$out_trade_no = $data['out_trade_no'];
\think\Log::record("回调成功,订单号:{$out_trade_no},金额:{$payamount}");
//你可以在此编写订单逻辑
} catch (Exception $e) {
\think\Log::record("回调逻辑处理错误:" . $e->getMessage(), "error");
}
//下面这句必须要执行,且在此之前不能有任何输出
if (Service::isVersionV3()) {
return $pay->success()->getBody()->getContents();
} else {
return $pay->success()->send();
}
}
/**
* 支付成功返回
*/
public function returnx()
{
$paytype = $this->request->param('paytype');
if (Service::checkReturn($paytype)) {
echo '签名错误';
return;
}
//你可以在这里定义你的提示信息,但切记不可在此编写逻辑
$this->success("恭喜你!支付成功!", addon_url("epay/index/index"));
}
/**
* 年检支付成功回调
*/
public function OrderPayNtf()
{
$type = $this->request->param('paytype', 'wechat');
file_put_contents("pcl_pay_p.log", date("Y-m-d H:i:s") . "::" . json_encode($this->request->param(), JSON_UNESCAPED_UNICODE) . PHP_EOL, FILE_APPEND);
$pay = \addons\epay\library\Service::checkNotify($type);
if (!$pay) {
echo '签名错误';
return;
}
$data = $pay->verify();
$payamount = $type == 'alipay' ? $data['total_amount'] : $data['total_fee'] / 100;
$out_trade_no = $data['out_trade_no'];
//你可以在此编写订单逻辑
//判断是否已更新过支付状态
$cks = Db::name('order')
->where(['order_no' => $data['out_trade_no']])
->find();
file_put_contents("pcl_pay_logs.log", date("Y-m-d H:i:s") . "::" . json_encode($cks, JSON_UNESCAPED_UNICODE) . PHP_EOL, FILE_APPEND);
$this->senWxmsgToDriverUser($cks['id']);
if($cks['rebook']==0){
$order['commission_pay'] = 1;
$rs = Db::name('order')
->where(['order_no' => $data['out_trade_no']])
->update($order);
}else if (!empty($cks) && $cks['is_pay'] == '2') {
//更新订单信息
$order['transaction_id'] = $data['transaction_id'];
$order['is_pay'] = 1;
$order['pay_time'] = time();
$order['update_time'] = time();
$rs = Db::name('order')
->where(['order_no' => $data['out_trade_no']])
->update($order);
SendMessage($cks['id']);
}
//生成订单日志
if ($rs) {
if($order['type']==1){
$orderlog['content'] = '计票消费';
}elseif($order['type']==2){
$orderlog['content'] = '城际消费';
}elseif($order['type']==3){
$orderlog['content'] = '包车消费';
}
$orderlog['order_id'] = $cks['id'];
$orderlog['price'] = $order['price'];
$orderlog['user_id'] = $cks['user_id'];
$orderlog['createtime'] = time();
Db::name('order_log')->insert($orderlog);
//$this->SendMessage($cks['id']);
}
//你可以在这里你的业务处理逻辑,比如处理你的订单状态、给会员加余额等等功能
//下面这句必须要执行,且在此之前不能有任何输出
return $pay->success()->send();
}
function senWxmsgToDriverUser($order_id)
{
$order=Db::name("order")->find($order_id);
if($order['driver_id']){
$order['start']=$order['starting_point'];
$order['to']=$order['end_point'];
$order['timeStr']=$order['reservation_time'];
$driver=Db::name("driver")->find($order['driver_id']);
$car=Db::name("car")->where("driver_id",$driver['id'])->find();
$user=Db::name("user")->find($driver['user_id']);
$wct_user=Db::name("wct_user")->where("unionid",$user['unionid'])->find();
$wxopenid=$wct_user['wx_openid'];
$substring = mb_substr($driver['name'], 0, 1); // "Hello"
$sendInfo = array(
'first' => array('value' => "汽车票出票状态通知", 'color' => "#743A3A"),
'thing2' => array('value' => "{$order['starting_point']}-{$order['end_point']}", 'color' => '#173177'),
'time3' => array('value' =>date("Y-m-d H:i:s",$order['departure_time']), 'color' => '#173177'),
'thing7' => array('value' =>"{$order['position']}", 'color' => '#173177'),
'thing8' => array('value' => "{$substring}师傅{$car['license_plate']}", 'color' => '#173177'),
'phone_number5' => array('value' => "{$order['phone']}", 'color' => '#173177'),
);
if ($wxopenid) {
$config = get_addon_config('wechat');
$tourl = '';
$ywt_appid = 'wx58ceff4e93cfc523';
$pagepath ='pages/module/cityOrders?params='.json_encode($order);
$res = $this->sendAstuWxMsgToAgent($sendInfo, $wxopenid, $tourl, $config['app_id'], $config['secret'], $ywt_appid, $pagepath);
//file_put_contents("pcl_wct_send.log", date("Y-m-d H:i:s") . "1-2-" . json_encode($res, JSON_UNESCAPED_UNICODE) . PHP_EOL, FILE_APPEND);
}
}
}
/**
* 微信公众号
* 用户下订单 消息推送
*/
function sendAstuWxMsgToAgent($info, $openid, $tourl, $appid, $secret, $ywt_appid, $pagepath)
{
$myurl = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" . $appid . "&secret=" . $secret;
$json_token = $this->http_request($myurl);
$access_tokens = json_decode($json_token, true);
$access_token = $access_tokens['access_token'];
$template = array(
'touser' => $openid, //
'template_id' => 'zQaLnhEOQxdGOKJlDUAfEl8sL4a3qchtiXtP-n_rupI', //模板消息id 必须修改
'url' => $tourl, //点击链接
"miniprogram" => [
'appid' => $ywt_appid,
'pagepath' => $pagepath
],
'topcolor' => "#173177",
'data' => $info
);
$json_template = json_encode($template);
$url = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=" . $access_token;
$json = $this->http_request($url, urldecode($json_template));
$rs = json_decode($json, true);
return $rs;
}
function http_request($url, $data = array())
{
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
// 我们在POST数据哦!
curl_setopt($ch, CURLOPT_POST, 1);
// 把post的变量加上
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
$output = curl_exec($ch);
curl_close($ch);
return $output;
}
}