declare (strict_types = 1);
namespace App\Logic\V1\Order;
use App\Logic\V1\Order\OrderLogic;
use App\Logic\BaseLogic;
use Hyperf\Utils\Context;
class WxPayLogic extends BaseLogic
{
//支付接口
public function appPay($order_sn,$total_money){
$ip = swoole_get_local_ip();
//注意swoole里获取ip的方式
$request_data = array(
'appid' => '**', #应用APPID
'mch_id' => '**', #商户号
'trade_type' => 'APP', #支付类型
'nonce_str' => $this->getRandom(30), #随机字符串 不长于32位
'body' => '商品名称', #商品名称
'out_trade_no' => $order_sn, #商户后台订单号
'total_fee' => $total_money, #商品价格
'spbill_create_ip' => $ip["eth0"], #用户端实际ip
'notify_url' => env('WECHAT_HOST', '').'/shop/v1/wxPaySuccess', #异步通知回调地址
);
$request_data['sign'] = $this -> get_sign($request_data);
$xml_data = $this -> set_xmldata($request_data);
$res = $this -> send_prePaycurl($xml_data);
if($res['return_code'] == 'SUCCESS' && $res['result_code'] == 'SUCCESS'){
$two_data['appid'] = '**'; #APPID
$two_data['partnerid'] = '**'; #商户号
$two_data['prepayid'] = $res['prepay_id']; //预支付交易会话标识
$two_data['noncestr'] = $this->getRandom(30);
$two_data['timestamp'] = time(); #时间戳
$two_data['package'] = "Sign=WXPay"; #固定值
$two_data['sign'] = $this -> get_twosign($two_data); #二次签名
// $this->ajaxReturn(array('code'=>200,'info'=>$two_data));
return $two_data;
}else{
// $this->ajaxReturn(array('code'=>201,'info'=>$res['err_code_des']));
return false;
}
}
//一次签名的函数
private function get_sign($data){
ksort($data);
$str = '';
foreach ($data as $key => $value) {
$str .= !$str ? $key . '=' . $value : '&' . $key . '=' . $value;
}
$str.='&key='."商户api秘钥";
$sign = strtoupper(md5($str));
return $sign;
}
//二次签名的函数
private function get_twosign($data){
$sign_data = array(
"appid"=>$data['appid'],
"partnerid"=>$data['partnerid'],
"prepayid"=>$data['prepayid'],
"noncestr"=>$data['noncestr'],
"timestamp"=>$data['timestamp'],
"package"=>$data['package'],
);
return $this -> get_sign($sign_data);
}
//生成xml格式的函数
private function set_xmldata($data) {
$xmlData = "
foreach ($data as $key => $value) {
$xmlData.="<".$key.">".$key.">";
}
$xmlData = $xmlData."";
return $xmlData;
}
//通过curl发送数据给微信接口的函数
private function send_prePaycurl($xmlData) {
$url = "https://api.mch.weixin.qq.com/pay/unifiedorder";
$header[] = "Content-type: text/xml";
$curl = curl_init();
curl_setopt($curl, CURLOPT_HTTPHEADER, $header);
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_POST, 1);
curl_setopt($curl, CURLOPT_POSTFIELDS, $xmlData);
$data = curl_exec($curl);
if (curl_errno($curl)) {
print curl_error($curl);
}
curl_close($curl);
return $this -> _xmldataparse($data);
}
//xml数据解析函数
private function _xmldataparse($data){
$msg = array();
$msg = (array)simplexml_load_string($data, 'SimpleXMLElement', LIBXML_NOCDATA);
return $msg;
}
public function getRandom($param){
$str="0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
$key = "";
for($i=0;$i<$param;$i++)
{
$key .= $str{mt_rand(0,32)}; //生成php随机数
}
return $key;
}
}