WxpayV2.php 10 KB

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