20,359
社区成员
发帖
与我相关
我的任务
分享
class WechatPay{
protected $wechat_appid;
protected $wechat_mchid;
protected $wechat_key;
function __construct($wechat_appid, $wechat_mchid, $wechat_key) {
$this->wechat_appid = $wechat_appid;
$this->wechat_mchid = $wechat_mchid;
$this->wechat_key = $wechat_key;
}
public function sendPay($out_trade_no, $total_fee, $subject, $notifyUrl, $id = 0) {
$url = 'https://api.mch.weixin.qq.com/pay/unifiedorder';
$nonce_str = Common::getRandChar(32); //随机字符串,长度要求在32位以内。
$param = [
'appid' => $this->wechat_appid,
'mch_id' => $this->wechat_mchid,
'nonce_str' => $nonce_str,
'body' => $subject,
'out_trade_no' => $out_trade_no,
'total_fee' => $total_fee,
'spbill_create_ip' => '127.0.0.1',
'notify_url' => $notifyUrl,
'trade_type' => 'NATIVE',
'product_id' => $id,
];
$xml = self::paySign($param, $this->wechat_key);
$http_result = Common::https_request($url, $xml['xml']);
$xml = simplexml_load_string($http_result, NULL, LIBXML_NOCDATA);
$result = json_decode(json_encode($xml), true);
if($result['return_code'] == 'FAIL'){
return ['result_code' => 'FAIL'];
}
return $result;
}
// 支付签名
public static function paySign($param, $wechatkey) {
ksort($param);
$stringSignTemp = '';
$xml = '<xml>';
foreach ($param as $key => $vo) {
$stringSignTemp .= $key . '=' . $vo . '&';
$xml .= '<' . $key . '>' . $vo . '</' . $key . '>';
}
// $stringSignTemp = rtrim($stringSignTemp,"&");
$stringSignTemp .= 'key=' . $wechatkey;
$sign = strtoupper(md5($stringSignTemp));
$xml .= '<sign>' . $sign . '</sign>';
$xml .= '</xml>';
$result_arr = [
'sign' => $sign,
'xml' => $xml
];
return $result_arr;
}
}