1.封装一个类 ~~~ <?php namespace app\common\library; class WechatPay { public function transfer($params) { $post_data = [ "appid" => '*******',//微信小程序appid "out_batch_no" => date('YmdHis') . mt_rand(100000, 999900), "batch_name" => '提现到账', "batch_remark" => '提现到账', "total_amount" => intval(strval($params['money'] * 100)), "total_num" => 1, "transfer_detail_list" => [ [ 'out_detail_no' => date('YmdHis') . mt_rand(100000, 999900), 'transfer_amount' => intval(strval($params['money'] * 100)), 'transfer_remark' => '提现到账', 'openid' =>$params['openid'] , ] ] ]; $url = 'https://api.mch.weixin.qq.com/v3/transfer/batches'; $result = self::wx_post($url, json_encode($post_data, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE)); $result = json_decode($result, true); return $result; } public static function wx_post($url, $param) { $authorization = self::getV3Sign($url, "POST", $param); $curl = curl_init(); $headers = [ 'Authorization:' . $authorization, '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); curl_setopt($curl, CURLOPT_RETURNTRANSFER, true); curl_setopt($curl, CURLOPT_TIMEOUT, 500); curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false); curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false); curl_setopt($curl, CURLOPT_URL, $url); curl_setopt($curl, CURLOPT_POSTFIELDS, $param); curl_setopt($curl, CURLOPT_POST, true); $res = curl_exec($curl); curl_close($curl); return $res; } public static function getV3Sign($url, $http_method, $body) { $nonce = strtoupper(self::createNonceStr(32)); $timestamp = time(); $url_parts = parse_url($url); $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"; $private_key = self::getPrivateKey(); openssl_sign($message, $raw_sign, $private_key, 'sha256WithRSAEncryption'); $sign = base64_encode($raw_sign); $token = sprintf('WECHATPAY2-SHA256-RSA2048 mchid="%s",nonce_str="%s",timestamp="%s",serial_no="%s",signature="%s"', "1609423883", $nonce, $timestamp, "12CCAE4777BB59DB3B103E6F83D250D5215A738B", $sign); return $token; } public static function createNonceStr($length = 16) { $chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"; $str = ""; for ($i = 0; $i < $length; $i++) { $str .= substr($chars, mt_rand(0, strlen($chars) - 1), 1); } return $str; } public static function getPrivateKey($filepath = '') { if (empty($filepath)) { $cert_dir = getcwd().'/../addons/epay/certs/'; $filepath = $cert_dir . "apiclient_key.pem"; } return openssl_get_privatekey(file_get_contents($filepath)); } } ~~~ 2.引入类调用 ~~~ use app\common\library\WechatPay; ~~~ ~~~ $result = (new WechatPay)->transfer(['money' => $money, 'openid' => $openid]); ~~~