Files
kiri-wchat/wchat/qq/Recharge.php
T
2020-05-21 18:16:48 +08:00

109 lines
2.5 KiB
PHP

<?php
/**
* Created by PhpStorm.
* User: whwyy
* Date: 2018/3/26 0026
* Time: 10:22
*/
namespace wchat\qq;
use Exception;
use wchat\common\HttpClient;
use wchat\common\Result;
use wchat\common\Help;
class Recharge extends SmallProgram
{
private $money = 0;
private $orderNo;
private $data = [];
private $unifiedorder = 'https://qpay.qq.com/cgi-bin/pay/qpay_unified_order.cgi';
/**
* @param int $money
* @param string $orderNo
* @param string $openId
* @return array|mixed|Result
* @throws
*/
public function recharge(int $money, string $orderNo, $openId = '')
{
if ($money < 0) {
return new Result(['code' => 500, 'message' => '充值金额不能小于0.']);
}
$this->money = $money;
$this->orderNo = $orderNo;
$this->data['openid'] = $openId;
$this->request->setCallback(function ($result, $body) {
$data = Help::toArray($result);
if (isset($data['sign'])) {
$sign = $data['sign'];
unset($data['sign']);
}
if (!isset($sign)) {
$return['code'] = -1;
$return['message'] = '返回数据签名验证失败';
} else {
$data['postBody'] = $body;
$return['code'] = 0;
$return['data'] = $data;
if ($data['return_code'] == 'FAIL') {
$return['code'] = -1;
$return['message'] = $data['return_msg'];
}
}
return new Result($return);
});
return $this->send($this->unifiedorder, $this->builder());
}
/**
* @return string
*/
protected function builder()
{
$data = [
'appid' => $this->config->getAppid(),
'mch_id' => $this->config->getMchId(),
'nonce_str' => Help::random(32),
'body' => $this->config->getBody(),
'out_trade_no' => $this->orderNo,
'total_fee' => $this->money,
'spbill_create_ip' => $_SERVER['REMOTE_ADDR'],
'notify_url' => $this->config->getNotifyUrl(),
'trade_type' => $this->config->getTradeType(),
];
$this->data = array_merge($data, $this->data);
$key = $this->config->getKey();
$sign_type = $this->config->getSignType();
$this->data['sign_type'] = $this->config->getSignType();
$this->data['sign'] = Help::sign($this->data, $key, $sign_type);
return Help::toXml($this->data);
}
/**
* @param $url
* @param $data
* @return array|mixed|Result
* @throws Exception
*/
private function send($url, $data)
{
$this->request->setIsSSL(true);
$this->request->setMethod(HttpClient::POST);
$this->request->addHeader('Content-Type', 'text/xml');
return $this->request->send($url, $data);
}
}