一个简单的微信支付类,实现了从微信财付通里面转账到个人微信的功能。本类适合直接转到零钱的操作,扩展后可以应用于转到银行卡等途径。
须知:1.到微信支付账户中开启企业付款功能;2.财付通有足够金额。
<?php
/** *
* Created by Brisk Ver
* User: 1076963452@qq.com
* Datetime: 2019/3/2 16:36
*/
//企业付款到微信零钱
class WxPayToUser
{
protected $appid = '';//商户账号appid
protected $mchid = '';//商户号
protected $mchkey = '';//支付密钥
protected $apiclient_cert = '';//证书的位置绝对路径
protected $apiclient_key = '';//证书的位置绝对路径
public function __construct($config)
{
$this->appid = $config['appid'];
$this->mchid = $config['mchid'];
$this->mchkey = $config['mchkey'];
$this->apiclient_cert = $config['sslsert_path'];
$this->apiclient_key = $config['sslkey_path'];
}
//随机字符串
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 arraytoxml($data)
{
$str='<xml>';
foreach($data as $k=>$v) {
$str.='<'.$k.'>'.$v.'</'.$k.'>';
}
$str.='</xml>';
return $str;
}
private function xmltoarray($xml)
{
//禁止引用外部xml实体
libxml_disable_entity_loader(true);
return json_decode(json_encode(simplexml_load_string($xml, 'SimpleXMLElement', LIBXML_NOCDATA)),true);
}
//发送请求
private function curl($param="",$url)
{
$postUrl = $url;
$curlPost = $param;
$ch = curl_init(); //初始化curl
curl_setopt($ch, CURLOPT_URL,$postUrl); //抓取指定网页
curl_setopt($ch, CURLOPT_HEADER, 0); //设置header
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); //要求结果为字符串且输出到屏幕上
curl_setopt($ch, CURLOPT_POST, 1); //post提交方式
curl_setopt($ch, CURLOPT_POSTFIELDS, $curlPost); // 增加 HTTP Header(头)里的字段
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE); // 终止从服务端进行验证
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
curl_setopt($ch,CURLOPT_SSLCERT,$this->apiclient_cert);
curl_setopt($ch,CURLOPT_SSLKEY,$this->apiclient_key);
$data = curl_exec($ch); //运行curl
curl_close($ch);
return $data;
}
/*
开始执行操作
*/
public function run($order)
{
$data = array(
'mch_appid'=>strval($this->appid),//商户账号appid(公众号、小程序、移动应用的APPID都是不一样的哦)
'mchid'=>strval($this->mchid),//商户号
'nonce_str'=>strval($this->createNoncestr()),//随机字符串
'partner_trade_no'=> strval($order['partner_trade_no']),//商户订单号
'openid'=> strval($order['openid']),//用户openid
'check_name'=>$order['check_name'],////NO_CHECK:不校验真实姓名 ,FORCE_CHECK:强校验真实姓名
're_user_name'=> $order['re_user_name'],//收款用户姓名
'amount'=>strval($order['amount']),//金额
'desc'=>$order['desc'],//企业付款描述信息
'spbill_create_ip'=> strval($order['spbill_create_ip']),//Ip地址
);
ksort($data);//按ASCII码排序数组
$str = '';
foreach($data as $k=>$v) {
$str .= $k.'='.$v.'&';
}
$str .= 'key='.$this->mchkey;//拼接支付商户的秘钥
$sign = strtoupper(md5($str));//转换为大写
$data['sign'] = $sign;
$xml = $this->arraytoxml($data);
$url = 'https://api.mch.weixin.qq.com/mmpaymkttransfers/promotion/transfers'; //调用接口
$res = $this->curl($xml,$url);
return $this->xmltoarray($res);//以数组方式返回,根据返回实现后期需要的逻辑业务
}
}