作者 郭鑫
1 个管道 的构建 通过 耗费 1 秒

页面修改

<?php
// +----------------------------------------------------------------------
// | bronet [ 以客户为中心 以奋斗者为本 ]
// +----------------------------------------------------------------------
// | Copyright (c) 2013-2017 http://www.bronet.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: 老猫 <bronet@126.com>
// +----------------------------------------------------------------------
namespace app\portal\controller;
use cmf\controller\AdminBaseController;
/**
* Class AdminConfigController
* @package app\portal\controller
* @adminMenuRoot(
* 'name' =>'配置',
* 'action' =>'default',
* 'parent' =>'',
* 'display'=> true,
* 'order' => 30,
* 'icon' =>'th',
* 'remark' =>'配置'
* )
*/
class AdminConfigController extends AdminBaseController
{
/**
* 配置
* @adminMenu(
* 'name' => '配置',
* 'parent' => 'portal/AdminConfig/default',
* 'display'=> true,
* 'hasView'=> true,
* 'order' => 10000,
* 'icon' => '',
* 'remark' => '配置',
* 'param' => ''
* )
*/
public function index()
{
$data = $this->request->param();
$final = $this->adminIndex($data);
$where_else = $final['where_arr'];
$where_else['status'] = array('neq',9);
$where_else['type'] = array('in','1,2');
$coo_list = Db::name('Banner')->where($where_else)->order('score desc , create_time desc')
->paginate(10,false,['query'=>$final['page_arr']]);
$page = $coo_list->render();
$this->assign('page',$page);
$this->assign('list',$coo_list);
return $this->fetch('index');
}
}
... ...
... ... @@ -137,7 +137,7 @@ class AdminOrderController extends AdminBaseController
$url = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=".$acctoken;
$send = array();
$send['touser'] = $hire['openid'];//OPENID
$send['template_id'] = 'wndcbbmdVKnmw6XYlEiaCY03tKDjZj-Afzm2pt6qlPM';
$send['template_id'] = 'YUC7jOhDQ_kWRumosx_aLFh_ReKjcrZOdbV-zVfRf14';
$send['url'] = 'http://yunzhi07.com/';//模板跳转链接
if($data['type'] == 3){
// 审核通过
... ... @@ -146,10 +146,11 @@ class AdminOrderController extends AdminBaseController
// 审核未通过
$send['data']['first']['value'] = "抱歉,您的审核未通过,原因为".$data['refund'].",请查看订单详";//模板数据
}
$send['data']['keyword1']['value'] = $hire['title'];//企业名称
$send['data']['keyword2']['value'] = $hire['select_name'];//职位名称
$send['data']['keyword3']['value'] = $hire['money'];;//工资金额
$send['data']['keyword4']['value'] = date('Y-m-d H:i:s',$hire['create_time']);//时间
$send['data']['keyword1']['value'] = $hire['select_name'];//模板数据
$send['data']['keyword2']['value'] = $hire['title'];//模板数据
$send['data']['keyword3']['value'] = $hire['title'];//模板数据
$send['data']['keyword4']['value'] = $hire['money'].'元';//模板数据
$send['data']['keyword5']['value'] = '0471-3388866';//模板数据
$send['data']['remark']['value'] = '如有其他问题,请及时与我们联系!';//模板数据
$ch = curl_init();//初始化curl
curl_setopt($ch, CURLOPT_URL,$url);//抓取指定网页
... ...
... ... @@ -48,8 +48,6 @@ class SomepayController extends HomeBaseController
}
//微信回调
public function pay_notify()
{
... ... @@ -100,6 +98,56 @@ class SomepayController extends HomeBaseController
}
// 微信提现
public function getWxpay($openid,$order_sn,$money){
require_once EXTEND_PATH . 'WxpayAPI/WxPay.Merch.php';
$desc = '青云职上提现';
$MerchPay = new \MerchPay();
// $money = 1;
$result = $MerchPay->pay($openid, $order_sn, $money, $desc);
if($result['result_code'] == "SUCCESS"){
Db::startTrans();
$where_order['order_sn'] = $result['partner_trade_no'];
$where_order['status'] = 11;
$order = Db::name('Order')->where($where_order)->find();
if($order){
$up_order['status'] = 12;
$up_order['update_time'] = time();
$res_order = Db::name('Order')->where($where_order)->update($up_order);
if($res_order){
// 减少店铺金额
$where_store['id'] = $order['store_id'];
$sall = Db::name('Store')->where($where_store)->setDec('money',$order['order_price']);
if(!$sall){
Db::rollback();
$this->apiResponse('0','失败3');
}
// 加入提现记录
$add_log['store_id'] = $order['store_id'];
$add_log['order_id'] = $order['id'];
$add_log['user_id'] = $order['user_id'];
$add_log['money'] = $order['order_price'];
$add_log['status'] = 3;
$add_log['create_time'] = time();
$add_log['update_time'] = time();
$res_log = Db::name('GetMoney')->insertGetId($add_log);
if($res_log){
Db::commit();
$this->apiResponse('1','提现成功');
}else{
Db::rollback();
$this->apiResponse('0','提现失败');
}
}else{
Db::rollback();
$this->apiResponse('0','获取订单失败2');
}
}else{
Db::rollback();
$this->apiResponse('0','获取订单失败');
}
}
}
}
... ...
<include file="public@header"/>
<style type="text/css">
.pic-list li {
margin-bottom: 5px;
}
</style>
</head>
<body>
<div class="wrap js-check-wrap">
<ul class="nav nav-tabs">
<li><a href="">配置</a></li>
</ul>
<form action="{:url('AdminBanner/addBanner')}" method="post" class="form-horizontal js-ajax-form margin-top-20">
<div class="row">
<div class="col-md-9">
<table class="table table-bordered">
<input class="form-control" type="hidden" name="id"
value=""/>
<tr>
<th width="100">分类<span class="form-required">*</span></th>
<td>
<select style="border: 1px solid #dce4ec;" name="type">
<option name="type[]" value="1"> &nbsp; 聘用&nbsp;</option>
<option name="type[]" value="2"> &nbsp;求职&nbsp;</option>
</select>
</td>
</tr>
<tr>
<th>轮播图<span class="form-required">*</span></th>
<td>
<div style="text-align: center;">
<input type="hidden" name="pic" id="thumbnail" value="" >
<a href="javascript:uploadOneImage('图片上传','#thumbnail');">
<img src="__TMPL__/public/assets/images/default-thumbnail.png"
id="thumbnail-preview"
width="135" style="cursor: pointer"/>
</a>
<input type="button" class="btn btn-sm btn-cancel-thumbnail" value="取消图片">
<p style="margin-right: 70px;">推荐尺寸:686px*278px</p>
</div>
</td>
</tr>
<tr>
<th>链接地址</th>
<td>
<input class="form-control" type="text" name="link"
value="" placeholder="请输入链接地址"/>
</td>
</tr>
<tr>
<th>排序</th>
<td>
<input class="form-control" type="text" name="score"
value="" placeholder="请输入排序,数字越大越靠前"/>
</td>
</tr>
</table>
<div class="form-group">
<div class="col-sm-offset-2 col-sm-10">
<button type="submit" class="btn btn-primary js-ajax-submit">{:lang('SAVE')}</button>
<a class="btn btn-default" href="{:url('AdminBanner/banner')}">{:lang('BACK')}</a>
</div>
</div>
</div>
</div>
</form>
</div>
<script type="text/javascript" src="__STATIC__/js/admin.js"></script>
<script type="text/javascript">
//编辑器路径定义
var editorURL = GV.WEB_ROOT;
</script>
<script type="text/javascript" src="__STATIC__/js/ueditor/ueditor.config.js"></script>
<script type="text/javascript" src="__STATIC__/js/ueditor/ueditor.all.min.js"></script>
<script type="text/javascript">
$(function () {
// editorcontent = new baidu.editor.ui.Editor();
// editorcontent.render('content');
// try {
// editorcontent.sync();
// } catch (err) {
// }
$('.btn-cancel-thumbnail').click(function () {
$('#thumbnail-preview').attr('src', '__TMPL__/public/assets/images/default-thumbnail.png');
$('#thumbnail').val('');
});
});
// function doSelectCategory() {
// var selectedCategoriesId = $('#js-categories-id-input').val();
// openIframeLayer("{:url('AdminCategory/select')}?ids=" + selectedCategoriesId, '请选择分类', {
// area: ['700px', '400px'],
// btn: ['确定', '取消'],
// yes: function (index, layero) {
// //do something
//
// var iframeWin = window[layero.find('iframe')[0]['name']];
// var selectedCategories = iframeWin.confirm();
// if (selectedCategories.selectedCategoriesId.length == 0) {
// layer.msg('请选择分类');
// return;
// }
// $('#js-categories-id-input').val(selectedCategories.selectedCategoriesId.join(','));
// $('#js-categories-name-input').val(selectedCategories.selectedCategoriesName.join(' '));
// //console.log(layer.getFrameIndex(index));
// layer.close(index); //如果设定了yes回调,需进行手工关闭
// }
// });
// }
</script>
</body>
</html>
... ...
<?php
//error_reporting(E_ALL^E_NOTICE);
///////////////////////////////////////////////////////////////////////////////////////////////
// 引如微信支付的SDK
// 微信支付的SDK,下载地址https://pay.weixin.qq.com/wiki/doc/api/jsapi.php?chapter=11_1
// 这个【企业付款】类跟微信支付SDK没有关系,
// 引入微信支付SDK仅仅是使用微信支付配置的【APPID】【证书】【商户号】及【商户支付秘钥】
// 如果不使用SDK那么自己可以在下方的$config配置信息中写好需要的配置信息
///////////////////////////////////////////////////////////////////////////////////////////////
const APPID = 'wx100c2e5f27e34b92';
const MCHID = '1511142881';
const KEY = 'hfrT4YKO3teQqOkdSFTY9RGvtAErieV5';
const APPSECRET = '4de2264efb220ea89c1095580f4f4350';
//=======【证书路径设置】=====================================
/**
* TODO:设置商户证书路径
* 证书路径,注意应该填写绝对路径(仅退款、撤销订单时需要,可登录商户平台下载,
* API证书下载地址:https://pay.weixin.qq.com/index.php/account/api_cert,下载之前需要安装商户操作证书)
* @var path
*/
const SSLCERT_PATH = EXTEND_PATH.'WxminipayAPI/cert/apiclient_cert.pem';
const SSLKEY_PATH = EXTEND_PATH.'/WxminipayAPI/cert/apiclient_key.pem';
class MerchPay{
/**
* 企业支付
* @param string $openid 用户openID
* @param string $trade_no 单号
* @param string $money 金额
* @param string $desc 描述
* @return string XML 结构的字符串
*/
public function pay($openid,$trade_no,$money,$desc){
$data = array(
'mch_appid' => 'wx100c2e5f27e34b92',
'mchid' => '1511142881',
'nonce_str' => self::getNonceStr(),
'partner_trade_no' => $trade_no, //商户订单号,需要唯一
'openid' => $openid,
'check_name'=> 'NO_CHECK', //OPTION_CHECK不强制校验真实姓名, FORCE_CHECK:强制 NO_CHECK:
'amount' => $money * 100, //付款金额单位为分
'desc' => $desc,
'spbill_create_ip' => self::getip()
);
//生成签名
$data['sign'] = self::makeSign($data);
//构造XML数据
$xmldata = self::array2xml($data);
$url = 'https://api.mch.weixin.qq.com/mmpaymkttransfers/promotion/transfers';
//发送post请求
$res = self::curl_post_ssl($url, $xmldata);
if(!$res){
return array('result_code'=>'FAIL', 'return_msg'=>"Can't connect the server" );
}
//付款结果分析
$content = self::xml2array($res);
// F('merch',$content);
if(strval($content['return_code']) == 'FAIL'){
return array('result_code'=>'FAIL', 'return_msg'=>strval($content['return_msg']));
}
if(strval($content['result_code']) == 'FAIL'){
return array('result_code'=>'FAIL', 'return_msg'=>strval($content['err_code']).':'.strval($content['err_code_des']));
}
$resdata = array(
'return_code' => strval($content['return_code']),
'result_code' => strval($content['result_code']),
'nonce_str' => strval($content['nonce_str']),
'partner_trade_no' => strval($content['partner_trade_no']),
'payment_no' => strval($content['payment_no']),
'payment_time' => strval($content['payment_time']),
);
return $resdata;
}
/**
* 将一个数组转换为 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-\x08\x0b-\x0c\x0e-\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;
}
/**
*
* 产生随机字符串,不长于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 $str;
}
/**
* 生成签名
* @return 签名
*/
public function makeSign($data){
//获取微信支付秘钥
$key = KEY;
// 去空
$data=array_filter($data);
//签名步骤一:按字典序排序参数
ksort($data);
$string_a=http_build_query($data);
$string_a=urldecode($string_a);
//签名步骤二:在string后加入KEY
//$config=$this->config;
$string_sign_temp=$string_a."&key=".$key;
//签名步骤三:MD5加密
$sign = md5($string_sign_temp);
// 签名步骤四:所有字符转为大写
$result=strtoupper($sign);
return $result;
}
/**
* 获取IP地址
* @return [String] [ip地址]
*/
public function getip() {
static $ip = '';
$ip = $_SERVER['REMOTE_ADDR'];
if(isset($_SERVER['HTTP_CDN_SRC_IP'])) {
$ip = $_SERVER['HTTP_CDN_SRC_IP'];
} elseif (isset($_SERVER['HTTP_CLIENT_IP']) && preg_match('/^([0-9]{1,3}\.){3}[0-9]{1,3}$/', $_SERVER['HTTP_CLIENT_IP'])) {
$ip = $_SERVER['HTTP_CLIENT_IP'];
} elseif(isset($_SERVER['HTTP_X_FORWARDED_FOR']) AND preg_match_all('#\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}#s', $_SERVER['HTTP_X_FORWARDED_FOR'], $matches)) {
foreach ($matches[0] AS $xip) {
if (!preg_match('#^(10|172\.16|192\.168)\.#', $xip)) {
$ip = $xip;
break;
}
}
}
return $ip;
}
/**
* 企业付款发起请求
* 此函数来自:https://pay.weixin.qq.com/wiki/doc/api/download/cert.zip
*/
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_PROXY, '10.206.30.98');
//curl_setopt($ch,CURLOPT_PROXYPORT, 8080);
curl_setopt($ch,CURLOPT_URL,$url);
curl_setopt($ch,CURLOPT_SSL_VERIFYPEER,false);
curl_setopt($ch,CURLOPT_SSL_VERIFYHOST,false);
//以下两种方式需选择一种
//第一种方法,cert 与 key 分别属于两个.pem文件
//默认格式为PEM,可以注释
curl_setopt($ch,CURLOPT_SSLCERTTYPE,'PEM');
curl_setopt($ch,CURLOPT_SSLCERT,SSLCERT_PATH);
//默认格式为PEM,可以注释
curl_setopt($ch,CURLOPT_SSLKEYTYPE,'PEM');
curl_setopt($ch,CURLOPT_SSLKEY,SSLKEY_PATH);
//第二种方式,两个文件合成一个.pem文件
//curl_setopt($ch,CURLOPT_SSLCERT,getcwd().'/all.pem');
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\n";
curl_close($ch);
return false;
}
}
//测试支付
public function test(){
$openid = 'ovprvtzBZaWXnZUadwgexOLNc93M';
$trade_no =mt_rand(1,9).date('YmdHis').mt_rand(1000,9999);
$res = self::pay($openid,$trade_no,1,'提现');
return $res;
}
}
?>
\ No newline at end of file
... ...
<?php
/**
* Created by PhpStorm.
* User: 29925
* Date: 2018/7/21
* Time: 11:39
*/
/*
* 微信退款
*/
class WxRefund {
protected $appid;
protected $mch_id;
protected $key;
protected $transaction_id;
protected $out_refund_no;
protected $total_fee;
protected $refund_fee;
protected $refund_desc;
function __construct($appid, $mch_id, $key, $transaction_id, $out_refund_no, $total_fee, $refund_fee, $refund_desc) {
$this->appid = $appid;
$this->mch_id = $mch_id;
$this->key = $key;
$this->transaction_id = $transaction_id;
$this->out_refund_no = $out_refund_no;
$this->total_fee = $total_fee;
$this->refund_fee = $refund_fee;
$this->refund_desc = $refund_desc;
}
public function pay() {
//微信退款
$return = $this->weixinrefund();
return $return;
}
//退款接口
private function refund() {
$url = 'https://api.mch.weixin.qq.com/secapi/pay/refund';
$parameters = array(
'appid' => $this->appid, //appID
'mch_id' => $this->mch_id, //商户号
'nonce_str' => $this->createNoncestr(), //随机字符串
'transaction_id' => $this->transaction_id,
// 'out_trade_no' => '2015450806125348', //商户订单号
'out_refund_no'=> $this->out_refund_no,
// 'total_fee' => floatval(0.01 * 100), //总金额 单位 分
'total_fee' => $this->total_fee,
'refund_fee' => $this->refund_fee,
'notify_url' => url('portal/Notify/notify', '', '', true), //通知地址 确保外网能正常访问
'refund_desc' => $this->refund_desc
);
//统一下单签名
$parameters['sign'] = $this->getSign($parameters);
$xmlData = $this->arrayToXmlT($parameters);
$return = $this->xmlToArray($this->postXmlCurl($xmlData, $url, 60,1));
return $return;
}
private static function postXmlCurl($xml, $url, $second = 30,$pem = null)
{
$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, FALSE); //严格校验
//设置header
curl_setopt($ch, CURLOPT_HEADER, FALSE);
//要求结果为字符串且输出到屏幕上
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
//post提交方式
curl_setopt($ch, CURLOPT_POST, TRUE);
curl_setopt($ch, CURLOPT_POSTFIELDS, $xml);
if($pem) {
//以下是证书相关代码
curl_setopt($ch,CURLOPT_SSLCERTTYPE,'PEM');
curl_setopt($ch,CURLOPT_SSLCERT,EXTEND_PATH.'WxminipayAPI/cert/apiclient_cert.pem');//绝对路径
curl_setopt($ch,CURLOPT_SSLKEYTYPE,'PEM');
curl_setopt($ch,CURLOPT_SSLKEY,EXTEND_PATH.'WxminipayAPI/cert/apiclient_key.pem');//绝对路径
}
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 20);
curl_setopt($ch, CURLOPT_TIMEOUT, 40);
set_time_limit(0);
//运行curl
$data = curl_exec($ch);
//返回结果
if ($data) {
curl_close($ch);
return $data;
} else {
$error = curl_errno($ch);
curl_close($ch);
return $error;
// throw new WxPayException("curl出错,错误码:$error");
}
}
//数组转换成xml
private function arrayToXml($arr) {
$xml = "<root>";
foreach ($arr as $key => $val) {
if (is_array($val)) {
$xml .= "<" . $key . ">" . arrayToXml($val) . "</" . $key . ">";
} else {
$xml .= "<" . $key . ">" . $val . "</" . $key . ">";
}
}
$xml .= "</root>";
return $xml;
}
//数组转换成xml
private function arrayToXmlT($arr) {
$xml = "<xml>";
foreach ($arr as $key => $val) {
if (is_array($val)) {
$xml .= "<" . $key . ">" . arrayToXmlT($val) . "</" . $key . ">";
} else {
$xml .= "<" . $key . ">" . $val . "</" . $key . ">";
}
}
$xml .= "</xml>";
return $xml;
}
//xml转换成数组
private function xmlToArray($xml) {
//禁止引用外部xml实体
libxml_disable_entity_loader(true);
$xmlstring = simplexml_load_string($xml,'SimpleXMLElement', LIBXML_NOCDATA);
$val = json_decode(json_encode($xmlstring), true);
return $val;
}
//微信接口
private function weixinrefund() {
//退款接口
$refund = $this->refund();
return $refund;
// print_r($unifiedorder);
$parameters = array(
'appId' => $this->appid, //小程序ID
'timeStamp' => '' . time() . '', //时间戳
'nonceStr' => $this->createNoncestr(), //随机串
'package' => 'prepay_id=' . $refund['prepay_id'], //数据包
'signType' => 'MD5'//签名方式
);
//签名
$parameters['paySign'] = $this->getSign($parameters);
return $parameters;
}
//作用:产生随机字符串,不长于32位
private function createNoncestr($length = 32) {
$chars = "abcdefghijklmnopqrstuvwxyz0123456789";
$str = "";
for ($i = 0; $i < $length; $i++) {
$str .= substr($chars, mt_rand(0, strlen($chars) - 1), 1);
}
return $str;
}
//作用:生成签名
private function getSign($Obj) {
foreach ($Obj as $k => $v) {
$Parameters[$k] = $v;
}
//签名步骤一:按字典序排序参数
ksort($Parameters);
$String = $this->formatBizQueryParaMap($Parameters, false);
//签名步骤二:在string后加入KEY
$String = $String . "&key=" . $this->key;
//签名步骤三:MD5加密
$String = md5($String);
//签名步骤四:所有字符转为大写
$result_ = strtoupper($String);
return $result_;
}
///作用:格式化参数,签名过程需要使用
private function formatBizQueryParaMap($paraMap, $urlencode) {
$buff = "";
ksort($paraMap);
foreach ($paraMap as $k => $v) {
if ($urlencode) {
$v = urlencode($v);
}
$buff .= $k . "=" . $v . "&";
}
$reqPar = "";
if (strlen($buff) > 0) {
$reqPar = substr($buff, 0, strlen($buff) - 1);
}
return $reqPar;
}
}
... ...
<?php
/**
* Created by PhpStorm.
* User: rui
* Date: 2017/12/7
* Time: 11:10
* 小程序微信支付
* notify_url地址按自己的路径/方法修改
*/
class WeixinPay {
protected $appid;
protected $mch_id;
protected $key;
protected $openid;
protected $out_trade_no;
protected $body;
protected $total_fee;
protected $notify;
function __construct($appid, $openid, $mch_id, $key,$out_trade_no,$body,$total_fee,$notify) {
$this->appid = $appid;
$this->openid = $openid;
$this->mch_id = $mch_id;
$this->key = $key;
$this->out_trade_no = $out_trade_no;
$this->body = $body;
$this->total_fee = $total_fee;
$this->notify = $notify;
}
public function pay() {
//统一下单接口
$return = $this->weixinapp();
return $return;
}
//统一下单接口
private function unifiedorder() {
$url = 'https://api.mch.weixin.qq.com/pay/unifiedorder';
$parameters = array(
'appid' => $this->appid, //小程序ID
'mch_id' => $this->mch_id, //商户号
'nonce_str' => $this->createNoncestr(), //随机字符串
// 'body' => 'test', //商品描述 $this->notify
'body' => $this->body,
// 'out_trade_no' => '2015450806125348', //商户订单号
'out_trade_no'=> $this->out_trade_no,
// 'total_fee' => floatval(0.01 * 100), //总金额 单位 分
'total_fee' => $this->total_fee,
// 'spbill_create_ip' => '192.168.0.161', //终端IP
'spbill_create_ip' => get_client_ip(0,true), //终端IP
'notify_url' => $this->notify,
'openid' => $this->openid, //用户id
'trade_type' => 'JSAPI'//交易类型
);
F('par',$this->notify);
//统一下单签名
$parameters['sign'] = $this->getSign($parameters);
$xmlData = $this->arrayToXml($parameters);
$return = $this->xmlToArray($this->postXmlCurl($xmlData, $url, 60));
F('res',$return);
return $return;
}
protected function postXmlCurl($xml, $url, $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, FALSE); //严格校验
//设置header
curl_setopt($ch, CURLOPT_HEADER, FALSE);
//要求结果为字符串且输出到屏幕上
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
//post提交方式
curl_setopt($ch, CURLOPT_POST, TRUE);
curl_setopt($ch, CURLOPT_POSTFIELDS, $xml);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 20);
curl_setopt($ch, CURLOPT_TIMEOUT, 40);
set_time_limit(0);
//运行curl
$data = curl_exec($ch);
//返回结果
if ($data) {
curl_close($ch);
return $data;
} else {
$error = curl_errno($ch);
curl_close($ch);
throw new WxPayException("curl出错,错误码:$error");
}
}
//数组转换成xml
private function arrayToXml($arr) {
$xml = "<root>";
foreach ($arr as $key => $val) {
if (is_array($val)) {
$xml .= "<" . $key . ">" . arrayToXml($val) . "</" . $key . ">";
} else {
$xml .= "<" . $key . ">" . $val . "</" . $key . ">";
}
}
$xml .= "</root>";
return $xml;
}
//xml转换成数组
private function xmlToArray($xml) {
//禁止引用外部xml实体
libxml_disable_entity_loader(true);
$xmlstring = simplexml_load_string($xml, 'SimpleXMLElement', LIBXML_NOCDATA);
$val = json_decode(json_encode($xmlstring), true);
return $val;
}
//微信小程序接口
private function weixinapp() {
//统一下单接口
$unifiedorder = $this->unifiedorder();
// print_r($unifiedorder);
$parameters = array(
'appId' => $this->appid, //小程序ID
'timeStamp' => '' . time() . '', //时间戳
'nonceStr' => $this->createNoncestr(), //随机串
'package' => 'prepay_id=' . $unifiedorder['prepay_id'], //数据包
'signType' => 'MD5'//签名方式
);
//签名
$parameters['paySign'] = $this->getSign($parameters);
return $parameters;
}
//作用:产生随机字符串,不长于32位
private function createNoncestr($length = 32) {
$chars = "abcdefghijklmnopqrstuvwxyz0123456789";
$str = "";
for ($i = 0; $i < $length; $i++) {
$str .= substr($chars, mt_rand(0, strlen($chars) - 1), 1);
}
return $str;
}
//作用:生成签名
private function getSign($Obj) {
foreach ($Obj as $k => $v) {
$Parameters[$k] = $v;
}
//签名步骤一:按字典序排序参数
ksort($Parameters);
$String = $this->formatBizQueryParaMap($Parameters, false);
//签名步骤二:在string后加入KEY
$String = $String . "&key=" . $this->key;
//签名步骤三:MD5加密
$String = md5($String);
//签名步骤四:所有字符转为大写
$result_ = strtoupper($String);
return $result_;
}
///作用:格式化参数,签名过程需要使用
private function formatBizQueryParaMap($paraMap, $urlencode) {
$buff = "";
ksort($paraMap);
foreach ($paraMap as $k => $v) {
if ($urlencode) {
$v = urlencode($v);
}
$buff .= $k . "=" . $v . "&";
}
$reqPar = '';
if (strlen($buff) > 0) {
$reqPar = substr($buff, 0, strlen($buff) - 1);
}
return $reqPar;
}
}
\ No newline at end of file
... ...