微信商家转账到零钱

 1.发起商家转账

发起商家转账接口。商户可以通过该接口同时向多个用户微信零钱进行转账操作。请求消息中应包含商家批次单号、转账名称、appid、转账总金额、转账总笔数、转账openid、收款用户姓名等信息。注意受理成功将返回批次单号,此时并不代表转账成功,请通过查单接口查询单据的付款状态

请求后返回数据

 

2.通过商家批次单号查询批次单

商家明细单号查单接口。商户可以通过该接口查询转账批次单以及指定状态的转账明细单。返回消息中包含微信批次单号、批次状态、批次类型、转账总金额、转账总笔数、成功金额、失败金额等信息。

返回数据

<?php

namespace fast;

class WxWithdrawal
{
    protected $mch_id = '';//商户号
    protected $appid = '';//appID
    // 证书、密钥地址
    protected $cert_pem = './../extend/wx/apiclient_cert.pem';
    protected $key_pem = './../extend/wx/apiclient_key.pem';
    public function __construct()
    {
//        parent::__construct();
    }

    /**
     * 商家转账到零钱
     * @param $arr
     * @return mixed
     */
    public function tx($arr)
    {
        $remark = '佣金';
        // 需要转账的用户信息
//        $arr = [
//            [
//                'order_sn'=>'TEST'.time(),//
//                'total_money'=>$money,
//                'openid'=>$openid
                'openid'=>'oFMDw6hx3Wuvey_EGjHFw8AtyTNs'
//            ]
//        ];
        // 转账明细列表
        $transfer_detail_list = [];
        foreach($arr as $k=>$v){
            $transfer_detail_list[$k]['out_detail_no'] = $v['order_sn'];
            $transfer_detail_list[$k]['transfer_amount'] = (int)bcmul($v['total_money'], 100, 0);;
            $transfer_detail_list[$k]['transfer_remark'] = $remark;
            $transfer_detail_list[$k]['openid'] = $v['openid'];
        }

        // 参数
        $out_batch_no = 'TEST'.time(); // 商家批次单号
        $batch_name = '佣金'; // 该笔批量转账的名称
        $batch_remark = '佣金'; // 转账说明,最多允许32个字符
        $total_amount = number_format(array_sum(array_column($arr,'total_money')),2); // 转账总金额单位为“分”。
        $total_num = count($arr); // 转账总笔数,一个转账批次单最多发起一千笔转账
        $params = [
            'appid'=>$this->appid,
            'out_batch_no'=>$out_batch_no,
            'batch_name'=>$batch_name,
            'batch_remark'=>$batch_remark,
            'total_amount'=>$total_amount * 100,
            'total_num'=>$total_num,
            'transfer_detail_list'=>$transfer_detail_list,
            'notify_url'=>'https://kbadmin.wubukeji.com/pay/wxwith_notify/wxnotify',
        ];

        // 商家转账没有要求参数排序,可写可不写
        $params = $this->param_filter($params);   //  过滤参数
        $params = $this->param_sort($params);    //  参数排序

        $url = 'https://api.mch.weixin.qq.com/v3/transfer/batches';
        $params = json_encode($params);
        $token = $this->getToken($url,time(),$params);

        $res_xml = $this->https_request($url,$params,$token);

        $resArr = json_decode($res_xml,true);
        return $resArr;
        // 查看请求数据
//        var_dump($resArr);
        // 业务逻辑...
    }

    /**
     *
     * @param $out_batch_no
     * @return mixed
     */
    public function query($out_batch_no)
    {
        $params = [
            'GET'=>'',
            'offset'=>0,
            'limit'=>20,
            'detail_status'=>'ALL'
        ];
//        $out_batch_no='TEST1719306082';

        $url = 'https://api.mch.weixin.qq.com/v3/transfer/batches/out-batch-no/'.$out_batch_no.'?need_query_detail=true&detail_status=ALL';
//        $params = json_encode($params);
        $token = $this->getToken($url,time(),'','GET');
//        halt($token );
        $res_xml = $this->GetHttp($url,$token);
        $resArr = json_decode($res_xml,true);
        return $resArr;
    }

    // 获取请求头
    public function getToken($url,$timestamp,$body='',$http_method='POST')
    {
        $url_parts   = parse_url($url); //获取请求的绝对URL
        $nonce       = $this->nonce();  //请求随机串
        $stream_opts = [
            "ssl" => [
                "verify_peer"=>false,
                "verify_peer_name"=>false,
            ]
        ];
        $apiclient_cert_path = $this->cert_pem;
        $apiclient_key_path  = $this->key_pem;
        $apiclient_cert_arr = openssl_x509_parse(file_get_contents($apiclient_cert_path,false, stream_context_create($stream_opts)));
        $serial_no          = $apiclient_cert_arr['serialNumberHex'];   // 证书序列号(忽略)
        $mch_private_key    = file_get_contents($apiclient_key_path,false, stream_context_create($stream_opts));    // 密钥
        $merchant_id = $this->mch_id;   // 商户id
        $canonical_url = ($url_parts['path'] . (!empty($url_parts['query']) ? "?${url_parts['query']}" : ""));
        $message = $http_method."\n".
            $canonical_url."\n".
            $timestamp."\n".
            $nonce."\n".
            $body."\n";

        openssl_sign($message, $raw_sign, $mch_private_key, 'sha256WithRSAEncryption');

        $sign = base64_encode($raw_sign);   // 签名
        return sprintf('mchid="%s",nonce_str="%s",timestamp="%d",serial_no="%s",signature="%s"',
            $merchant_id, $nonce, $timestamp, $serial_no, $sign);   // 微信返回token
    }

    // 过滤参数
    public function param_filter($para)
    {
        $paraFilter = [];
        foreach ($para as $key => $val) {
            if ($val === '' || $val === null) {
                continue;
            }
            if (!is_array($para[$key])) {
                if (!is_numeric($para[$key])){
                    $para[$key] = is_bool($para[$key]) ? $para[$key] : trim($para[$key]);
                }
            }

            $paraFilter[$key] = $para[$key];
        }

        return $paraFilter;
    }

    // 参数排序
    public function param_sort(array $param)
    {
        ksort($param);
        reset($param);

        return $param;
    }

    public  function GetHttp($url,$token=''){
        // 关闭句柄
        $curl = curl_init(); // 启动一个CURL会话
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_HEADER, 0);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false); // 跳过证书检查
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false); // 从证书中检查SSL加密算法是否存在
        // 设置Accept头部字段
        //添加请求头
        $headers = [
            'Authorization:WECHATPAY2-SHA256-RSA2048 '.$token,
            'Accept: application/json',
            'Content-Type: application/json; charset=utf-8',
            'User-Agent:Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.132 Safari/537.36',
        ];
        curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
        $tmpInfo = curl_exec($curl); //返回api的json对象
        if(curl_exec($curl) === false)
        {
            return 'Curl error: ' . curl_error($curl);
        }
        //关闭URL请求
        curl_close($curl);
        return $tmpInfo; //返回json对象
    }
    /**
     *请求接口
     */
    function https_request($url,$data = null,$token=''){
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, (string)$url);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);
        if (!empty($data)){
            curl_setopt($curl, CURLOPT_POST, 1);
            curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
        }
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        //添加请求头
        $headers = [
            'Authorization:WECHATPAY2-SHA256-RSA2048 '.$token,
            'Accept: application/json',
            'Content-Type: application/json; charset=utf-8',
            'User-Agent:Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.132 Safari/537.36',
        ];
        if(!empty($headers)){
            curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
        }
        $output = curl_exec($curl);
        curl_close($curl);
        return $output;
    }

    // 随机数
    public function nonce(int $size = 32)
    {
        if ($size < 1) {
            throw new InvalidArgumentException('Size must be a positive integer.');
        }

        return implode('', array_map(static function(string $c): string {
            return '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'[ord($c) % 62];
        }, str_split(random_bytes($size))));
    }


}

  • 9
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
微信商家转账零钱 V3 的实现需要通过微信支付 API 接口来实现,以下是 JAVA 版本的代码实现: 1. 导入依赖包 ```java import java.util.HashMap; import java.util.Map; import com.github.wxpay.sdk.WXPay; import com.github.wxpay.sdk.WXPayConfig; import com.github.wxpay.sdk.WXPayConstants; import com.github.wxpay.sdk.WXPayUtil; ``` 2. 构造微信支付配置对象 ```java public class WXPayConfigImpl implements WXPayConfig { private String appID; // 公众账号ID或应用ID private String mchID; // 商户号 private String key; // 商户密钥 private String certPath; // 商户证书路径 private int httpConnectTimeoutMs = 6 * 1000; // 连接超时时间 private int httpReadTimeoutMs = 8 * 1000; // 读取超时时间 public WXPayConfigImpl(String appID, String mchID, String key, String certPath) { this.appID = appID; this.mchID = mchID; this.key = key; this.certPath = certPath; } @Override public String getAppID() { return appID; } @Override public String getMchID() { return mchID; } @Override public String getKey() { return key; } @Override public InputStream getCertStream() { try { return new FileInputStream(new File(certPath)); } catch (FileNotFoundException e) { e.printStackTrace(); } return null; } @Override public int getHttpConnectTimeoutMs() { return httpConnectTimeoutMs; } @Override public int getHttpReadTimeoutMs() { return httpReadTimeoutMs; } } ``` 3. 构造微信支付对象 ```java WXPayConfig wxPayConfig = new WXPayConfigImpl(appID, mchID, key, certPath); WXPay wxPay = new WXPay(wxPayConfig, WXPayConstants.SignType.MD5, true); ``` 4. 构造参数并调用接口 ```java // 构造请求参数 Map<String, String> reqData = new HashMap<String, String>(); reqData.put("mch_appid", appID); reqData.put("mchid", mchID); reqData.put("nonce_str", WXPayUtil.generateNonceStr()); reqData.put("partner_trade_no", "xxxxxxxxxxxx"); // 商户订单号 reqData.put("openid", "xxxxxxxxxxxx"); // 用户openid reqData.put("check_name", "NO_CHECK"); // 不校验真实姓名 reqData.put("amount", "100"); // 转账金额 reqData.put("desc", "测试转账"); // 转账描述 reqData.put("spbill_create_ip", "127.0.0.1"); // 调用接口的机器IP地址 // 调用接口 Map<String, String> respData = wxPay.transfer(reqData); ``` 其中,`appID`、`mchID`、`key`、`certPath` 等参数需要根据实际情况填写。`wxPay.transfer(reqData)` 方法返回的是一个 Map 对象,包含了接口响应的所有信息,可以根据业务需求进行处理。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

梦夏夜

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值