AlipayService.php 7.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230
  1. <?php
  2. namespace crmeb\services;
  3. class AlipayService
  4. {
  5. protected $appId;
  6. protected $notifyUrl;
  7. protected $charset;
  8. //私钥值
  9. protected $rsaPrivateKey;
  10. protected $alipayPublicKey;
  11. protected $totalFee;
  12. protected $outTradeNo;
  13. protected $orderName;
  14. protected $passback_params = [];
  15. public function __construct()
  16. {
  17. $this->charset = 'utf-8';
  18. }
  19. public function setAppid($appid)
  20. {
  21. $this->appId = $appid;
  22. }
  23. public function setNotifyUrl($notifyUrl)
  24. {
  25. $this->notifyUrl = $notifyUrl;
  26. }
  27. public function setRsaPrivateKey($saPrivateKey)
  28. {
  29. $this->rsaPrivateKey = $saPrivateKey;
  30. }
  31. public function setAlipayPublicKey($alipayPublicKey)
  32. {
  33. $this->alipayPublicKey = $alipayPublicKey;
  34. }
  35. public function setTotalFee($payAmount)
  36. {
  37. $this->totalFee = $payAmount;
  38. }
  39. public function setOutTradeNo($outTradeNo)
  40. {
  41. $this->outTradeNo = $outTradeNo;
  42. }
  43. public function setOrderName($orderName)
  44. {
  45. $this->orderName = $orderName;
  46. }
  47. public function setPassbackParams($passback_params)
  48. {
  49. $this->passback_params = $passback_params;
  50. }
  51. /**
  52. * 获取orderStr
  53. * @return string
  54. */
  55. public function getOrderStr()
  56. {
  57. //请求参数
  58. $requestConfigs = array(
  59. 'out_trade_no' => $this->outTradeNo,
  60. 'total_amount' => $this->totalFee, //单位 元
  61. 'subject' => $this->orderName, //订单标题
  62. 'product_code' => 'QUICK_MSECURITY_PAY', //销售产品码,商家和支付宝签约的产品码,为固定值QUICK_MSECURITY_PAY
  63. 'timeout_express' => '15m', //该笔订单允许的最晚付款时间,逾期将关闭交易。取值范围:1m~15d。m-分钟,h-小时,d-天,1c-当天(1c-当天的情况下,无论交易何时创建,都在0点关闭)。 该参数数值不接受小数点, 如 1.5h,可转换为 90m。
  64. // 'store_id'=>'', //商户门店编号。该参数用于请求参数中以区分各门店,非必传项。
  65. // 'extend_params'=>array(
  66. // 'sys_service_provider_id'=>'' //系统商编号,该参数作为系统商返佣数据提取的依据,请填写系统商签约协议的PID
  67. // )
  68. 'passback_params' => http_build_query($this->passback_params),
  69. );
  70. $commonConfigs = array(
  71. //公共参数
  72. 'app_id' => $this->appId,
  73. 'method' => 'alipay.trade.app.pay', //接口名称
  74. 'format' => 'JSON',
  75. 'charset' => $this->charset,
  76. 'sign_type' => 'RSA2',
  77. 'timestamp' => date('Y-m-d H:i:s'),
  78. 'version' => '1.0',
  79. 'notify_url' => $this->notifyUrl,
  80. 'biz_content' => json_encode($requestConfigs),
  81. );
  82. $commonConfigs["sign"] = $this->generateSign($commonConfigs, $commonConfigs['sign_type']);
  83. $result = $this->buildOrderStr($commonConfigs);
  84. return $result;
  85. }
  86. public function generateSign($params, $signType = "RSA")
  87. {
  88. return $this->sign($this->getSignContent($params), $signType);
  89. }
  90. protected function sign($data, $signType = "RSA")
  91. {
  92. $priKey = $this->rsaPrivateKey;
  93. $res = "-----BEGIN RSA PRIVATE KEY-----\n" .
  94. wordwrap($priKey, 64, "\n", true) .
  95. "\n-----END RSA PRIVATE KEY-----";
  96. ($res) or die('您使用的私钥格式错误,请检查RSA私钥配置');
  97. if ("RSA2" == $signType) {
  98. openssl_sign($data, $sign, $res, version_compare(PHP_VERSION, '5.4.0', '<') ? SHA256 : OPENSSL_ALGO_SHA256); //OPENSSL_ALGO_SHA256是php5.4.8以上版本才支持
  99. } else {
  100. openssl_sign($data, $sign, $res);
  101. }
  102. $sign = base64_encode($sign);
  103. return $sign;
  104. }
  105. /**
  106. * 校验$value是否非空
  107. * if not set ,return true;
  108. * if is null , return true;
  109. **/
  110. protected function checkEmpty($value)
  111. {
  112. if (!isset($value))
  113. return true;
  114. if ($value === null)
  115. return true;
  116. if (trim($value) === "")
  117. return true;
  118. return false;
  119. }
  120. public function getSignContent($params)
  121. {
  122. ksort($params);
  123. $stringToBeSigned = "";
  124. $i = 0;
  125. foreach ($params as $k => $v) {
  126. if (false === $this->checkEmpty($v) && "@" != substr($v, 0, 1)) {
  127. // 转换成目标字符集
  128. $v = $this->characet($v, $this->charset);
  129. if ($i == 0) {
  130. $stringToBeSigned .= "$k" . "=" . "$v";
  131. } else {
  132. $stringToBeSigned .= "&" . "$k" . "=" . "$v";
  133. }
  134. $i++;
  135. }
  136. }
  137. unset ($k, $v);
  138. return $stringToBeSigned;
  139. }
  140. /**
  141. * 转换字符集编码
  142. * @param $data
  143. * @param $targetCharset
  144. * @return string
  145. */
  146. function characet($data, $targetCharset)
  147. {
  148. if (!empty($data)) {
  149. $fileType = $this->charset;
  150. if (strcasecmp($fileType, $targetCharset) != 0) {
  151. $data = mb_convert_encoding($data, $targetCharset, $fileType);
  152. //$data = iconv($fileType, $targetCharset.'//IGNORE', $data);
  153. }
  154. }
  155. return $data;
  156. }
  157. public function buildOrderStr($data)
  158. {
  159. return http_build_query($data);
  160. }
  161. /**
  162. * 验证签名
  163. **/
  164. public function rsaCheck($params)
  165. {
  166. $sign = $params['sign'];
  167. $signType = $params['sign_type'];
  168. unset($params['sign_type']);
  169. unset($params['sign']);
  170. return $this->verify($this->getSignContent($params), $sign, $signType);
  171. }
  172. function verify($data, $sign, $signType = 'RSA')
  173. {
  174. $pubKey = $this->alipayPublicKey;
  175. $res = "-----BEGIN PUBLIC KEY-----\n" .
  176. wordwrap($pubKey, 64, "\n", true) .
  177. "\n-----END PUBLIC KEY-----";
  178. ($res) or die('支付宝RSA公钥错误。请检查公钥文件格式是否正确');
  179. //调用openssl内置方法验签,返回bool值
  180. if ("RSA2" == $signType) {
  181. $result = (bool)openssl_verify($data, base64_decode($sign), $res, version_compare(PHP_VERSION, '5.4.0', '<') ? SHA256 : OPENSSL_ALGO_SHA256);
  182. } else {
  183. $result = (bool)openssl_verify($data, base64_decode($sign), $res);
  184. }
  185. // if(!$this->checkEmpty($this->alipayPublicKey)) {
  186. // //释放资源
  187. // openssl_free_key($res);
  188. // }
  189. return $result;
  190. }
  191. }
  192. // 是否支付宝客户端
  193. function isInAlipayClient()
  194. {
  195. if (strpos($_SERVER['HTTP_USER_AGENT'], 'AlipayClient') !== false) {
  196. return true;
  197. }
  198. return false;
  199. }
  200. function getCurrentUrl()
  201. {
  202. $scheme = $_SERVER['HTTPS'] == 'on' ? 'https://' : 'http://';
  203. $uri = $_SERVER['PHP_SELF'] . $_SERVER['QUERY_STRING'];
  204. if ($_SERVER['REQUEST_URI']) $uri = $_SERVER['REQUEST_URI'];
  205. $baseUrl = urlencode($scheme . $_SERVER['HTTP_HOST'] . $uri);
  206. return $baseUrl;
  207. }