需求:
新增提现功能
文档:
1.开通条件https://pay.weixin.qq.com/wiki/doc/api/tools/mch_pay.php?chapter=14_1
2.开通该功能比较麻烦,我也是连续多人付款了三四十天才开通成功(每次一两分钱)
服务端接口类代码
<?php
namespace App\Libs\common;
class WeiXinWithdrawDeposit {
private $openid;
private $APPID;
private $MCHID;
private $key;
private $partnerTradeNo;
private $totalFee;
private $remark;
private $SSLCERT_PATH;
private $SSLKEY_PATH;
/**
* WeiXinWithdrawDeposit constructor.
* @param $openid string 小程序用户的openid
* @param $appid string 商户账号绑定的appid
* @param $mch_id string 商户号
* @param $key string 商户秘钥
* @param $partnerTradeNo string(32) 商户订单号
* @param $totalFee float 金额
* @param $remark string(100) 提现备注
* desc:https://pay.weixin.qq.com/wiki/doc/api/tools/mch_pay.php?chapter=14_2
*/
public function __construct($openid,$appid,$mch_id,$key,$partnerTradeNo,$totalFee,$remark='余额提现'){
//初始化退款类需要的变量
$this->openid = $openid;//openid
$this->APPID = $appid;
$this->MCHID = $mch_id;
$this->key = $key;
$this->partnerTradeNo = $partnerTradeNo;//订单号order_sn
$this->totalFee = $totalFee;//订单总金额
$this->remark = $remark;//备注
$this->SSLCERT_PATH = app_path().'/Libs/wx_cert/apiclient_cert.pem';//证书路径
$this->SSLKEY_PATH = app_path().'/Libs/wx_cert/apiclient_key.pem';//证书路径
}
/*
* 请求接口
*/
public function withdraw_deposit(){
//re_user_name为空时,不加入sign验证
$param = array(
'mch_appid' => $this->APPID,
'mchid' => $this->MCHID,
'nonce_str' => $this->createNoncestr(),
'partner_trade_no' => $this->partnerTradeNo,
'openid' => $this->openid,
'check_name' => 'NO_CHECK',
// 're_user_name' => '',
'amount' => floatval(($this->totalFee) * 100),
'desc' => $this->remark,
'spbill_create_ip'=>$_SERVER['REMOTE_ADDR']
);
$param['sign'] = $this->getSign($param);
$xmldata = $this->arrayToXml($param);
$xmlresult = $this->postXmlSSLCurl($xmldata,'https://api.mch.weixin.qq.com/mmpaymkttransfers/promotion/transfers');
$result = $this->xmlToArray($xmlresult);
return $result;
}
//需要使用证书的请求
private function postXmlSSLCurl($xml,$url,$second=30)
{
$ch = curl_init();
//超时时间
curl_setopt($ch, CURLOPT_TIMEOUT, $second);
//这里设置代理,如果有的话
//curl_setopt($ch,CURLOPT_PROXY, '8.8.8.8');
//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);
//设置header
curl_setopt($ch, CURLOPT_HEADER, FALSE);
//要求结果为字符串且输出到屏幕上
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
//设置证书
//使用证书:cert 与 key 分别属于两个.pem文件
//默认格式为PEM,可以注释
curl_setopt($ch, CURLOPT_SSLCERTTYPE, 'PEM');
curl_setopt($ch, CURLOPT_SSLCERT, $this->SSLCERT_PATH);
//默认格式为PEM,可以注释
curl_setopt($ch, CURLOPT_SSLKEYTYPE, 'PEM');
curl_setopt($ch, CURLOPT_SSLKEY, $this->SSLKEY_PATH);
//post提交方式
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $xml);
$data = curl_exec($ch);
//返回结果
if ($data) {
curl_close($ch);
return $data;
} else {
$error = curl_errno($ch);
echo "curl出错,错误码:$error" . "<br>";
curl_close($ch);
return false;
}
}
//作用:生成签名
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;
}
//作用:产生随机字符串,不长于 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;
}
//数组转换成 xml
private function arrayToXml($arr) {
$xml = "<xml>
<mch_appid>".$arr['mch_appid']."</mch_appid>
<mchid>".$arr['mchid']."</mchid>
<nonce_str>".$arr['nonce_str']."</nonce_str>
<partner_trade_no>".$arr['partner_trade_no']."</partner_trade_no>
<openid>".$arr['openid']."</openid>
<check_name>".$arr['check_name']."</check_name>
<re_user_name></re_user_name>
<amount>".$arr['amount']."</amount>
<desc>".$arr['desc']."</desc>
<spbill_create_ip>".$arr['spbill_create_ip']."</spbill_create_ip>
<sign>".$arr['sign']."</sign>
</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;
}
/**
* 成功返回值
* array(9) {
["return_code"]=>
string(7) "SUCCESS"
["return_msg"]=>
array(0) {
}
["mch_appid"]=>
string(18) "小程序id"
["mchid"]=>
string(10) "商户号"
["nonce_str"]=>
string(32) "syylzwd3u7lcgwrwlylov227thb0i1x7"
["result_code"]=>
string(7) "SUCCESS"
["partner_trade_no"]=>
string(32) "20210702162304162521418474028374"
["payment_no"]=>
string(32) "10101258300502107026041097111670"
["payment_time"]=>
string(19) "2021-07-02 16:23:28"
}
*/
}
调用接口
//'///'开头的为项目逻辑,根据自己需要及项目进行处理
public function wx_withdraw_deposit($data){
///验证余额(检测用户余额来源是否合法)
//获取小程序配置信息
//获取商户号配置
//定义参数
$remark = '余额提现';
$order_sn = $this->get_order_sn();
///创建提现订单
$id = DB::getPdo()->lastInsertId();//创建的订单id
DB::beginTransaction();
/// 扣除余额
///调用提现接口
$withdraw_deposit = new WeiXinWithdrawDeposit($verify_balance['data']['wx_openid'],$mini_config['c_appid'],$mch_config['c_appid'],$mch_config['c_key'],$order_sn,$this->price_convert($data['withdrawal_price'],1),$remark);
$res = $withdraw_deposit->withdraw_deposit();
if ($res['result_code'] != 'SUCCESS'){
DB::rollback();
return ['status'=>false, 'msg'=>$res['err_code_des'], 'data'=>$res];
}
///处理结果(订单改为已完成)
DB::commit();
return ['status'=>true, 'msg'=>'成功', 'data'=>$res];
}