如何封装一个可以接收多个参数的方法而且参数位置可变?
- 定义个基类,
- 写一个类继承基类,其中定义一些基础必备参数
- 哪里需要调用就各自定义需要的参数即可
<?php
/**
* Created by IntelliJ IDEA.
* User: Administrator
* Date: 2017/5/26
* Time: 11:32
*/
namespace luweiss\wechat;
abstract class Base
{
/**
* 微信组件
*
* @var Wechat
*/
protected $wechat;
/**
* @param Wechat $wechat
*/
public function __construct($wechat)
{
$this->wechat = $wechat;
}
}<?php
/**
* Created by IntelliJ IDEA.
* User: Administrator
* Date: 2017/5/26
* Time: 10:18
*/
namespace luweiss\wechat;
class Pay extends Base
{
/**
* 统一下单
* @param array $args [
*
* 'body' => '商品描述',
*
* 'detail' => '商品详情,选填',
*
* 'attach' => '附加数据,选填',
*
* 'out_trade_no' => '商户订单号,最大长度32',
*
* 'total_fee' => '订单总金额,单位为分',
*
* 'notify_url' => '异步接收微信支付结果通知的回调地址,通知url必须为外网可访问的url,不能携带参数',
*
* 'trade_type' => '交易类型,可选值:JSAPI,NATIVE,APP',
*
* 'product_id' => '商品ID,trade_type=NATIVE时,此参数必传',
*
* 'openid' => '用户标识,trade_type=JSAPI时,此参数必传',
*
* ]
*
* @return array|boolean
*
*/
public function unifiedOrder($args)
{
$args['appid'] = $this->wechat->mchAppId;
$args['sub_appid'] = $this->wechat->appId;
$args['sub_mch_id'] = (int)$this->wechat->subMchId;
$args['mch_id'] = $this->wechat->mchId;
$args['profit_sharing'] = $this->wechat->profitSharing;//是否使用分账;Y是 N否
$args['nonce_str'] = md5(uniqid());
$args['sign_type'] = 'MD5';
$args['spbill_create_ip'] = '127.0.0.1';
$args['sign'] = $this->makeSign($args);
$xml = DataTransform::arrayToXml($args);
$api = "https://api.mch.weixin.qq.com/pay/unifiedorder";
$this->wechat->curl->post($api, $xml);
if (!$this->wechat->curl->response)
return false;
return DataTransform::xmlToArray($this->wechat->curl->response);
}
}调用:自己需要啥参数就自定义传参数
//单个订单微信支付下单
private function unifiedOrder($goods_names)
{
$this->wechat = $this->getWechat();
$res = $this->wechat->pay->unifiedOrder([
'body' => $goods_names,
'out_trade_no' => $this->order->order_no,
'total_fee' => $this->order->pay_price * 100,
'notify_url' => pay_notify_url('/pay-notify.php'),
'trade_type' => 'JSAPI',
'sub_openid' => $this->user->wechat_open_id,
]);
if (!$res) {
return [
'code' => 1,
'msg' => '支付失败',
];
}
if ($res['return_code'] != 'SUCCESS') {
return [
'code' => 1,
'msg' => '支付失败,' . (isset($res['return_msg']) ? $res['return_msg'] : ''),
'res' => $res,
];
}
if ($res['result_code'] != 'SUCCESS') {
if ($res['err_code'] == 'INVALID_REQUEST') { //商户订单号重复
$this->order->order_no = (new OrderSubmitForm())->getOrderNo();
$this->order->save();
return $this->unifiedOrder($goods_names);
} else {
return [
'code' => 1,
'msg' => '支付失败,' . (isset($res['err_code_des']) ? $res['err_code_des'] : ''),
'res' => $res,
];
}
}
return $res;
}版权声明:本文为dj1540225203原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。