支付宝支付及回调
/* * 支付宝支付 * $body 名称 * $total_amount 价格 * $product_code 订单号 */ public function aliPay($total_amount,$body,$product_code){ Vendor('alipay.aop.AopClient'); Vendor('alipay.aop.request.AlipayTradePrecreateRequest'); $aop = new AopClient(); $aop->appId = C('ALI_PAY.appId'); // APPID $aop->gatewayUrl = C('ALI_PAY.gatewayUrl'); $aop->rsaPrivateKey = C('ALI_PAY.rsaPrivateKey'); // 应用私钥 $aop->alipayrsaPublicKey = C('ALI_PAY.alipayrsaPublicKey'); // 支付宝公钥 $aop->signType = "RSA2"; $aop->format = "json"; $aop->charset = "UTF-8"; $aop->debugInfo = true; $request = new AlipayTradePrecreateRequest(); $arr['body'] = $body; $arr['subject'] = $body; $arr['out_trade_no'] = $product_code; $arr['timeout_express'] = '30m'; $arr['total_amount'] = floatval($total_amount); $json = json_encode($arr); $request->setNotifyUrl(C('ALI_PAY.notify_url')); // 回调地址 $request->setBizContent($json); $result = $aop->execute($request); $responseNode = str_replace(".", "_", $request->getApiMethodName()) . "_response"; $resultCode = $result->$responseNode->code; if(!empty($resultCode) && $resultCode == 10000){ $resp = (array)$result->$responseNode; return $resp['qr_code']; }else{ return false; } } /** *支付宝支付成功回调 */ public function alipay_notify(){ $trade_status = I('post.trade_status',''); $trade_no = I('post.trade_no',''); $out_trade_no = I('post.out_trade_no',''); $total_amount = I('post.total_amount',''); if ($trade_status == 'TRADE_FINISHED' || $trade_status == 'TRADE_SUCCESS') { // 修改订单状态 $res['transaction_id'] = $trade_no; //支付宝流水号 $res['pay_time'] = time(); $res['pay_status'] = 2; $res['total_fee'] = $total_amount; $result = D('Order')->saveOrder($res,$out_trade_no); if($result){ echo 'success'; }else{ echo 'fail'; } }else{ echo "fail"; } }
微信支付及回调
class WxPayModel { /** * 微信支付请求接口(POST) * @param string $goods_id 商品ID * @param string $body 商品简单描述 * @param string $order_sn 订单编号 * @param string $total_fee 金额 * @return json的数据 */ public function prePay($order_id,$price,$order_title,$order_sn){ //统一下单参数构造 $unifiedorder = array( 'appid' => C('WX.appid'), 'mch_id' => C('WX.pay_mchid'), 'device_info' => 'WEB', 'nonce_str' => $this->getNonceStr(), 'body' => $order_title, 'out_trade_no' => $order_sn, 'total_fee' => $price * 100, 'spbill_create_ip' => get_client_ip(), 'notify_url' => C('WX.notify_url'), 'trade_type' => 'NATIVE', 'product_id' => $order_id ); $unifiedorder['sign'] = $this->makeSign($unifiedorder); //return $unifiedorder; //请求数据,统一下单 $xmldata = $this->array2xml($unifiedorder); $url = 'https://api.mch.weixin.qq.com/pay/unifiedorder'; $res = $this->curl_post_ssl($url, $xmldata); if(!$res){ return false; } // 这句file_put_contents是用来查看服务器返回的结果 测试完可以删除了 file_put_contents('./log.txt',$res,FILE_APPEND); $content = $this->xml2array($res); if(strval($content['result_code']) == 'FAIL' || strval($content['return_code']) == 'FAIL'){ return false; } if($content['return_code'] == 'SUCCESS' && $content['result_code'] == 'SUCCESS'){ return $content['code_url']; } return false; } /** * 生成签名 * @return 签名 */ public function makeSign($data){ //获取微信支付秘钥 $key = C('WX.pay_apikey'); // 去空 $data=array_filter($data); //签名步骤一:按字典序排序参数 ksort($data); $string_a=http_build_query($data); $string_a=urldecode($string_a); //签名步骤二:在string后加入KEY $string_sign_temp=$string_a."&key=".$key; //签名步骤三:MD5加密 $sign = md5($string_sign_temp); // 签名步骤四:所有字符转为大写 $result=strtoupper($sign); return $result; } /** * * 产生随机字符串,不长于32位 * @param int $length * @return 产生的随机字符串 */ public function getNonceStr($length = 32) { $chars = "abcdefghijklmnopqrstuvwxyz0123456789"; $str =""; for ( $i = 0; $i < $length; $i++ ) { $str .= substr($chars, mt_rand(0, strlen($chars)-1), 1); } return (String)$str; } /** * 将一个数组转换为 XML 结构的字符串 * @param array $arr 要转换的数组 * @param int $level 节点层级, 1 为 Root. * @return string XML 结构的字符串 */ public function array2xml($arr, $level = 1) { $s = $level == 1 ? "<xml>" : ''; foreach($arr as $tagname => $value) { if (is_numeric($tagname)) { $tagname = $value['TagName']; unset($value['TagName']); } if(!is_array($value)) { $s .= "<{$tagname}>".(!is_numeric($value) ? '<![CDATA[' : '').$value.(!is_numeric($value) ? ']]>' : '')."</{$tagname}>"; } else { $s .= "<{$tagname}>" . $this->array2xml($value, $level + 1)."</{$tagname}>"; } } $s = preg_replace("/([x01-x08x0b-x0cx0e-x1f])+/", ' ', $s); return $level == 1 ? $s."</xml>" : $s; } /** * 将xml转为array * @param string $xml xml字符串 * @return array 转换得到的数组 */ public function xml2array($xml){ //禁止引用外部xml实体 libxml_disable_entity_loader(true); $result= json_decode(json_encode(simplexml_load_string($xml, 'SimpleXMLElement', LIBXML_NOCDATA)), true); return $result; } /** * 微信支付发起请求 */ public function curl_post_ssl($url, $xmldata, $second=30,$aHeader=array()){ $ch = curl_init(); //超时时间 curl_setopt($ch,CURLOPT_TIMEOUT,$second); curl_setopt($ch,CURLOPT_RETURNTRANSFER, 1); //这里设置代理,如果有的话 curl_setopt($ch,CURLOPT_URL,$url); curl_setopt($ch,CURLOPT_SSL_VERIFYPEER,false); curl_setopt($ch,CURLOPT_SSL_VERIFYHOST,false); if( count($aHeader) >= 1 ){ curl_setopt($ch, CURLOPT_HTTPHEADER, $aHeader); } curl_setopt($ch,CURLOPT_POST, 1); curl_setopt($ch,CURLOPT_POSTFIELDS,$xmldata); $data = curl_exec($ch); if($data){ curl_close($ch); return $data; } else { $error = curl_errno($ch); echo "call faild, errorCode:$error "; curl_close($ch); return false; } } } public function wx_notify(){ //获取通知的数据 $xml = file_get_contents('php://input'); //将服务器返回的XML数据转化为数组 $data = D('Wxpay')->xml2array($xml); // 保存微信服务器返回的签名sign $data_sign = $data['sign']; // sign不参与签名算法 unset($data['sign']); $sign = D('Wxpay')->makeSign($data); // 判断签名是否正确 判断支付状态 if ( ($sign===$data_sign) && ($data['return_code']=='SUCCESS') && ($data['result_code']=='SUCCESS') ) { $result = $data; $out_trade_no = $data['out_trade_no']; //订单单号 $res['total_fee'] = $data['total_fee'] / 100; //付款金额 $res['transaction_id'] = $data['transaction_id']; //微信支付流水号 $res['pay_time'] = time(); $res['pay_status'] = 2; $result = D('Order')->saveOrder($res,$out_trade_no); }else{ $result = false; } if($result !== false){ $str='<xml><return_code><![CDATA[SUCCESS]]></return_code><return_msg><![CDATA[OK]]></return_msg></xml>'; }else{ $str='<xml><return_code><![CDATA[FAIL]]></return_code><return_msg><![CDATA[签名失败]]></return_msg></xml>'; } return str; }
配置参数
//微信支付配置 'WX'=> array( 'appid' => 'wxffc0e69d53eb3f',//'wx57f5199c9111eb8a', 'app_secret' => '57884765bec5ab757c6752232c92',//'ba94a8a67deee50a5e85057ad159d33d', 'pay_mchid' => '129201', //商户号 'pay_apikey' => 'a9mb0sg8ow276p11qpkcpmtvo', // 支付秘钥 'notify_url' => 'http://api2.xxxxxxxxxx.cn/zhisi/order/wx_notify' ), // 支付宝配置 'ALI_PAY' => array( // APPID 'appId' => '20000***************', // 应用私钥 'rsaPrivateKey' => 'MIIEpQIBAAKCAQEAyxIq9vgcCK1iKUbHusbjxDp/EL7y0xRbCIn/ANJlb7YqUP8uBQmwviqy2zL9GHuyfku/VSd4YPV9pINGW8A4m2Dezfo5itcYvVHYMO6UTDny1Hjoh0TcwcknRgjXqMnmafYtan6i2H0PfF4spKX8Zxct/+Qm8hIhXBQ/fvFbhDVlXyiwmMzJ+s/g9rAWutTn8DecK8OMROys5HyWi19O+X4HL1aEPqYTw/IFjBf5k0EFqU4tkr8LHEolQhtNRzY8m3fm7COo2e9Msaa7hDqewsZi+bm5+tiUiY1Rzxd+rv3eUzQzkilU6yPGJv+c5rxwgp+IloFrfiPq7XmYwQUdQwIDAQABAoIBAQDBN68jwB1EcFym847U+6r6KcJ/F4CKMKMRc+PrT0VuzoBjAvoxlu/RcWUuxcwlwISsQLxzdJPIhayfnLyUTkhOJxS4Ha8kmNcUQ8yVelwmTzjqy4RMOMxnolK5A27XTgvrpG3AF3Aw1oWmiyClJL4NBPQit14LFA8jwqxLx7CREF8BJo2JdZGtZbZJwIACARea4mnoTorE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ANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAyxIq9vgcCK1iKUbHusbjxDp/EL7y0xRbCIn/ANJlb7YqUP8uBQmwviqy2zL9GHuyfku/VSd4YPV9pINGW8A4m2Dezfo5itcYvVHYMO6UTDny1Hjoh0TcwcknRgjXqMnmafYtan6i2H0PfF4spKX8Zxct/+Qm8hIhXBQ/fvFbhDVlXyiwmMzJ+s/g9rAWutTn8DecK8OMROys5HyWi19O+X4HL1aEPqYTw/IFjBf5k0EFqU4tkr8LHEolQhtNRzY8m3fm7COo2e9Msaa7hDqewsZi+bm5+tiUiY1Rzxd+rv3eUzQzkilU6yPGJv+c5rxwgp+IloFrfiPq7XmYwQUdQwIDAQAB', // 支付宝公钥 'alipayrsaPublicKey' => 'MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAnVRCETbyNwfF5w3PeCMcLvMJuKTks4XYRap7woTOysSB+JQjV8S/4MWvpAo1c3CLWWiLPkrKdRdbNAG7EzSErWu9USfIrXB8JZUvyhvY3Whm1sNIPI896zll5Ixnb9ac0P8AYwvGxkZhMxtf7x7JAJr7KGA8tb4Qn9v8EXaASIV2WDLtUMI04MwRj+TuudGQvrz0JFjVMludb7se24rg6JNzfE0U8D0dOvH2jYXNlK4jtWYWGNrEO1NCKK9SArFUAERf9FFjJJ+i/zgc0LC74HFSye+BVMBGP1LEynYh/zJjnkgN/evQdCj+VveWZnh55fBDj+jJ+Zgwt4yheA75swIDAQAB', // 回调地址 'notify_url' => 'http://api2.xxxxx.cn/zhisi/order/alipay_notify', ),