AlipayService.php 7.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202
  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 array
  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'=>'2h', //该笔订单允许的最晚付款时间,逾期将关闭交易。取值范围: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. return $this->sign($this->getSignContent($params), $signType);
  88. }
  89. protected function sign($data, $signType = "RSA") {
  90. $priKey=$this->rsaPrivateKey;
  91. $res = "-----BEGIN RSA PRIVATE KEY-----\n" .
  92. wordwrap($priKey, 64, "\n", true) .
  93. "\n-----END RSA PRIVATE KEY-----";
  94. ($res) or die('您使用的私钥格式错误,请检查RSA私钥配置');
  95. if ("RSA2" == $signType) {
  96. openssl_sign($data, $sign, $res, version_compare(PHP_VERSION,'5.4.0', '<') ? SHA256 : OPENSSL_ALGO_SHA256); //OPENSSL_ALGO_SHA256是php5.4.8以上版本才支持
  97. } else {
  98. openssl_sign($data, $sign, $res);
  99. }
  100. $sign = base64_encode($sign);
  101. return $sign;
  102. }
  103. /**
  104. * 校验$value是否非空
  105. * if not set ,return true;
  106. * if is null , return true;
  107. **/
  108. protected function checkEmpty($value) {
  109. if (!isset($value))
  110. return true;
  111. if ($value === null)
  112. return true;
  113. if (trim($value) === "")
  114. return true;
  115. return false;
  116. }
  117. public function getSignContent($params) {
  118. ksort($params);
  119. $stringToBeSigned = "";
  120. $i = 0;
  121. foreach ($params as $k => $v) {
  122. if (false === $this->checkEmpty($v) && "@" != substr($v, 0, 1)) {
  123. // 转换成目标字符集
  124. $v = $this->characet($v, $this->charset);
  125. if ($i == 0) {
  126. $stringToBeSigned .= "$k" . "=" . "$v";
  127. } else {
  128. $stringToBeSigned .= "&" . "$k" . "=" . "$v";
  129. }
  130. $i++;
  131. }
  132. }
  133. unset ($k, $v);
  134. return $stringToBeSigned;
  135. }
  136. /**
  137. * 转换字符集编码
  138. * @param $data
  139. * @param $targetCharset
  140. * @return string
  141. */
  142. function characet($data, $targetCharset) {
  143. if (!empty($data)) {
  144. $fileType = $this->charset;
  145. if (strcasecmp($fileType, $targetCharset) != 0) {
  146. $data = mb_convert_encoding($data, $targetCharset, $fileType);
  147. //$data = iconv($fileType, $targetCharset.'//IGNORE', $data);
  148. }
  149. }
  150. return $data;
  151. }
  152. public function buildOrderStr($data)
  153. {
  154. return http_build_query($data);
  155. }
  156. /**
  157. * 验证签名
  158. **/
  159. public function rsaCheck($params) {
  160. $sign = $params['sign'];
  161. $signType = $params['sign_type'];
  162. unset($params['sign_type']);
  163. unset($params['sign']);
  164. return $this->verify($this->getSignContent($params), $sign, $signType);
  165. }
  166. function verify($data, $sign, $signType = 'RSA') {
  167. $pubKey= $this->alipayPublicKey;
  168. $res = "-----BEGIN PUBLIC KEY-----\n" .
  169. wordwrap($pubKey, 64, "\n", true) .
  170. "\n-----END PUBLIC KEY-----";
  171. ($res) or die('支付宝RSA公钥错误。请检查公钥文件格式是否正确');
  172. //调用openssl内置方法验签,返回bool值
  173. if ("RSA2" == $signType) {
  174. $result = (bool)openssl_verify($data, base64_decode($sign), $res, version_compare(PHP_VERSION,'5.4.0', '<') ? SHA256 : OPENSSL_ALGO_SHA256);
  175. } else {
  176. $result = (bool)openssl_verify($data, base64_decode($sign), $res);
  177. }
  178. // if(!$this->checkEmpty($this->alipayPublicKey)) {
  179. // //释放资源
  180. // openssl_free_key($res);
  181. // }
  182. return $result;
  183. }
  184. }
  185. // 是否支付宝客户端
  186. function isInAlipayClient() {
  187. if( strpos($_SERVER['HTTP_USER_AGENT'], 'AlipayClient') !== false ) {
  188. return true;
  189. }
  190. return false;
  191. }
  192. function getCurrentUrl()
  193. {
  194. $scheme = $_SERVER['HTTPS']=='on' ? 'https://' : 'http://';
  195. $uri = $_SERVER['PHP_SELF'].$_SERVER['QUERY_STRING'];
  196. if($_SERVER['REQUEST_URI']) $uri = $_SERVER['REQUEST_URI'];
  197. $baseUrl = urlencode($scheme.$_SERVER['HTTP_HOST'].$uri);
  198. return $baseUrl;
  199. }