Pay.php 9.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235
  1. <?php
  2. namespace app\service\api;
  3. use app\service\ConfServiceFacade;
  4. use laytp\traits\Error;
  5. use think\facade\Cache;
  6. use think\facade\Config;
  7. use think\facade\Request;
  8. use EasyWeChat\Factory;
  9. class Pay{
  10. use Error;
  11. /**
  12. * phpmailer对象
  13. */
  14. protected $wechat;
  15. protected $pay;
  16. /**
  17. * 构造函数
  18. */
  19. public function __construct()
  20. {
  21. $wechat = ConfServiceFacade::groupGet('system.wechat', true);
  22. // print_r($wechat);
  23. $pay = ConfServiceFacade::groupGet('system.pay', true);
  24. $this->wechat = $wechat;
  25. $this->pay = $pay;
  26. }
  27. /**
  28. * 初始化
  29. * @param $token
  30. * @return bool
  31. * @throws \think\db\exception\DataNotFoundException
  32. * @throws \think\db\exception\DbException
  33. * @throws \think\db\exception\ModelNotFoundException
  34. */
  35. public function option($plateform='wechat')
  36. {
  37. $wechat = ConfServiceFacade::groupGet('system.'.$plateform, true);
  38. // print_r($wechat);
  39. $pay = ConfServiceFacade::groupGet('system.pay', true);
  40. // print_r(IA_ROOT_WK.'/public/static/storage/'.$pay['cert_filename']);
  41. if(!empty($pay['cert_filename'])){
  42. $config = [
  43. // 必要配置
  44. 'app_id' => $wechat['appid'],
  45. 'mch_id' => $pay['wechat_pay_mchid'],
  46. 'key' => $pay['wechat_pay_apikey'], // API v2 密钥 (注意: 是v2密钥 是v2密钥 是v2密钥)
  47. // 如需使用敏感接口(如退款、发送红包等)需要配置 API 证书路径(登录商户平台下载 API 证书)
  48. 'cert_path' => IA_ROOT_WK.'/public/static/storage/'.$pay['cert_filename'], // XXX: 绝对路径!!!!
  49. 'key_path' => IA_ROOT_WK.'/public/static/storage/'.$pay['key_filename'], // XXX: 绝对路径!!!
  50. 'notify_url' => request()->domain() . SURL . '/index.php/api.pay/notify', // 你也可以在下单时单独设置来想覆盖它
  51. // 'log' => [
  52. // 'level' => 'debug',
  53. // 'file' => __DIR__.'/pay.log',
  54. // ],
  55. ];
  56. } else{
  57. $config = [
  58. // 必要配置
  59. 'app_id' => $wechat['appid'],
  60. 'mch_id' => $pay['wechat_pay_mchid'],
  61. 'key' => $pay['wechat_pay_apikey'], // API v2 密钥 (注意: 是v2密钥 是v2密钥 是v2密钥)
  62. 'notify_url' => request()->domain() . SURL . '/index.php/api.pay/notify', // 你也可以在下单时单独设置来想覆盖它
  63. // 'log' => [
  64. // 'level' => 'debug',
  65. // 'file' => __DIR__.'/pay.log',
  66. // ],
  67. ];
  68. }
  69. return Factory::payment($config);
  70. }
  71. /**
  72. * 付款到微信零钱
  73. * sOpenid:收款方openid
  74. * nMoney:转账金额
  75. */
  76. public function transfer_batches($sOpenid, $nMoney)
  77. {
  78. //请求URL
  79. $url = 'https://api.mch.weixin.qq.com/v3/transfer/batches';
  80. //请求方式
  81. $http_method = 'POST';
  82. $sOrderId = 'wd3452'.time();
  83. //请求参数
  84. $data = [
  85. 'appid' => $this->wechat['appid'],//申请商户号的appid或商户号绑定的appid(企业号corpid即为此appid)
  86. 'out_batch_no' =>$sOrderId,//商户系统内部的商家批次单号,要求此参数只能由数字、大小写字母组成,在商户系统内部唯一
  87. 'batch_name' => '提现至微信零钱',//该笔批量转账的名称
  88. 'batch_remark' => '提现至微信零钱',//转账说明,UTF8编码,最多允许32个字符
  89. 'total_amount' => $nMoney,//转账金额单位为“分”。转账总金额必须与批次内所有明细转账金额之和保持一致,否则无法发起转账操作
  90. 'total_num' => 1,//一个转账批次单最多发起三千笔转账。转账总笔数必须与批次内所有明细之和保持一致,否则无法发起转账操作
  91. 'transfer_detail_list' => [
  92. [//发起批量转账的明细列表,最多三千笔
  93. 'out_detail_no' => $sOrderId,//商户系统内部区分转账批次单下不同转账明细单的唯一标识,要求此参数只能由数字、大小写字母组成
  94. 'transfer_amount' => $nMoney,//转账金额单位为分
  95. 'transfer_remark' => '提现至微信零钱',//单条转账备注(微信用户会收到该备注),UTF8编码,最多允许32个字符
  96. 'openid' => $sOpenid,//openid是微信用户在公众号appid下的唯一用户标识(appid不同,则获取到的openid就不同),可用于永久标记一个用户
  97. ]]
  98. ];
  99. if ($nMoney >= 2000) {
  100. // if (empty($withdrawApply['real_name'])) {
  101. // throw new \Exception('转账金额 >= 2000元,收款用户真实姓名必填');
  102. // }
  103. // $data['transfer_detail_list'][0]['user_name'] = self::getEncrypt($withdrawApply['real_name'],$config);
  104. }
  105. $token = self::token($url,$http_method,$data,$this->pay);//获取token
  106. $result = self::https_request($url,json_encode($data),$token);//发送请求
  107. $result_arr = json_decode($result,true);
  108. if(!isset($result_arr['create_time'])) {//批次受理失败
  109. throw new \Exception($result_arr['message']);
  110. }
  111. //批次受理成功,进行操作
  112. return true;
  113. }
  114. /**
  115. * @notes 获取签名
  116. */
  117. public static function token($url,$http_method,$data,$config)
  118. {
  119. $timestamp = time();//请求时间戳
  120. $url_parts = parse_url($url);//获取请求的绝对URL
  121. $nonce = $timestamp.rand('10000','99999');//请求随机串
  122. $body = empty($data) ? '' : json_encode((object)$data);//请求报文主体
  123. $stream_opts = [
  124. "ssl" => [
  125. "verify_peer"=>false,
  126. "verify_peer_name"=>false,
  127. ]
  128. ];
  129. $apiclient_cert_arr = openssl_x509_parse(file_get_contents(IA_ROOT_WK.'/public/static/storage/'.$config['cert_filename'],false, stream_context_create($stream_opts)));
  130. $serial_no = $apiclient_cert_arr['serialNumberHex'];//证书序列号
  131. $mch_private_key = file_get_contents(IA_ROOT_WK.'/public/static/storage/'.$config['key_filename'],false, stream_context_create($stream_opts));//密钥
  132. $merchant_id = $config['wechat_pay_mchid'];//商户id
  133. $canonical_url = ($url_parts['path'] . (!empty($url_parts['query']) ? "?${url_parts['query']}" : ""));
  134. $message = $http_method."\n".
  135. $canonical_url."\n".
  136. $timestamp."\n".
  137. $nonce."\n".
  138. $body."\n";
  139. openssl_sign($message, $raw_sign, $mch_private_key, 'sha256WithRSAEncryption');
  140. $sign = base64_encode($raw_sign);//签名
  141. $schema = 'WECHATPAY2-SHA256-RSA2048';
  142. $token = sprintf('mchid="%s",nonce_str="%s",timestamp="%d",serial_no="%s",signature="%s"',
  143. $merchant_id, $nonce, $timestamp, $serial_no, $sign);//微信返回token
  144. return $schema.' '.$token;
  145. }
  146. /**
  147. * @notes 发送请求
  148. */
  149. public static function https_request($url,$data,$token)
  150. {
  151. $curl = curl_init();
  152. curl_setopt($curl, CURLOPT_URL, (string)$url);
  153. curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
  154. curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);
  155. if (!empty($data)){
  156. curl_setopt($curl, CURLOPT_POST, 1);
  157. curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
  158. }
  159. curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
  160. //添加请求头
  161. $headers = [
  162. 'Authorization:'.$token,
  163. 'Accept: application/json',
  164. 'Content-Type: application/json; charset=utf-8',
  165. 'User-Agent:Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.132 Safari/537.36',
  166. ];
  167. if(!empty($headers)){
  168. curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
  169. }
  170. $output = curl_exec($curl);
  171. curl_close($curl);
  172. return $output;
  173. }
  174. /**
  175. * @notes 敏感信息加解密
  176. */
  177. public static function getEncrypt($str,$config)
  178. {
  179. //$str是待加密字符串
  180. $public_key = file_get_contents(IA_ROOT_WK.'/public/static/storage/'.$this->pay['cert_filename']);
  181. $encrypted = '';
  182. if (openssl_public_encrypt($str, $encrypted, $public_key, OPENSSL_PKCS1_OAEP_PADDING)) {
  183. //base64编码
  184. $sign = base64_encode($encrypted);
  185. } else {
  186. throw new \Exception('encrypt failed');
  187. }
  188. return $sign;
  189. }
  190. /**
  191. * @notes 商家明细单号查询
  192. */
  193. public static function detailsQuery($withdrawApply,$config)
  194. {
  195. //请求URL
  196. $url = 'https://api.mch.weixin.qq.com/v3/transfer/batches/out-batch-no/'.$withdrawApply['batch_no'].'/details/out-detail-no/'.$withdrawApply['sn'];
  197. //请求方式
  198. $http_method = 'GET';
  199. //请求参数
  200. $data = [];
  201. $token = self::token($url,$http_method,$data,$config);//获取token
  202. $result = self::https_request($url,$data,$token);//发送请求
  203. $result_arr = json_decode($result,true);
  204. return $result_arr;
  205. }
  206. }