first commit

This commit is contained in:
编码猿
2024-09-27 01:32:49 +08:00
commit 28ebe05a64
7399 changed files with 1174529 additions and 0 deletions

View File

@@ -0,0 +1 @@
41317f36-53f7-47a0-ad5d-d0e65a032eae

View File

@@ -0,0 +1,131 @@
<?php
/**
* Created by PhpStorm.
* User: Administrator
* Date: 2020/4/17
* Time: 13:26
*/
namespace app\api\service;
use app\api\model\Order as OrderModel;
use app\lib\exception\ParamException;
use think\Log;
class Order
{
protected $uid;
protected $totalMoney;
/**
* @param array $orderInfo 下单信息
* @return array 订单状态
* @throws Exception
*/
public function place($uid,$orderInfo)
{
$this->uid = $uid;
//判断是否有该权限商品
$this->getProductByType($orderInfo['vip_type']);
//判断订单是否已购买
$resOrder = $this->checkOrderStatus($uid,$orderInfo);
//有待支付的订单提交支付,没有则创建新订单
if($resOrder){
$status = [
'order_id' => $resOrder
];
}else{
//创建订单
$status = self::createOrderBy($orderInfo);
}
$status['pass'] = true;
return $status;
}
//创建订单
private function createOrderBy($orderInfo)
{
$orderNo = $this->makeOrderNo();
$order = new OrderModel();
$order->user_id = $this->uid;
$order->ord_no = $orderNo;
$order->money = $this->totalMoney;
$order->score = $orderInfo['score'];
$order->telnum = $orderInfo['telnum'];
$order->wenli = $orderInfo['subType'];
$order->mykemu = $orderInfo['mySub'];
$order->stu_yzy_province = $orderInfo['userPro'];
$order->stu_province = $orderInfo['province']*10000;
$order->province_title = config('province.province')[$order->stu_province]['title'];
if($order->mykemu){
$order->mykemu = sortStr($orderInfo['mySub']);
$order->mykemustr = changeSubString($order->mykemu);
}else{
$order->mykemustr = '';
}
$order->vip = $orderInfo['vip_type'];
$order->add_time = time();
$order->save();
if($order->id){
return [
'order_no' => $orderNo,
'order_id' => $order->id,
'create_time' => $order->add_time
];
}else{
return api_error("订单创建失败!");
}
}
/*
* 判断价格是否匹配
* */
private function getProductByType($type){
$productArr = config('product.vipType');
if(array_key_exists($type,$productArr)){
$this->totalMoney = $productArr[$type];
}else{
throw new ParamException([
'msg' => '购买的权限不存在',
'erroCode' => 10000,
'code' => 404
]);
}
}
//生成订单号
public static function makeOrderNo()
{
$yCode = array('A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J');
$orderSn =
$yCode[intval(date('Y')) - 2019] . strtoupper(dechex(date('m'))) . date(
'd') . substr(time(), -5) . substr(microtime(), 2, 5) . sprintf(
'%02d', rand(0, 99));
return $orderSn;
}
/*
* 判断用户是否购买该分数下的订单
* */
public function checkOrderStatus($uid,$orderInfo){
$result = OrderModel::checkOrder($uid,$orderInfo['score'],$orderInfo['userPro'],$orderInfo['vip_type'],$orderInfo['subType'],$orderInfo['mySub']);
if($result){
if($result['status'] == 1){
throw new ParamException([
'msg' => '订单已存在并支付过啦',
'erroCode' => 10000,
'code' => 400
]);
}else{
return $result['id'];
}
}
}
}

View File

@@ -0,0 +1,253 @@
<?php
/**
* Created by PhpStorm.
* User: Administrator
* Date: 2020/4/17
* Time: 21:07
*/
namespace app\api\service;
use app\api\model\Order as OrderModel;
use app\api\service\Order as OrderService;
use app\lib\exception\ParamException;
use \think\facade\Log;
require '../extend/WxPay/WxPay.Api.php';
class Pay
{
private $orderNo;
private $payWay;
private $payType;
private $orderID;
function __construct($orderID,$payType,$payWay)
{
if (!$orderID)
{
throw new Exception('订单号不允许为NULL');
}
$this->orderID = $orderID;
$this->payType = $payType;
$this->payWay = $payWay;
}
//微信H5支付
public function wapPay($user_id,$rebackUrl){
$resOrder = $this->checkOrderValid( $this->orderID,$user_id);
//调用统一下单接口
$wxOrderData = new \WxPayUnifiedOrder();
$wxOrderData->SetOut_trade_no( $resOrder['ord_no']);
$wxOrderData->SetTrade_type('MWEB');
$wxOrderData->SetTotal_fee($resOrder['money']*100);
$wxOrderData->setBody('聚志愿');
$wxOrderData->SetNotify_url(config('secure.pay_back_url'));
$wxOrder = \WxPayApi::unifiedOrder($wxOrderData);
$url = $wxOrder['mweb_url'].'&redirect_url='.$rebackUrl;//redirect_url 是支付完成后返回的页面
return $url;
}
//微信扫码支付
public function codePay($user_id){
//
$resOrder = $this->checkOrderValid( $this->orderID,$user_id);
//调用统一下单接口
$wxOrderData = new \WxPayUnifiedOrder();
$wxOrderData->SetOut_trade_no($resOrder['ord_no']);
$wxOrderData->SetTrade_type('NATIVE');
$wxOrderData->SetTime_start(date("YmdHis"));
$wxOrderData->SetTime_expire(date("YmdHis", time() + 600));
$wxOrderData->SetProduct_id($resOrder['vip']);
$wxOrderData->SetTotal_fee($resOrder['money']*100);
$wxOrderData->setBody('聚志愿');
$wxOrderData->SetNotify_url(config('secure.pay_back_url'));
$wxOrder = \WxPayApi::unifiedOrder($wxOrderData);
if($wxOrder['result_code']=='SUCCESS' && $wxOrder['return_code']=='SUCCESS') {
$url = $wxOrder["code_url"];
return $url;
}else{
throw new ParamException([
'msg' => '参数错误',
'errorCode' => 10000,
'code' => 400
]);
}
}
//支付宝wap支付
public function alipay_wap($user_id,$rebackUrl)
{
$resOrder = $this->checkOrderValid( $this->orderID,$user_id);
require '../extend/alipay/aop/AopClient.php';// 加载交易服务
//商品参数
$array['body'] = "聚志愿";
$array['subject'] = "聚志愿vip权限";
$array['out_trade_no'] = $resOrder['ord_no'];
$array['timeout_express'] = "5m";
$array['total_amount'] = $resOrder['money'];
$array['product_code'] = "QUICK_WAP_WAY";
$aop = new \AopClient ();
//支付配置参数
$aop->gatewayUrl = 'https://openapi.alipay.com/gateway.do';
$aop->appId = config('alipay.app_id');
$aop->rsaPrivateKey = config('alipay.merchant_private_key');
$aop->alipayrsaPublicKey=config('alipay.alipay_public_key');
$aop->signType='RSA2';
$aop->format = "json";
require '../extend/alipay/aop/request/AlipayTradeWapPayRequest.php';// 加载交易服务
$request = new \AlipayTradeWapPayRequest ();
$request->setBizContent(json_encode($array));
//回调地址
$request->setReturnUrl($rebackUrl);
$request->setNotifyUrl(config('alipay.notify_url'));
$result = $aop->pageExecute($request, "POST");
return $result;
}
//支付宝pc支付
public function alipay_pc($user_id,$rebackUrl)
{
$resOrder = $this->checkOrderValid( $this->orderID,$user_id);
require '../extend/alipaypage/pagepay/service/AlipayTradeService.php';// 加载交易服务
require '../extend/alipaypage/pagepay/buildermodel/AlipayTradePagePayContentBuilder.php';
//商品参数
$body = "聚志愿";
$subject = "聚志愿vip权限";
$out_trade_no= $resOrder['ord_no'];
$timeout_express = "5m";
$total_amount = $resOrder['money'];
$payRequestBuilder = new \AlipayTradePagePayContentBuilder();
$payRequestBuilder->setBody($body);
$payRequestBuilder->setSubject($subject);
$payRequestBuilder->setTotalAmount($total_amount);
$payRequestBuilder->setOutTradeNo($out_trade_no);
$payRequestBuilder->setTimeExpress($timeout_express);
$config = config('alipay.');
$aop = new \AlipayTradeService($config);
$result = $aop->pagePay($payRequestBuilder,$rebackUrl,$config['notify_url']);
return $result;
}
//小程序支付
public function pay()
{
// 订单号可能不存在
//订单号和用户不匹配
//订单可能倍支付过
//进行库存量检测
$this->checkOrderValid();
$orderService = new OrderService();
$status = $orderService->checkOrderStock($this->orderID);
if(!$status['pass']){
return $status;
}
return $this->makeWxPreOrder($status['orderPrice']);
}
// 构建微信支付订单信息
private function makeWxPreOrder($totalPrice){
$openid = Token::getCurrentTokenVar('openid');
if(!$openid){
throw new TokenException();
}
//调用统一下单接口
$wxOrderData = new \WxPayUnifiedOrder();
$wxOrderData->SetOut_trade_no($this->orderNo);
$wxOrderData->SetTrade_type('JSAPI');
$wxOrderData->SetTotal_fee($totalPrice*100);
$wxOrderData->setBody('伊莎商城');
$wxOrderData->SetOpenid($openid);
$wxOrderData->SetNotify_url(config('secure.pay_back_url'));
return $this->getPaySignature($wxOrderData);
}
//向微信请求订单号并生成签名
private function getPaySignature($wxOrderData){
$wxOrder = \WxPayApi::unifiedOrder($wxOrderData);
// 失败时不会返回result_code
if($wxOrder['return_code'] != 'SUCCESS' || $wxOrder['result_code'] !='SUCCESS'){
Log::record($wxOrder,'error');
Log::record('获取预支付订单失败','error');
}
$this->recordPreOrder($wxOrder);
$signature = $this->sign($wxOrder);
return $signature;
}
private function sign($wxOrder){
$jsApiPayData = new \WxPayJsApiPay();
$jsApiPayData->SetAppid(config('wx.app_id'));
$jsApiPayData->SetTimeStamp((string)time());
$rand = md5(time() . mt_rand(0, 1000));
$jsApiPayData->SetNonceStr($rand);
$jsApiPayData->SetPackage('prepay_id=' . $wxOrder['prepay_id']);
$jsApiPayData->SetSignType('md5');
$sign = $jsApiPayData->MakeSign();
$rawValues = $jsApiPayData->GetValues();
$rawValues['paySign'] = $sign;
unset($rawValues['appId']);
return $rawValues;
}
private function recordPreOrder($wxOrder){
// 必须是update每次用户取消支付后再次对同一订单支付prepay_id是不同的
OrderModel::where('id', '=', $this->orderID)
->update(['prepay_id' => $wxOrder['prepay_id']]);
}
/**
* 订单验证
* @return string
* @throws OrderException
* @throws TokenException
*/
private function checkOrderValid($orderTD,$userID){
$order = OrderModel::field('id,ord_no,status,money,vip')->where([['id','=',$orderTD],['user_id','=',$userID]])
->find();
if(!$order){
throw new ParamException([
'msg' => '订单不存在',
'errorCode' => 10004,
'code' => 404
]);
}
if(!Token::isValidOperate($userID)){
throw new ParamException([
'msg' => '订单与用户信息不匹配',
'errorCode' => 10000,
'code' => 400
]);
}
if($order['status'] == 1){
throw new ParamException([
'msg' => '订单已支付过啦',
'errorCode' => 10000,
'code' => 400
]);
}
return $order;
}
}

View File

@@ -0,0 +1,81 @@
<?php
/**
* Created by PhpStorm.
* User: Administrator
* Date: 2020/4/13
* Time: 17:25
*/
namespace app\api\service;
use app\api\controller\Basecontroller;
use app\common\controller\SignatureHelper;
class SendMessage extends Basecontroller
{
/**
* 短信发送api
* @param int $phoneNums 接收短信的手机号
* @param string $SignName 短信签名
* @param string $TemplateCode 短信模板Code
* @param string $code 短信变量
* @return \think\response\Json
*/
public static function sendAliMessage($phoneNums,$SignName,$TemplateCode,$code="")
{
$params = array ();
// *** 需用户填写部分 ***
// fixme 必填是否启用https
$security = false;
// fixme 必填: 请参阅 https://ak-console.aliyun.com/ 取得您的AK信息
$accessKeyId = config('alidayu.AccessKeyID');
$accessKeySecret = config('alidayu.AccessKeySecret');
// fixme 必填: 短信接收号码
$params["PhoneNumbers"] = $phoneNums;
// fixme 必填: 短信签名,应严格按"签名名称"填写,请参考: https://dysms.console.aliyun.com/dysms.htm#/develop/sign
$params["SignName"] = $SignName;
// fixme 必填: 短信模板Code应严格按"模板CODE"填写, 请参考: https://dysms.console.aliyun.com/dysms.htm#/develop/template
$params["TemplateCode"] = $TemplateCode;
// fixme 可选: 设置模板参数, 假如模板中存在变量需要替换则为必填项
if($code){
$params['TemplateParam'] = $code;
}
// fixme 可选: 设置发送短信流水号
//$params['OutId'] = "12345";
// fixme 可选: 上行短信扩展码, 扩展码字段控制在7位或以下无特殊需求用户请忽略此字段
//$params['SmsUpExtendCode'] = "1234567";
// *** 需用户填写部分结束, 以下代码若无必要无需更改 ***
if(!empty($params["TemplateParam"]) && is_array($params["TemplateParam"])) {
$params["TemplateParam"] = json_encode($params["TemplateParam"], JSON_UNESCAPED_UNICODE);
}
// 初始化SignatureHelper实例用于设置参数签名以及发送请求
$helper = new SignatureHelper();
// 此处可能会抛出异常注意catch
$content = $helper->request(
$accessKeyId,
$accessKeySecret,
"dysmsapi.aliyuncs.com",
array_merge($params, array(
"RegionId" => "cn-hangzhou",
"Action" => "SendSms",
"Version" => "2017-05-25",
)),
$security
);
if($content->Message == 'OK')
return ['status'=>1];
else
return ['status'=>0];
}
}

View File

@@ -0,0 +1,65 @@
<?php
/**
* Created by PhpStorm.
* User: Administrator
* Date: 2020/4/13
*/
namespace app\api\service;
use think\Exception;
use think\facade\Cache;
use think\facade\Request;
class Token
{
public static function generateToken(){
$randChar = getRandChar(32);
$timestamp = $_SERVER['REQUEST_TIME_FLOAT'];
$tokenSalt = config('secure.token_salt');
return md5($randChar . $timestamp . $tokenSalt);
}
public static function getCurrentTokenVar($key){
$token = Request::header('token');
// $vars = Cache::get($token);
$vars = Cache::store('redis')->get($token);
if(!$vars){
throw new TokenException();
}else{
if(!is_array($vars))
{
$vars = json_decode($vars, true);
return $vars;
}
if (array_key_exists($key, $vars)) {
return $vars[$key];
}
else{
throw new Exception('尝试获取的Token变量并不存在');
}
}
}
public static function getCurrentUid(){
$uid = self::getCurrentTokenVar('uid');
return $uid;
}
public static function isValidOperate($checkedUID){
if(!$checkedUID){
throw new Exception('检测UID时必须传入一个被检测的UID');
}
$currentOperateUID = self::getCurrentUid();
if($currentOperateUID == $checkedUID){
return true;
}
return false;
}
}

View File

@@ -0,0 +1,180 @@
<?php
/**
* Created by PhpStorm.
* User: Administrator
* Date: 2019/5/25 0025
* Time: 16:47
*/
namespace app\api\service;
use app\lib\exception\ParamException;
use think\Exception;
use app\api\model\User as UserModel;
use think\facade\Cache;
class UserToken extends Token
{
protected $code;
protected $wxLoginUrl;
protected $wxAppID;
protected $wxAppSecret;
function __construct($code)
{
$this->code = $code;
$this->wxAppID = config('wx.app_id');
$this->wxAppSecret = config('wx.app_secret');
$this->wxLoginUrl = sprintf(
config('wx.login_url'), $this->wxAppID, $this->wxAppSecret, $this->code);
}
/**
* 登陆
* 思路1每次调用登录接口都去微信刷新一次session_key生成新的Token不删除久的Token
* 思路2检查Token有没有过期没有过期则直接返回当前Token
* 思路3重新去微信刷新session_key并删除当前Token返回新的Token
*/
public function get($paramPost)
{
$result = curl_get($this->wxLoginUrl);
// 注意json_decode的第一个参数true
// 这将使字符串被转化为数组而非对象
$wxResult = json_decode($result, true);
if (empty($wxResult)) {
// 为什么以empty判断是否错误这是根据微信返回
// 规则摸索出来的
// 这种情况通常是由于传入不合法的code
throw new ParamException([
'code'=>401,
'msg' => '获取session_key及openID时异常微信内部错误',
'errorCode' => 10001
]);
}
else {
// 建议用明确的变量来表示是否成功
// 微信服务器并不会将错误标记为400无论成功还是失败都标记成200
// 这样非常不好判断只能使用errcode是否存在来判断
$loginFail = array_key_exists('errcode', $wxResult);
if ($loginFail) {
$this->processLoginError($wxResult);
}
else {
return $this->grantToken($wxResult,$paramPost);
}
}
}
// 颁发令牌
// 只要调用登陆就颁发新令牌
// 但旧的令牌依然可以使用
// 所以通常令牌的有效时间比较短
// 目前微信的express_in时间是7200秒
// 在不设置刷新令牌refresh_token的情况下
// 只能延迟自有token的过期时间超过7200秒目前还无法确定在express_in时间到期后
// 还能否进行微信支付
// 没有刷新令牌会有一个问题,就是用户的操作有可能会被突然中断
private function grantToken($wxResult)
{
// 此处生成令牌使用的是TP5自带的令牌
// 如果想要更加安全可以考虑自己生成更复杂的令牌
// 比如使用JWT并加入盐如果不加入盐有一定的几率伪造令牌
$openid = $wxResult['openid'];
$user = UserModel::getByOpenID($openid);
if (!$user)
// 借助微信的openid作为用户标识
// 但在系统中的相关查询还是使用自己的uid
{
$uid = $this->newUser($openid);
}
else {
$uid = $user->id;
}
$cachedValue = $this->prepareCachedValue($wxResult, $uid);
$token = $this->saveToCache($cachedValue);
return $token;
}
private function newUser($openid){
$user = UserModel::create([
'openid' =>$openid
]);
return $user->id;
}
//生成token并缓存
private function saveToCache($wxResult){
$key = self::generateToken();
$value = json_encode($wxResult);
$request = Cache::store('redis')->set($key,$value,2592000);
if(!$request){
throw new ParamException([
'code' => 401,
'msg' => '服务起缓存异常',
'errorCode' => 10001
]);
}
return $key;
}
//缓存数据预处理
private function prepareCachedValue($wxResult, $uid)
{
$cachedValue = $wxResult;
$cachedValue['uid'] = $uid;
return $cachedValue;
}
private function processLoginError($wxResult){
throw new ParamException([
'msg' => $wxResult['errmsg'],
'errorCode' => $wxResult['errcode']
]);
}
/**
* 过滤微信昵称的特殊表情
* @param $text
* @param string $replaceTo
* @return null|string|string[]
*/
public function filterEmoji($text, $replaceTo = 'x'){
$clean_text = "";
// Match Emoticons
$regexEmoticons = '/[\x{1F600}-\x{1F64F}]/u';
$clean_text = preg_replace($regexEmoticons, $replaceTo, $text);
// Match Miscellaneous Symbols and Pictographs
$regexSymbols = '/[\x{1F300}-\x{1F5FF}]/u';
$clean_text = preg_replace($regexSymbols, $replaceTo, $clean_text);
// Match Transport And Map Symbols
$regexTransport = '/[\x{1F680}-\x{1F6FF}]/u';
$clean_text = preg_replace($regexTransport, $replaceTo, $clean_text);
// Match Miscellaneous Symbols
$regexMisc = '/[\x{2600}-\x{26FF}]/u';
$clean_text = preg_replace($regexMisc, $replaceTo, $clean_text);
// Match Dingbats
$regexDingbats = '/[\x{2700}-\x{27BF}]/u';
$clean_text = preg_replace($regexDingbats, $replaceTo, $clean_text);
return $clean_text;
}
/**
* 非小程序登录token
* @param $arr
* @return string
* @throws ParamException
*/
public function LoginToken($str)
{
$token = $this->saveToCache($str);
return $token;
}
}

View File

@@ -0,0 +1,378 @@
<?php
/**
* Created by PhpStorm.
* User: Administrator
* Date: 2020-01-10
* Time: 17:24
*/
namespace app\api\service;
use think\Log;
class WechatH5Pay
{
//use Flight;
/**
* 微信支付服务器端下单
* 微信APP支付文档地址: https://pay.weixin.qq.com/wiki/doc/api/app.php?chapter=8_6
* 使用示例
* 构造方法参数
* 'appid' => //填写微信分配的公众账号ID
* 'mch_id' => //填写微信支付分配的商户号
* 'notify_url'=> //填写微信支付结果回调地址
* 'key' => //填写微信商户支付密钥
* );
* 统一下单方法
* $WechatAppPay = new wechatAppPay($options);
* $params['body'] = '商品描述'; //商品描述
* $params['out_trade_no'] = '1217752501201407'; //自定义的订单号,不能重复
* $params['total_fee'] = '100'; //订单金额 只能为整数 单位为分
* $params['trade_type'] = 'APP'; //交易类型 JSAPI | NATIVE |APP | WAP
* $wechatAppPay->unifiedOrder( $params );
*/
//接口API URL前缀
const API_URL_PREFIX = 'https://api.mch.weixin.qq.com';
//下单地址URL
const UNIFIEDORDER_URL = "/pay/unifiedorder";
//查询订单URL
const ORDERQUERY_URL = "/pay/orderquery";
//关闭订单URL
const CLOSEORDER_URL = "/pay/closeorder";
//公众账号ID
private $appid;
//商户号
private $mch_id;
//随机字符串
private $nonce_str;
//签名
private $sign;
//商品描述
private $body;
//商户订单号
private $out_trade_no;
//支付总金额
private $total_fee;
//终端IP
private $spbill_create_ip;
//支付结果回调通知地址
private $notify_url;
//交易类型
private $trade_type;
//支付密钥
private $key;
//证书路径
private $SSLCERT_PATH;
private $SSLKEY_PATH;
//所有参数
private $params = array();
public function __construct($appid, $mch_id, $notify_url, $key)
{
$this->appid = $appid;
$this->mch_id = $mch_id;
$this->notify_url = $notify_url;
$this->key = $key;
}
/**
* 下单方法
* @param $params 下单参数
*/
public function unifiedOrder( $params ){
$this->body = $params['body'];
$this->out_trade_no = $params['out_trade_no'];
$this->total_fee = $params['total_fee'];
$this->trade_type = $params['trade_type'];
$this->scene_info = $params['scene_info'];
$this->nonce_str = $this->genRandomString();
$this->spbill_create_ip = $_SERVER['REMOTE_ADDR'];
$this->params['appid'] = $this->appid;
$this->params['mch_id'] = $this->mch_id;
$this->params['nonce_str'] = $this->nonce_str;
$this->params['body'] = $this->body;
$this->params['out_trade_no'] = $this->out_trade_no;
$this->params['total_fee'] = $this->total_fee;
$this->params['spbill_create_ip'] = $this->spbill_create_ip;
$this->params['notify_url'] = $this->notify_url;
$this->params['trade_type'] = $this->trade_type;
$this->params['scene_info'] = $this->scene_info;
//获取签名数据
$this->sign = $this->MakeSign( $this->params );
$this->params['sign'] = $this->sign;
$xml = $this->data_to_xml($this->params);
$response = $this->postXmlCurl($xml, self::API_URL_PREFIX.self::UNIFIEDORDER_URL);
if( !$response ){
return false;
}
$result = $this->xml_to_data( $response );
if( !empty($result['result_code']) && !empty($result['err_code']) ){
$result['err_msg'] = $this->error_code( $result['err_code'] );
}
return $result;
}
/**
* 查询订单信息
* @param $out_trade_no 订单号
* @return array
*/
public function orderQuery( $out_trade_no ){
$this->params['appid'] = $this->appid;
$this->params['mch_id'] = $this->mch_id;
$this->params['nonce_str'] = $this->genRandomString();
$this->params['out_trade_no'] = $out_trade_no;
//获取签名数据
$this->sign = $this->MakeSign( $this->params );
$this->params['sign'] = $this->sign;
$xml = $this->data_to_xml($this->params);
$response = $this->postXmlCurl($xml, self::API_URL_PREFIX.self::ORDERQUERY_URL);
if( !$response ){
return false;
}
$result = $this->xml_to_data( $response );
if( !empty($result['result_code']) && !empty($result['err_code']) ){
$result['err_msg'] = $this->error_code( $result['err_code'] );
}
return $result;
}
/**
* 关闭订单
* @param $out_trade_no 订单号
* @return array
*/
public function closeOrder( $out_trade_no ){
$this->params['appid'] = $this->appid;
$this->params['mch_id'] = $this->mch_id;
$this->params['nonce_str'] = $this->genRandomString();
$this->params['out_trade_no'] = $out_trade_no;
//获取签名数据
$this->sign = $this->MakeSign( $this->params );
$this->params['sign'] = $this->sign;
$xml = $this->data_to_xml($this->params);
$response = $this->postXmlCurl($xml, self::API_URL_PREFIX.self::CLOSEORDER_URL);
if( !$response ){
return false;
}
$result = $this->xml_to_data( $response );
return $result;
}
/**
*
* 获取支付结果通知数据
* return array
*/
public function getNotifyData(){
//获取通知的数据
$xml = $GLOBALS['HTTP_RAW_POST_DATA'];
//echo 123;die;
$data = array();
if( empty($xml) ){
return false;
}
$data = $this->xml_to_data( $xml );
if( !empty($data['return_code']) ){
if( $data['return_code'] == 'FAIL' ){
return false;
}
}
return $data;
}
/**
* 接收通知成功后应答输出XML数据
* @param string $xml
*/
public function replyNotify(){
$data['return_code'] = 'SUCCESS';
$data['return_msg'] = 'OK';
$xml = $this->data_to_xml( $data );
echo $xml;
die();
}
/**
* 生成APP端支付参数
* @param $prepayid 预支付id
*/
public function getAppPayParams( $prepayid ){
$data['appid'] = $this->appid;
$data['partnerid'] = $this->mch_id;
$data['prepayid'] = $prepayid;
$data['package'] = 'Sign=WXPay';
$data['noncestr'] = $this->genRandomString();
$data['timestamp'] = time();
$data['sign'] = $this->MakeSign( $data );
return $data;
}
/**
* 生成签名
* @return 签名
*/
public function MakeSign( $params ){
//签名步骤一:按字典序排序数组参数
ksort($params);
$string = $this->ToUrlParams($params);
//签名步骤二在string后加入KEY
$string = $string . "&key=".$this->key;
//签名步骤三MD5加密
$string = md5($string);
//签名步骤四:所有字符转为大写
$result = strtoupper($string);
return $result;
}
/**
* 将参数拼接为url: key=value&key=value
* @param $params
* @return string
*/
public function ToUrlParams( $params ){
$string = '';
if( !empty($params) ){
$array = array();
foreach( $params as $key => $value ){
$array[] = $key.'='.$value;
}
$string = implode("&",$array);
}
return $string;
}
/**
* 输出xml字符
* @param $params 参数名称
* return string 返回组装的xml
**/
public function data_to_xml( $params ){
if(!is_array($params)|| count($params) <= 0)
{
return false;
}
$xml = "<xml>";
foreach ($params as $key=>$val)
{
if (is_numeric($val)){
$xml.="<".$key.">".$val."</".$key.">";
}else{
$xml.="<".$key."><![CDATA[".$val."]]></".$key.">";
}
}
$xml.="</xml>";
return $xml;
}
/**
* 将xml转为array
* @param string $xml
* return array
*/
public function xml_to_data($xml){
if(!$xml){
return false;
}
//将XML转为array
//禁止引用外部xml实体
libxml_disable_entity_loader(true);
$data = json_decode(json_encode(simplexml_load_string($xml, 'SimpleXMLElement', LIBXML_NOCDATA)), true);
return $data;
}
/**
* 获取毫秒级别的时间戳
*/
private static function getMillisecond(){
//获取毫秒的时间戳
$time = explode ( " ", microtime () );
$time = $time[1] . ($time[0] * 1000);
$time2 = explode( ".", $time );
$time = $time2[0];
return $time;
}
/**
* 产生一个指定长度的随机字符串,并返回给用户
* @param type $len 产生字符串的长度
* @return string 随机字符串
*/
private function genRandomString($len = 32) {
$chars = array(
"a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k",
"l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v",
"w", "x", "y", "z", "A", "B", "C", "D", "E", "F", "G",
"H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R",
"S", "T", "U", "V", "W", "X", "Y", "Z", "0", "1", "2",
"3", "4", "5", "6", "7", "8", "9"
);
$charsLen = count($chars) - 1;
// 将数组打乱
shuffle($chars);
$output = "";
for ($i = 0; $i < $len; $i++) {
$output .= $chars[mt_rand(0, $charsLen)];
}
return $output;
}
/**
* 以post方式提交xml到对应的接口url
*
* @param string $xml 需要post的xml数据
* @param string $url url
* @param bool $useCert 是否需要证书,默认不需要
* @param int $second url执行超时时间默认30s
* @throws WxPayException
*/
private function postXmlCurl($xml, $url, $useCert = false, $second = 30){
$ch = curl_init();
//设置超时
curl_setopt($ch, CURLOPT_TIMEOUT, $second);
curl_setopt($ch,CURLOPT_URL, $url);
curl_setopt($ch,CURLOPT_SSL_VERIFYPEER,FALSE);
curl_setopt($ch,CURLOPT_SSL_VERIFYHOST,2);
//设置header
curl_setopt($ch, CURLOPT_HEADER, FALSE);
//要求结果为字符串且输出到屏幕上
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
if($useCert == true){
//设置证书
//使用证书cert 与 key 分别属于两个.pem文件
curl_setopt($ch,CURLOPT_SSLCERTTYPE,'PEM');
//curl_setopt($ch,CURLOPT_SSLCERT, WxPayConfig::SSLCERT_PATH);
curl_setopt($ch,CURLOPT_SSLKEYTYPE,'PEM');
//curl_setopt($ch,CURLOPT_SSLKEY, WxPayConfig::SSLKEY_PATH);
}
//post提交方式
curl_setopt($ch, CURLOPT_POST, TRUE);
curl_setopt($ch, CURLOPT_POSTFIELDS, $xml);
//运行curl
$data = curl_exec($ch);
//返回结果
if($data){
curl_close($ch);
return $data;
} else {
$error = curl_errno($ch);
curl_close($ch);
return false;
}
}
/**
* 错误代码
* @param $code 服务器输出的错误代码
* return string
*/
public function error_code( $code ){
$errList = array(
'NOAUTH' => '商户未开通此接口权限',
'NOTENOUGH' => '用户帐号余额不足',
'ORDERNOTEXIST' => '订单号不存在',
'ORDERPAID' => '商户订单已支付,无需重复操作',
'ORDERCLOSED' => '当前订单已关闭,无法支付',
'SYSTEMERROR' => '系统错误!系统超时',
'APPID_NOT_EXIST' => '参数中缺少APPID',
'MCHID_NOT_EXIST' => '参数中缺少MCHID',
'APPID_MCHID_NOT_MATCH' => 'appid和mch_id不匹配',
'LACK_PARAMS' => '缺少必要的请求参数',
'OUT_TRADE_NO_USED' => '同一笔交易不能多次提交',
'SIGNERROR' => '参数签名结果不正确',
'XML_FORMAT_ERROR' => 'XML格式错误',
'REQUIRE_POST_METHOD' => '未使用post传递参数 ',
'POST_DATA_EMPTY' => 'post数据不能为空',
'NOT_UTF8' => '未使用指定编码格式',
);
if( array_key_exists( $code , $errList ) ){
return $errList[$code];
}
}
}

View File

@@ -0,0 +1,42 @@
<?php
/**
* Created by PhpStorm.
* User: Administrator
* Date: 2020/4/18
* Time: 10:49
*/
namespace app\api\service;
use app\api\model\Order as OrderModel;
use think\Exception;
use think\facade\Log;
require 'D:/wwwroot/www.zhiyuanhelp.com/extend/WxPay/WxPay.Api.php';
class WxNotify extends \WxPayNotify
{
public function NotifyProcess($data, &$msg){
if($data['result_code'] == 'SUCCESS'){
$orderNo = $data['out_trade_no'];
try{
$order = OrderModel::where('ord_no','=',$orderNo)->find();
//修改订单状态
$resUpdate = $this->updateOrderStatus($order['id']);
if($resUpdate){
return true;
}
}catch (Exception $e){
return false;
}
}else{
return false;
}
}
//更改状态
private function updateOrderStatus($orderID){
OrderModel::where('id','=',$orderID)
->update(['status'=>1,'pay_way'=>1,'pay_time'=>time()]);
}
}