PaypalController.php 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364
  1. <?php
  2. /**
  3. * Created by PhpStorm.
  4. * User: blank
  5. * Date: 2020/4/22
  6. * Time: 10:23
  7. */
  8. namespace app\payment\controllers;
  9. use app\common\helpers\Url;
  10. use app\common\models\AccountWechats;
  11. use app\common\services\PayFactory;
  12. use app\common\services\utils\EncryptUtil;
  13. use app\payment\PaymentController;
  14. use PayPal\Api\Payment;
  15. use PayPal\Api\PaymentExecution;
  16. use PayPal\Auth\OAuthTokenCredential;
  17. use PayPal\Rest\ApiContext;
  18. use Yunshop\PayPal\models\PayPalLog;
  19. use Yunshop\PayPal\models\PayPalOrder;
  20. class PaypalController extends PaymentController
  21. {
  22. /** 正式验证地址 URL */
  23. const VERIFY_URI = 'https://ipnpb.paypal.com/cgi-bin/webscr';
  24. /** 沙箱验证地址 URL */
  25. const SANDBOX_VERIFY_URI = 'https://ipnpb.sandbox.paypal.com/cgi-bin/webscr';
  26. /** 验证成功 值*/
  27. const VALID = 'VERIFIED';
  28. /** 验证失败 值 */
  29. const INVALID = 'INVALID';
  30. public $parameter;
  31. //支付回调
  32. public function payNotify()
  33. {
  34. $parameter = $this->getIpnData();
  35. $this->setI($parameter['custom']);
  36. $bool = $this->verifyIPN();
  37. if ($bool) {
  38. $payOrder = PayPalOrder::uniacid()->where('transaction_id', $parameter['txn_id'])->first();
  39. if (empty($payOrder)) {
  40. \Log::debug('-----------PayPal记录为空------------>>');
  41. exit('failure');
  42. }
  43. if ($payOrder->status == PayPalOrder::STATUS_SUCCESS) {
  44. \Log::debug('-----------PayPal已支付成功------------>>', $payOrder->toArray());
  45. exit('success');
  46. }
  47. $data = [
  48. 'total_fee' => $parameter['mc_gross'],
  49. 'out_trade_no' => $parameter['invoice'],
  50. 'trade_no' => $parameter['txn_id'],
  51. 'unit' => 'yuan',
  52. 'pay_type' => 'PayPal支付',
  53. 'pay_type_id' => PayFactory::PAY_PAL,
  54. ];
  55. \Log::debug('-----------PayPal支付成功------------>>', $data);
  56. $payOrder->status = PayPalOrder::STATUS_SUCCESS;
  57. $payOrder->save();
  58. $this->payResutl($data);
  59. exit('success');
  60. }
  61. \Log::debug('------------PayPal支付回调失败------------------>>');
  62. exit('failure');
  63. }
  64. //退款回调
  65. public function refundNotify()
  66. {
  67. }
  68. public function setI($i)
  69. {
  70. \Setting::$uniqueAccountId = \YunShop::app()->uniacid = $i;
  71. AccountWechats::setConfig(AccountWechats::getAccountByUniacid(\YunShop::app()->uniacid));
  72. }
  73. //同步步回调 - 用于确认用户取消支付
  74. public function cancelPay()
  75. {
  76. \Log::debug('---------paypal支付取消-------------', $_GET);
  77. redirect(Url::absoluteApp('member/', ['i' => \YunShop::app()->uniacid]))->send();
  78. }
  79. public function getApiContext()
  80. {
  81. $set = \Setting::get('plugin.pay_pal');
  82. $apiContext = new ApiContext(new OAuthTokenCredential($set['client_id'], $set['client_secret']));
  83. return $apiContext;
  84. }
  85. //同步步回调 - 用于确认用户是否付款
  86. public function confirmPay()
  87. {
  88. if (empty($i) && !isset($_GET['paymentId']) && !isset($_GET['PayerID'])) {
  89. \Log::debug('-----PayPal支付确认失败-----', $_GET);
  90. redirect(Url::absoluteApp('member/payErr', ['i' => \YunShop::app()->uniacid]))->send();exit();
  91. }
  92. $i = intval($_GET['i']);
  93. $this->setI($i);
  94. $paymentId = trim($_GET['paymentId']);
  95. $PayerID = trim($_GET['PayerID']);
  96. $salt_sign = trim($_GET['s']);
  97. $payPalLog = PayPalLog::uniacid()->where('payment_id',$paymentId)->first();
  98. if (is_null($payPalLog)) {
  99. \Log::debug('------PayPal支付确认支付记录不存在---------', ['payment_id'=> $paymentId]);
  100. redirect(Url::absoluteApp('member/payErr', ['i' => \YunShop::app()->uniacid]))->send();exit();
  101. //exit('支付记录不存在');
  102. }
  103. $verify_salt = EncryptUtil::decryptECB($salt_sign,$payPalLog['aes_key']);
  104. if ($verify_salt['code'] === false && $verify_salt['data'] != $payPalLog['aes_key']) {
  105. \Log::debug('------PayPal支付确认盐验证失败---------');
  106. redirect(Url::absoluteApp('member/payErr', ['i' => \YunShop::app()->uniacid]))->send();exit();
  107. //exit('验证失败');
  108. }
  109. if ($payPalLog->status == PayPalLog::STATUS_SUCCESS) {
  110. //已支付订单
  111. \Log::debug('------PayPal支付确认---订单已支付---------',$_GET);
  112. redirect(Url::absoluteApp('member/payErr', ['i' => \YunShop::app()->uniacid]))->send();exit();
  113. //exit('订单已支付');
  114. }
  115. $apiContext = $this->getApiContext();
  116. $payment = Payment::get($paymentId, $apiContext);
  117. $execute = new PaymentExecution();
  118. $execute->setPayerId($PayerID);
  119. try {
  120. $payment->execute($execute, $apiContext);
  121. $paymentArray = $payment->toArray();
  122. \Log::debug('------PayPal confirm--------', $payment->toArray());
  123. //dump($paymentArray);
  124. //更新支付记录
  125. $this->updateLog($payPalLog, ['state' => $paymentArray['state'], 'payer_id'=>$PayerID, 'status'=> PayPalLog::STATUS_SUCCESS]);
  126. //保存支付信息,付款成功之后会有sale_id需要保存起来 退款需要
  127. $this->savePayPalOrder($paymentArray);
  128. //echo '支付成功,支付ID【' . $paymentId . '】,支付人ID【' . $PayerID . '】';die;
  129. redirect(Url::absoluteApp('member/payYes', ['i' => \YunShop::app()->uniacid]))->send();exit();
  130. } catch (\Exception $e) {
  131. $this->updateLog($payPalLog, ['state' => 'failure', 'payer_id'=>$PayerID, 'status'=> PayPalLog::STATUS_FAILED]);
  132. //echo '支付失败,支付ID【' . $paymentId . '】,支付人ID【' . $PayerID . '】';dd($e);
  133. redirect(Url::absoluteApp('member/payErr', ['i' => \YunShop::app()->uniacid]))->send();exit();
  134. }
  135. }
  136. public function payErr()
  137. {
  138. redirect(Url::absoluteApp('member/payErr', ['i' => \YunShop::app()->uniacid]))->send();exit();
  139. }
  140. public function updateLog(PayPalLog $payPalLog, $data)
  141. {
  142. $payPalLog->fill($data);
  143. $payPalLog->save();
  144. return $payPalLog;
  145. }
  146. public function savePayPalOrder($paymentArray)
  147. {
  148. $data = [
  149. 'uniacid' => \YunShop::app()->uniacid,
  150. 'pay_sn' => $paymentArray['transactions'][0]['invoice_number'],
  151. 'currency' => $paymentArray['transactions'][0]['amount']['currency'],
  152. 'payment_id' => $paymentArray['id'],
  153. 'intent' => $paymentArray['intent'],
  154. 'transaction_id' => $paymentArray['transactions'][0]['related_resources'][0][$paymentArray['intent']]['id'],
  155. ];
  156. if (is_null(PayPalOrder::uniacid()->where('transaction_id', $data['transaction_id'])->first())) {
  157. PayPalOrder::create($data);
  158. }
  159. }
  160. public function getIpnData()
  161. {
  162. $json = file_get_contents('php://input');
  163. //file_put_contents(storage_path("logs/paypal.log"), $json);
  164. //获取字符集
  165. $result1 = strstr($json, 'charset');
  166. $result2 = substr($result1,0,strpos($result1, '&'));
  167. $charset = substr($result2,strlen('charset='));
  168. $raw_post_array = explode('&', $json);
  169. $myPost = array();
  170. foreach ($raw_post_array as $keyval) {
  171. $keyval = explode('=', $keyval);
  172. if (count($keyval) == 2) {
  173. if (empty($charset) || strtolower($charset) == 'utf-8') {
  174. $value = rawurldecode($keyval[1]);
  175. } else {
  176. $value = iconv($charset, 'UTF-8', rawurldecode($keyval[1])); //字符集转换为utf-8
  177. }
  178. $myPost[$keyval[0]] =$value;
  179. }
  180. }
  181. if (empty($myPost)) {
  182. \Log::debug('<<-------------PayPal IPN data is null----------',$json);
  183. }
  184. \Log::debug('<<------PayPal IPN-------------', $myPost);
  185. $this->parameter = $myPost;
  186. return $this->parameter;
  187. }
  188. protected function getAllParameter()
  189. {
  190. return $this->parameter;
  191. }
  192. public function getUrl($sandbox = true)
  193. {
  194. $app = \Setting::get('plugin.pay_pal.app');
  195. if ($app == 'live') {
  196. return self::VERIFY_URI;
  197. }
  198. return self::SANDBOX_VERIFY_URI;
  199. // if ($sandbox) {
  200. // return self::SANDBOX_VERIFY_URI;
  201. // }
  202. // return self::VERIFY_URI;
  203. }
  204. /**
  205. * @return bool
  206. */
  207. public function verifyIPN()
  208. {
  209. $str = file_get_contents('php://input');
  210. $req = 'cmd=_notify-validate&'.$str;
  211. // Build the body of the verification post request, adding the _notify-validate command.
  212. // $req = 'cmd=_notify-validate';
  213. // $myPost = $this->getAllParameter()?:$this->getIpnData();
  214. // $get_magic_quotes_exists = false;
  215. // if (function_exists('get_magic_quotes_gpc')) {
  216. // $get_magic_quotes_exists = true;
  217. // }
  218. // foreach ($myPost as $key => $value) {
  219. //
  220. //
  221. // if ($get_magic_quotes_exists == true && get_magic_quotes_gpc() == 1) {
  222. // $value = rawurlencode(stripslashes($value));
  223. // } else {
  224. // $value = rawurlencode($value);
  225. // }
  226. // $req .= strlen($req) == 0 ? "" : "&";
  227. // $req .= "$key=$value";
  228. // }
  229. \Log::debug('-------------validate--req-----------------------',$req);
  230. // Post the data back to PayPal, using curl. Throw exceptions if errors occur.
  231. $ch = curl_init($this->getUrl());
  232. curl_setopt($ch, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1);
  233. curl_setopt($ch, CURLOPT_POST, 1);
  234. curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
  235. curl_setopt($ch, CURLOPT_POSTFIELDS, $req);
  236. curl_setopt($ch, CURLOPT_SSLVERSION, 6);
  237. curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 1);
  238. curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);
  239. // This is often required if the server is missing a global cert bundle, or is using an outdated one.
  240. // if ($this->use_local_certs) {
  241. // curl_setopt($ch, CURLOPT_CAINFO, __DIR__ . "/cert/cacert.pem");
  242. // }
  243. curl_setopt($ch, CURLOPT_FORBID_REUSE, 1);
  244. curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 30);
  245. curl_setopt($ch, CURLOPT_HTTPHEADER, array(
  246. 'User-Agent: PHP-IPN-VerificationScript',
  247. 'Connection: Close',
  248. ));
  249. $res = curl_exec($ch);
  250. \Log::debug('----PayPal--verifies-----', $res);
  251. if ( !($res)) {
  252. $errno = curl_errno($ch);
  253. $errstr = curl_error($ch);
  254. curl_close($ch);
  255. \Log::debug('---PayPal verifies error------',['error'=> $errno, 'msg' => $errstr]);
  256. //throw new \Exception("cURL error: [$errno] $errstr");
  257. }
  258. $info = curl_getinfo($ch);
  259. $http_code = $info['http_code'];
  260. if ($http_code != 200) {
  261. \Log::debug('---PayPal responded with http code ------',$http_code);
  262. //throw new \Exception("PayPal responded with http code $http_code");
  263. }
  264. curl_close($ch);
  265. // Check if PayPal verifies the IPN data, and if so, return true.
  266. if ($res == self::VALID) {
  267. return true;
  268. } else {
  269. return false;
  270. }
  271. }
  272. }