WxpayV2.php 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295
  1. <?php
  2. // +----------------------------------------------------------------------
  3. // | [ WE CAN DO IT MORE SIMPLE ]
  4. // +----------------------------------------------------------------------
  5. // | Copyright (c) 2018-2020 rights reserved.
  6. // +----------------------------------------------------------------------
  7. // | Author: YingZi
  8. // +----------------------------------------------------------------------
  9. // | Date: 2022-05-27 15:14
  10. // +----------------------------------------------------------------------
  11. declare (strict_types = 1);
  12. namespace library\utils;
  13. use WeChatPay\Builder;
  14. use WeChatPay\Formatter;
  15. use WeChatPay\Crypto\Rsa;
  16. use WeChatPay\Crypto\AesGcm;
  17. use WeChatPay\Crypto\AesEcb;
  18. use WeChatPay\Crypto\Hash;
  19. use WeChatPay\Util\PemUtil;
  20. use WeChatPay\Transformer;
  21. class WxpayV2{
  22. private $config;
  23. private $client;
  24. public $errorMsg;
  25. /**
  26. * 构造函数
  27. * @param type $config
  28. */
  29. public function __construct($config = []){
  30. if(empty($config)) $config = config('wxpay');
  31. $this->config = $config;
  32. // 工厂方法构造一个实例
  33. $this->client = Builder::factory([
  34. 'mchid' => $this->config["MCHID"],
  35. 'serial' => 'nop',
  36. 'privateKey' => 'any',
  37. 'certs' => ['any' => null],
  38. 'secret' => $this->config["ApiV2Key"],
  39. 'merchant' => [
  40. 'cert' => $this->config["ApiclientCert"],
  41. 'key' => $this->config["ApiclientKey"],
  42. ],
  43. ]);
  44. }
  45. public function wxmpPay($post=[]){
  46. $apiUrl = "v2/pay/unifiedorder";
  47. //sign_type默认MD5不用传
  48. $params = [
  49. 'appid' => $this->config["APPID"], // 小程序ID/微信开放平台审核通过的应用APPID
  50. 'mch_id' => $this->config["MCHID"], // 商户号
  51. 'nonce_str' => Formatter::nonce(), // 32位随机字符串
  52. 'body' => empty($post["body"]) ? "微信小程序支付" : $post["body"],
  53. 'attach' => empty($post["attach"])? "微信小程序支付" : $post["attach"],
  54. 'out_trade_no' => $post["out_trade_no"], // 商户订单号
  55. 'total_fee' => (int)(floatval($post["total"])*100), // 订单总金额,单位分
  56. 'spbill_create_ip' => empty($post["payer_client_ip"]) ? "127.0.0.1" : $post["payer_client_ip"], // 终端ip
  57. 'time_expire' => date("YmdHis",time()+30*60),//交易结束时间2018-06-08T10:34:56+08:00
  58. 'notify_url' => $this->config["NOTIFY_URL"], // 通知地址
  59. 'trade_type' => "JSAPI", // 交易类型
  60. 'openid' => $post["openid"],
  61. ];
  62. $result = $this->clientHttp("POST", $apiUrl, $params);
  63. if(empty($result)){
  64. if(empty($this->errorMsg)){
  65. $this->errorMsg = "支付错误001";
  66. }
  67. return false;
  68. }
  69. $resuleAr = Transformer::toArray($result);
  70. if(empty($resuleAr)){
  71. if(empty($this->errorMsg)){
  72. $this->errorMsg = "支付错误002";
  73. }
  74. return false;
  75. }
  76. if(empty($resuleAr["prepay_id"])){
  77. if(empty($this->errorMsg)){
  78. $this->errorMsg = "支付错误003";
  79. }
  80. return false;
  81. }
  82. //组装支付参数
  83. $payInfo=array();
  84. $payInfo['appId'] = $this->config["APPID"];
  85. $payInfo['timeStamp'] = time();
  86. $payInfo['nonceStr'] = Formatter::nonce();//生成随机数
  87. $payInfo["package"] = "prepay_id=".$resuleAr["prepay_id"];
  88. $payInfo['signType'] = 'MD5';
  89. $payInfo['paySign'] = $this->v2makeSign($payInfo);
  90. return $payInfo;
  91. }
  92. public function v2makeSign($values) {
  93. //签名步骤一:按字典序排序参数
  94. ksort($values);
  95. $string = $this->ToUrlParams($values);
  96. //签名步骤二:在string后加入KEY
  97. $string = $string . "&key=" . $this->config["ApiV2Key"];
  98. //签名步骤三:MD5加密
  99. $string = md5($string);
  100. //签名步骤四:所有字符转为大写
  101. $result = strtoupper($string);
  102. return $result;
  103. }
  104. /**
  105. * 参数数组转换为url参数
  106. * @param array $urlObj
  107. */
  108. private function ToUrlParams($urlObj) {
  109. $buff = "";
  110. foreach ($urlObj as $k => $v) {
  111. $buff .= $k . "=" . $v . "&";
  112. }
  113. $buff = trim($buff, "&");
  114. return $buff;
  115. }
  116. /**
  117. * 订单查询
  118. * @param type $out_trade_no
  119. */
  120. public function searchOrderQuery($out_trade_no){
  121. $apiUrl = "v2/pay/orderquery";
  122. $result = $this->clientHttp("POST", $apiUrl, [
  123. 'appid' => $this->config["APPID"], // 小程序ID/微信开放平台审核通过的应用APPID
  124. 'mch_id' => $this->config["MCHID"], // 商户号
  125. "out_trade_no" =>$out_trade_no,
  126. 'nonce_str' => Formatter::nonce(), // 32位随机字符串
  127. ]);
  128. return $result;
  129. // var_dump($result);
  130. }
  131. /**
  132. * 查询订单
  133. * @param type $out_trade_no 商户订单号
  134. */
  135. public function searchOrder($out_trade_no){
  136. $apiUrl = "v3/pay/transactions/out-trade-no/{out_trade_no}";
  137. $result = $this->clientHttp("GET", $apiUrl,[
  138. "out_trade_no"=>$out_trade_no,
  139. "query"=>["mchid"=>$this->config["MCHID"]],
  140. ]);
  141. return $result;
  142. }
  143. /**
  144. * 关闭订单
  145. * @param type $out_trade_no 商户订单号
  146. */
  147. public function closeOrder($out_trade_no){
  148. $apiUrl = "v3/pay/transactions/out-trade-no/{out_trade_no}/close";
  149. $result = $this->clientHttp("GET", $apiUrl,[
  150. "out_trade_no"=>$out_trade_no,
  151. "query"=>["mchid"=>$this->config["MCHID"]],
  152. ]);
  153. return $result;
  154. }
  155. // public function v2makeSign($info){
  156. // $params = [
  157. // 'appId' => $info["appId"],
  158. // 'timeStamp' => time(),
  159. // 'nonceStr' => Formatter::nonce(),
  160. // 'package' => "prepay_id=".$info["prepay_id"],
  161. // ];
  162. // var_dump(Formatter::queryStringLike(Formatter::ksort($params)));
  163. // $params['paySign'] = Hash::sign(
  164. // Hash::ALGO_MD5,//默认md5
  165. // Formatter::queryStringLike(Formatter::ksort($params)),
  166. // $this->config["ApiV2Key"],
  167. // );
  168. // $params['signType'] = Hash::ALGO_MD5;
  169. // return $params;
  170. // }
  171. /**
  172. * 生成签名
  173. * @param type $info
  174. * @return string
  175. */
  176. private function makeSign($info){
  177. $params = [
  178. 'appId' => $info["appId"],
  179. 'timeStamp' => (string)Formatter::timestamp(),
  180. 'nonceStr' => Formatter::nonce(),
  181. 'package' => 'prepay_id='.$info["prepay_id"],
  182. ];
  183. $params["paySign"] = Rsa::sign(Formatter::joinedByLineFeed(...array_values($params)),$this->merchantPrivateKeyInstance);
  184. $params["signType"] = 'RSA';
  185. return $params;
  186. }
  187. /**
  188. * 解密回调参数
  189. * @param type $data
  190. * @return type
  191. */
  192. public function aesGcmDecrypt($data){
  193. // 加密文本消息解密
  194. $inBodyResource = AesGcm::decrypt($data["ciphertext"], $this->config["apiv3Key"], $data["nonce"], $data["associated_data"]);
  195. // 把解密后的文本转换为PHP Array数组
  196. $inBodyResourceArray = (array)json_decode($inBodyResource, true);
  197. return $inBodyResourceArray;
  198. }
  199. /**
  200. * http提交[同步请求]
  201. * @param type $type
  202. * @param type $url 示例:v3/pay/transactions/native
  203. * @param type $json
  204. * @return boolean
  205. */
  206. private function clientHttp($type='POST',$url='',$json=[]){
  207. try {
  208. $resp=null;
  209. if($type=="POST"){
  210. $resp = $this->client->chain($url)->post(['xml' => $json]);
  211. if(empty($json)){
  212. $resp = $this->client->chain($url)->post();
  213. }else{
  214. $resp = $this->client->chain($url)->post(['xml' => $json]);
  215. }
  216. }
  217. if($type=="GET"){
  218. if(empty($json)){
  219. $resp = $this->client->chain($url)->get();
  220. }else{
  221. $resp = $this->client->chain($url)->get($json);
  222. }
  223. }
  224. if(empty($resp)){
  225. $this->errorMsg="提交方式错误";
  226. return false;
  227. }
  228. $statusCode = $resp->getStatusCode();
  229. if ($statusCode == 200) { //处理成功
  230. return $resp->getBody()->getContents();
  231. } else if ($statusCode == 204) { //处理成功,无返回Body
  232. $this->errorMsg = "处理成功,无返回Body";
  233. return false;
  234. }else{
  235. $this->errorMsg = "未知错误";
  236. return false;
  237. }
  238. } catch (\Exception $e) {
  239. // var_dump($e->getMessage());
  240. // 进行错误处理
  241. $this->errorMsg = $e->getMessage();
  242. if ($e instanceof \GuzzleHttp\Exception\RequestException && $e->hasResponse()) {
  243. $r = $e->getResponse();
  244. $this->errorMsg=$r->getStatusCode()."".$r->getReasonPhrase().$r->getBody();
  245. }
  246. return false;
  247. }
  248. }
  249. /**
  250. * 回调验签
  251. * @param type $inBody
  252. * @return bool
  253. */
  254. public function notifyCheckSign($inBody){
  255. $apiv2Key = $this->config["ApiV2Key"];// 在商户平台上设置的APIv2密钥
  256. $inBodyArray = Transformer::toArray($inBody);
  257. $signType = empty($inBodyArray["sign_type"]) ? Hash::ALGO_MD5 : $inBodyArray["sign_type"];
  258. $sign = $inBodyArray["sign"];
  259. $calculated = Hash::sign(
  260. $signType,// 如没获取到`sign_type`,假定默认为`MD5`
  261. Formatter::queryStringLike(Formatter::ksort($inBodyArray)),
  262. $apiv2Key
  263. );
  264. $signatureStatus = Hash::equals($calculated, $sign);
  265. if ($signatureStatus) {
  266. // 如需要解密的
  267. $inBodyReqInfoArray = null;
  268. if(!empty($inBodyArray['req_info'])){
  269. $reqInfo = $inBodyArray['req_info'];
  270. $inBodyReqInfoXml = AesEcb::decrypt($reqInfo, Hash::md5($apiv2Key));
  271. $inBodyReqInfoArray = Transformer::toArray($inBodyReqInfoXml);
  272. }
  273. return [
  274. "data"=>$inBodyArray,//消息体
  275. "info"=>$inBodyReqInfoArray//解密数据
  276. ];
  277. }
  278. return $signatureStatus;
  279. }
  280. }