PHP开发微信商家转账到零钱接口

仔细阅读了微信接口文档并且参考网上的案例,完成了商家转账到零钱的接口开发,目前已在使用中

下面是完整代码:

/**
     * @notes 商家转账到零钱
     */
    public static function transfer($withdrawApply,$userAuth,$config)
    {
        //请求URL
        $url = 'https://api.mch.weixin.qq.com/v3/transfer/batches';
        //请求方式
        $http_method = 'POST';
        //请求参数
        $data = [
            'appid' => $config['app_id'],//申请商户号的appid或商户号绑定的appid(企业号corpid即为此appid)
            'out_batch_no' => $withdrawApply['batch_no'],//商户系统内部的商家批次单号,要求此参数只能由数字、大小写字母组成,在商户系统内部唯一
            'batch_name' => '提现至微信零钱',//该笔批量转账的名称
            'batch_remark' => '提现至微信零钱',//转账说明,UTF8编码,最多允许32个字符
            'total_amount' => $withdrawApply['left_money'] * 100,//转账金额单位为“分”。转账总金额必须与批次内所有明细转账金额之和保持一致,否则无法发起转账操作
            'total_num' => 1,//一个转账批次单最多发起三千笔转账。转账总笔数必须与批次内所有明细之和保持一致,否则无法发起转账操作
            'transfer_detail_list' => [
                [//发起批量转账的明细列表,最多三千笔
                    'out_detail_no' => $withdrawApply['sn'],//商户系统内部区分转账批次单下不同转账明细单的唯一标识,要求此参数只能由数字、大小写字母组成
                    'transfer_amount' => $withdrawApply['left_money'] * 100,//转账金额单位为分
                    'transfer_remark' => '提现至微信零钱',//单条转账备注(微信用户会收到该备注),UTF8编码,最多允许32个字符
                    'openid' => $userAuth['openid'],//openid是微信用户在公众号appid下的唯一用户标识(appid不同,则获取到的openid就不同),可用于永久标记一个用户
                ]]
        ];
        if ($withdrawApply['left_money'] >= 2000) {
            if (empty($withdrawApply['real_name'])) {
                throw new \Exception('转账金额 >= 2000元,收款用户真实姓名必填');
            }
            $data['transfer_detail_list'][0]['user_name'] = self::getEncrypt($withdrawApply['real_name'],$config);
        }

        $token  = self::token($url,$http_method,$data,$config);//获取token
        $result = self::https_request($url,json_encode($data),$token);//发送请求
        $result_arr = json_decode($result,true);

        if(!isset($result_arr['create_time'])) {//批次受理失败
            throw new \Exception($result_arr['message']);
        }

        //批次受理成功,进行操作


        return true;
    }

    /**
     * @notes 获取签名
     */
    public static function token($url,$http_method,$data,$config)
    {
        $timestamp   = time();//请求时间戳
        $url_parts   = parse_url($url);//获取请求的绝对URL
        $nonce       = $timestamp.rand('10000','99999');//请求随机串
        $body        = empty($data) ? '' : json_encode((object)$data);//请求报文主体
        $stream_opts = [
            "ssl" => [
                "verify_peer"=>false,
                "verify_peer_name"=>false,
            ]
        ];

        $apiclient_cert_arr = openssl_x509_parse(file_get_contents($config['cert_path'],false, stream_context_create($stream_opts)));
        $serial_no          = $apiclient_cert_arr['serialNumberHex'];//证书序列号
        $mch_private_key    = file_get_contents($config['key_path'],false, stream_context_create($stream_opts));//密钥
        $merchant_id = $config['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);//签名
        $schema = 'WECHATPAY2-SHA256-RSA2048';
        $token = sprintf('mchid="%s",nonce_str="%s",timestamp="%d",serial_no="%s",signature="%s"',
            $merchant_id, $nonce, $timestamp, $serial_no, $sign);//微信返回token
        return $schema.' '.$token;
    }

    /**
     * @notes 发送请求
     */
    public static function https_request($url,$data,$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:'.$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;
    }

    /**
     * @notes 敏感信息加解密
     */
    public static function getEncrypt($str,$config)
    {
        //$str是待加密字符串
        $public_key = file_get_contents($config['cert_path']);
        $encrypted = '';
        if (openssl_public_encrypt($str, $encrypted, $public_key, OPENSSL_PKCS1_OAEP_PADDING)) {
            //base64编码
            $sign = base64_encode($encrypted);
        } else {
            throw new \Exception('encrypt failed');
        }
        return $sign;
    }

    /**
     * @notes 商家明细单号查询
     */
    public static function detailsQuery($withdrawApply,$config)
    {
        //请求URL
        $url = 'https://api.mch.weixin.qq.com/v3/transfer/batches/out-batch-no/'.$withdrawApply['batch_no'].'/details/out-detail-no/'.$withdrawApply['sn'];
        //请求方式
        $http_method = 'GET';
        //请求参数
        $data = [];
        $token  = self::token($url,$http_method,$data,$config);//获取token
        $result = self::https_request($url,$data,$token);//发送请求
        $result_arr = json_decode($result,true);
        return $result_arr;
    }

注意事项:

1.明细转账金额 >= 2,000元,收款用户姓名必填;

2.同一批次转账明细中,收款用户姓名字段需全部填写、或全部不填写;

3.转账受理成功后,需要调用《商家明细单号查询》接口来判断转账状态;

最后补上微信开发文档:商家转账到零钱-文档中心-微信支付商户平台

经过评论区老哥的提醒,参数里带有收款用户姓名,得在HTTP头部增加Wechatpay-Serial,Wechatpay-Serial后面带上平台证书序列号。

附上证书相关接口文档:证书相关 - WechatPay-API-v3

 

 

  • 10
    点赞
  • 24
    收藏
    觉得还不错? 一键收藏
  • 6
    评论
微信商家转账零钱 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 对象,包含了接口响应的所有信息,可以根据业务需求进行处理。
评论 6
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值