dggjimai/application/api/controller/PaymentController.php

93 lines
3.1 KiB
PHP
Executable File
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\api\controller;
use app\common\model\User;
use app\common\model\Order;
use app\common\model\ShopConfig;
use Exception;
use think\Request;
use think\response\Json;
use tools\Crypt;
use tools\WxxiaopayApi;
use think\facade\Log;
class PaymentController extends Controller
{
protected $authExcept = [
'wxnotify'
];
/**
* Notes: 预支付
*/
public function prepay(Request $request,Order $omodel)
{
$param = $request->param();
$user_id = $param['uid']?Crypt::decrypt($param['uid']):'';
if(!$user_id){
return unauthorized('请先授权');
}
$order_sn=$param['order_sn']??'';
if(!isset($order_sn)) {
return client_error('订单不存在');
}
$order = $omodel
->alias('o')
->field("order_status,openid")
->join('user u', 'u.id = o.user_id')
->where(array('order_sn'=>$order_sn,'user_id'=>$user_id))
->find();
//找不到订单
if (empty($order)) {
return client_error('订单不存在');
}
if ($order['order_status'] !='0') {
return client_error('该订单无法进行支付,请查看订单状态');
}
$order_wechatsn =$order_sn.str_pad(mt_rand(1, 999), 3, '0', STR_PAD_LEFT);
$WXPAYKEY=ShopConfig::get('website', 'WXPAYKEY');
$MCHID=ShopConfig::get('website', 'MCHID');
$APPID=ShopConfig::get('website', 'APPID');
$notify_url=ShopConfig::get('website', 'notify_url');
$WxxiaopayApi = new WxxiaopayApi($APPID,$MCHID,$WXPAYKEY,$notify_url);
$log_ip=$request->ip();
$wxData =$WxxiaopayApi->prePay($order_sn,$order_wechatsn,'0.01',$order['openid'],$log_ip);
return success($wxData);
}
//微信小程序回调
public function wxnotify(Request $request,Order $omodel)
{
$xml = file_get_contents('php://input', 'r');
$data = $this->toArray($xml);
Log::write('微信回调2'.var_export($data, true));
if($data['result_code']==='SUCCESS' && $data['return_code']==='SUCCESS'){
$order_sn = mb_substr($data['out_trade_no'],0,18);
$parameter['transaction_id']= $data['transaction_id']; //支付宝交易号
$parameter['pay_time'] =time();
$parameter['order_status'] =1;
$order_info = $omodel
->where(array('order_sn'=>$order_sn))
->find();
if($order_info){
$omodel->where(array('id'=>$order_info['id']))->update($parameter);
exit('success');
}
}
exit('fail');
}
/**
* 将xml转为array
* @param string $xml xml字符串
* @return array 转换得到的数组
*/
public function toArray($xml) {
//禁止引用外部xml实体
libxml_disable_entity_loader(true);
$result= json_decode(json_encode(simplexml_load_string($xml, 'SimpleXMLElement', LIBXML_NOCDATA)), true);
return $result;
}
}