Alipay.php 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429
  1. <?php
  2. /*
  3. * FecShop file.
  4. *
  5. * @link http://www.fecshop.com/
  6. * @copyright Copyright (c) 2016 FecShop Software LLC
  7. * @license http://www.fecshop.com/license/
  8. */
  9. namespace fecshop\services\payment;
  10. //use fecshop\models\mysqldb\IpnMessage;
  11. use fecshop\services\Service;
  12. use Yii;
  13. /**
  14. * Payment Paypal services.
  15. * @author Terry Zhao <2358269014@qq.com>
  16. * @since 1.0
  17. */
  18. class Alipay extends Service
  19. {
  20. public $gatewayUrl;
  21. // 商家 appid
  22. public $appId;
  23. // 商家uid
  24. public $sellerId;
  25. // 应用私钥
  26. public $rsaPrivateKey;
  27. // 支付宝公钥
  28. public $alipayrsaPublicKey;
  29. public $format;
  30. public $charset;
  31. public $signType;
  32. public $devide;
  33. public $apiVersion = '1.0'; //'1.0';
  34. //protected $_returnUrl;
  35. //protected $_notifyUrl;
  36. protected $_AopClient;
  37. protected $_alipayRequest;
  38. protected $_productCode;
  39. protected $_order;
  40. //交易创建,等待买家付款
  41. const WAIT_BUYER_PAY = 'WAIT_BUYER_PAY';
  42. //未付款交易超时关闭,或支付完成后全额退款
  43. const TRADE_CLOSED = 'TRADE_CLOSED';
  44. //交易支付成功
  45. const TRADE_SUCCESS = 'TRADE_SUCCESS';
  46. //交易结束,不可退款
  47. const TRADE_FINISHED = 'TRADE_FINISHED';
  48. protected $_ipnMessageModelName = '\fecshop\models\mysqldb\IpnMessage';
  49. protected $_ipnMessageModel;
  50. // 允许更改的订单状态,不存在这里面的订单状态不允许修改
  51. protected $_allowChangOrderStatus;
  52. protected $_initAlipayLib = 0;
  53. /**
  54. * 支付宝:SDK工作目录
  55. * 存放日志,AOP缓存数据
  56. */
  57. public $alipay_aop_sdk_work_dir = '/tmp/';
  58. /**
  59. * 是否处于开发模式
  60. * 在你自己电脑上开发程序的时候千万不要设为false,以免缓存造成你的代码修改了不生效
  61. * 部署到生产环境正式运营后,如果性能压力大,可以把此常量设定为false,能提高运行速度(对应的代价就是你下次升级程序时要清一下缓存)
  62. */
  63. public $alipay_aop_sdk_dev_mode = true;
  64. public function init()
  65. {
  66. parent::init();
  67. list($this->_ipnMessageModelName, $this->_ipnMessageModel) = \Yii::mapGet($this->_ipnMessageModelName);
  68. $this->_allowChangOrderStatus = [
  69. Yii::$service->order->payment_status_pending,
  70. Yii::$service->order->payment_status_processing,
  71. ];
  72. // init by store config
  73. $this->appId = Yii::$app->store->get('payment_alipay', 'app_id');
  74. $this->sellerId = Yii::$app->store->get('payment_alipay', 'seller_id');
  75. $this->rsaPrivateKey = Yii::$app->store->get('payment_alipay', 'rsa_private_key');
  76. $this->alipayrsaPublicKey = Yii::$app->store->get('payment_alipay', 'rsa_public_key');
  77. if ($alipay_aop_sdk_work_dir = Yii::$app->store->get('payment_alipay', 'alipay_aop_sdk_work_dir')) {
  78. $this->alipay_aop_sdk_work_dir = $alipay_aop_sdk_work_dir;
  79. }
  80. $this->alipay_aop_sdk_dev_mode = Yii::$app->store->get('payment_alipay', 'alipay_aop_sdk_dev_mode') == 1 ? true : false ;
  81. // 沙盒还是正式环境
  82. $env = Yii::$app->store->get('payment_alipay', 'alipay_env');
  83. if ($env == Yii::$service->payment->env_sanbox) {
  84. $this->gatewayUrl = 'https://openapi.alipaydev.com/gateway.do';
  85. } else {
  86. $this->gatewayUrl = 'https://openapi.alipay.com/gateway.do';
  87. }
  88. }
  89. /**
  90. * 初始化 $this->_AopClient
  91. */
  92. protected function initParam()
  93. {
  94. /**
  95. * 引入 支付宝支付的SDK文件。
  96. */
  97. if (!$this->_initAlipayLib) {
  98. define("AOP_SDK_WORK_DIR", $this->alipay_aop_sdk_work_dir);
  99. define("AOP_SDK_DEV_MODE", $this->alipay_aop_sdk_dev_mode);
  100. $AopSdkFile = Yii::getAlias('@fecshop/lib/alipay/AopSdk.php');
  101. require($AopSdkFile);
  102. $this->_initAlipayLib = 1;
  103. }
  104. if (!$this->_AopClient) {
  105. $this->_AopClient = new \AopClient;
  106. $this->_AopClient->gatewayUrl = $this->gatewayUrl;
  107. $this->_AopClient->appId = $this->appId;
  108. $this->_AopClient->rsaPrivateKey = $this->rsaPrivateKey;
  109. $this->_AopClient->apiVersion = $this->apiVersion; //'1.0';
  110. $this->_AopClient->format = $this->format;
  111. $this->_AopClient->charset = $this->charset;
  112. $this->_AopClient->signType = $this->signType;
  113. $this->_AopClient->alipayrsaPublicKey= $this->alipayrsaPublicKey;
  114. }
  115. }
  116. /**
  117. * @param $out_trade_no | String ,[支付宝传递过来的]fecshop站内订单号
  118. * @param $total_amount | String ,[支付宝传递过来的]fecshop站内订单金额(CNY)
  119. * @param $seller_id | String ,[支付宝传递过来的]商家UID
  120. * @param $auth_app_id | String ,[支付宝传递过来的]商家appId
  121. * 验证订单数据是否正确,需要满足下面的条件:
  122. * 1、商户需要验证该通知数据中的out_trade_no是否为商户系统中创建的订单号
  123. * 2、判断total_amount是否确实为该订单的实际金额(即商户订单创建时的金额)
  124. * 3、校验通知中的seller_id(或者seller_email) 是否为out_trade_no这笔单据的对应的操作方(有的时候,一个商户可能有多个seller_id/seller_email)
  125. * 4、验证app_id是否为该商户本身。
  126. * 上述1、2、3、4有任何一个验证不通过,则表明本次通知是异常通知,
  127. * 务必忽略。在上述验证通过后商户必须根据支付宝不同类型的业务通知,
  128. * 正确的进行不同的业务处理,并且过滤重复的通知结果数据。
  129. * 在支付宝的业务通知中,只有交易通知状态为TRADE_SUCCESS或TRADE_FINISHED时,
  130. * 支付宝才会认定为买家付款成功。
  131. */
  132. protected function validateReviewOrder($out_trade_no, $total_amount, $seller_id, $auth_app_id)
  133. {
  134. if (!$this->_order) {
  135. $this->_order = Yii::$service->order->getByIncrementId($out_trade_no);
  136. Yii::$service->payment->setPaymentMethod($this->_order['payment_method']);
  137. }
  138. if (!$this->_order) {
  139. Yii::$service->helper->errors->add('order increment id:{out_trade_no} is not exist.', ['out_trade_no' => $out_trade_no]);
  140. return false;
  141. }
  142. //$base_grand_total = $this->_order['base_grand_total'];
  143. //$order_total_amount = Yii::$service->page->currency->getCurrencyPrice($base_grand_total,'CNY');
  144. $order_total_amount = $this->_order['grand_total'];
  145. if ($order_total_amount != $total_amount) {
  146. Yii::$service->helper->errors->add('order increment id:{out_trade_no} , total_amount({total_amount}) is not equal to order_total_amount({order_total_amount})', ['out_trade_no'=>$out_trade_no , 'total_amount'=>$total_amount , 'order_total_amount'=>$order_total_amount ]);
  147. return false;
  148. }
  149. if (!$this->sellerId) {
  150. Yii::$service->helper->errors->add('you must config sellerId in alipay payment config file');
  151. return false;
  152. }
  153. if ($seller_id != $this->sellerId) {
  154. Yii::$service->helper->errors->add('request sellerId({seller_id}) is not equle to config sellerId({this_seller_id})', ['seller_id'=>$seller_id , 'this_seller_id'=>$this->sellerId ]);
  155. return false;
  156. }
  157. if ($auth_app_id != $this->appId) {
  158. Yii::$service->helper->errors->add('request auth_app_id({auth_app_id}) is not equle to config appId({app_id})', ['auth_app_id'=>$auth_app_id, 'app_id'=>$this->appId ]);
  159. return false;
  160. }
  161. return true;
  162. }
  163. /**
  164. * 支付宝 支付成功后,返回网站,调用该函数进行支付宝订单支付状态查询
  165. * 如果支付成功,则修改订单状态为支付成功状态。
  166. */
  167. protected function actionReview()
  168. {
  169. $this->initParam();
  170. $trade_no = Yii::$app->request->get('trade_no');
  171. $out_trade_no = Yii::$app->request->get('out_trade_no');
  172. $total_amount = Yii::$app->request->get('total_amount');
  173. $seller_id = Yii::$app->request->get('seller_id');
  174. $auth_app_id = Yii::$app->request->get('auth_app_id');
  175. //验证订单的合法性
  176. if (!$this->validateReviewOrder($out_trade_no, $total_amount, $seller_id, $auth_app_id)) {
  177. return false;
  178. }
  179. $this->_AopClient->postCharset = $this->charset;
  180. $this->_alipayRequest = new \AlipayTradeQueryRequest();
  181. $bizContent = json_encode([
  182. 'out_trade_no' => $out_trade_no,
  183. 'trade_no' => $trade_no,
  184. ]);
  185. //echo $bizContent;
  186. $this->_alipayRequest->setBizContent($bizContent);
  187. $result = $this->_AopClient->execute($this->_alipayRequest);
  188. $responseNode = str_replace(".", "_", $this->_alipayRequest->getApiMethodName()) . "_response";
  189. $resultCode = $result->$responseNode->code;
  190. if (!empty($resultCode)&&$resultCode == 10000) {
  191. $this->paymentSuccess($out_trade_no, $trade_no);
  192. // 清空购物车
  193. Yii::$service->cart->clearCartProductAndCoupon();
  194. return true;
  195. } else {
  196. Yii::$service->helper->errors->add('Alipay payment fail,resultCode: {result_code}', ['result_code' => $resultCode]);
  197. return false;
  198. }
  199. }
  200. /**
  201. * 支付宝的消息接收IPN,执行的函数,接收的消息用来更改订单状态。
  202. * 您开启log后,可以在@app/runtime/fecshop_logs
  203. * 文件夹下执行:tail -f fecshop_debug.log , 来查看log输出。
  204. */
  205. public function receiveIpn()
  206. {
  207. Yii::info('alipay service receiveIpn():begin init param', 'fecshop_debug');
  208. $this->initParam();
  209. Yii::info('alipay service receiveIpn():begin rsaCheck', 'fecshop_debug');
  210. // 验签
  211. $checkV2Status = $this->_AopClient->rsaCheckV1($_POST, '', $this->signType);
  212. Yii::info('alipay service receiveIpn():rsacheck end', 'fecshop_debug');
  213. if ($checkV2Status) {
  214. Yii::info('alipay service receiveIpn():rsacheck success', 'fecshop_debug');
  215. $trade_no = Yii::$app->request->post('trade_no');
  216. $out_trade_no = Yii::$app->request->post('out_trade_no');
  217. $total_amount = Yii::$app->request->post('total_amount');
  218. $seller_id = Yii::$app->request->post('seller_id');
  219. $auth_app_id = Yii::$app->request->post('app_id');
  220. $trade_status = Yii::$app->request->post('trade_status');
  221. Yii::info('alipay service receiveIpn(): [ trade_no: ]'.$trade_no, 'fecshop_debug');
  222. Yii::info('alipay service receiveIpn(): [ out_trade_no: ]'.$out_trade_no, 'fecshop_debug');
  223. Yii::info('alipay service receiveIpn(): [ total_amount: ]'.$total_amount, 'fecshop_debug');
  224. Yii::info('alipay service receiveIpn(): [ seller_id: ]'.$seller_id, 'fecshop_debug');
  225. Yii::info('alipay service receiveIpn(): [ auth_app_id: ]'.$auth_app_id, 'fecshop_debug');
  226. Yii::info('alipay service receiveIpn(): [ trade_status: ]'.$trade_status, 'fecshop_debug');
  227. //验证订单的合法性
  228. if (!$this->validateReviewOrder($out_trade_no, $total_amount, $seller_id, $auth_app_id)) {
  229. Yii::info('alipay service receiveIpn(): validate order fail', 'fecshop_debug');
  230. return false;
  231. }
  232. Yii::info('alipay service receiveIpn():validate order success', 'fecshop_debug');
  233. if (self::TRADE_SUCCESS == $trade_status) {
  234. Yii::info('alipay service receiveIpn():alipay trade success ', 'fecshop_debug');
  235. if ($this->paymentSuccess($out_trade_no, $trade_no)) {
  236. Yii::info('alipay service receiveIpn():update order status success', 'fecshop_debug');
  237. return true;
  238. }
  239. }
  240. } else {
  241. return false;
  242. }
  243. }
  244. /**
  245. * @param $increment_id | String 订单号
  246. * @param $sendEmail | boolean 是否发送邮件
  247. * 订单支付成功后,需要更改订单支付状态等一系列的处理。
  248. */
  249. protected function paymentSuccess($increment_id, $trade_no, $sendEmail = true)
  250. {
  251. Yii::$service->store->currentLangCode = 'zh';
  252. if (!$this->_order) {
  253. $this->_order = Yii::$service->order->getByIncrementId($increment_id);
  254. Yii::$service->payment->setPaymentMethod($this->_order['payment_method']);
  255. }
  256. // 【优化后的代码 ##】
  257. $orderstatus = Yii::$service->order->payment_status_confirmed;
  258. $updateArr['order_status'] = $orderstatus;
  259. $updateArr['txn_id'] = $trade_no; // 支付宝的交易号
  260. $updateColumn = $this->_order->updateAll(
  261. $updateArr,
  262. [
  263. 'and',
  264. ['order_id' => $this->_order['order_id']],
  265. ['in','order_status',$this->_allowChangOrderStatus]
  266. ]
  267. );
  268. if (!empty($updateColumn)) {
  269. // 发送邮件,以及其他的一些操作(订单支付成功后的操作)
  270. Yii::$service->order->orderPaymentCompleteEvent($this->_order['increment_id']);
  271. }
  272. // 【优化后的代码 ##】
  273. /* 注释掉的原来代码,上面进行了优化,保证更改只有一次,这样发邮件也就只有一次了
  274. // 如果订单状态已经是processing,那么,不需要更改订单状态了。
  275. if ($this->_order['order_status'] == Yii::$service->order->payment_status_confirmed){
  276. return true;
  277. }
  278. $order = $this->_order;
  279. if (isset($order['increment_id']) && $order['increment_id']) {
  280. // 如果支付成功,则更改订单状态为支付成功
  281. $order->order_status = Yii::$service->order->payment_status_confirmed;
  282. $order->txn_id = $trade_no; // 支付宝的交易号
  283. // 更新订单信息
  284. $order->save();
  285. Yii::$service->order->orderPaymentCompleteEvent($order['increment_id']);
  286. // 上面的函数已经执行下面的代码,因此注释掉。
  287. // 得到当前的订单信息
  288. //$orderInfo = Yii::$service->order->getOrderInfoByIncrementId($order['increment_id']);
  289. // 发送新订单邮件
  290. //Yii::$service->email->order->sendCreateEmail($orderInfo);
  291. return true;
  292. }
  293. */
  294. return true;
  295. }
  296. /**
  297. * 根据订单,将内容提交给支付宝。跳转到支付宝支付页面。
  298. * 在下单页面点击place order按钮,跳转到支付宝的时候,执行该函数。
  299. */
  300. public function start($returnUrl = '', $type="POST")
  301. {
  302. // 初始化参数
  303. $this->initParam();
  304. // 根据wap 还是pc ,进行参数初始化
  305. if ($this->devide == 'wap') {
  306. $this->_alipayRequest = new \AlipayTradeWapPayRequest();
  307. $this->_productCode = 'QUICK_WAP_WAY';
  308. } elseif ($this->devide == 'pc') {
  309. $this->_productCode = 'FAST_INSTANT_TRADE_PAY';
  310. $this->_alipayRequest = new \AlipayTradePagePayRequest();
  311. } else {
  312. Yii::$service->helper->errors->add('you must config param [devide] in payment alipay service');
  313. return;
  314. }
  315. // 根据订单得到json格式的支付宝支付参数。
  316. $bizContent = $this->getStartBizContentAndSetPaymentMethod();
  317. if (!$bizContent) {
  318. Yii::$service->helper->errors->add('generate alipay bizContent error');
  319. }
  320. // 设置支付成功返回的url 和 支付消息接收url
  321. // 在调用这个函数之前一定要先设置 Yii::$service->payment->setPaymentMethod($payment_method);
  322. if (!$returnUrl) {
  323. $returnUrl = Yii::$service->payment->getStandardReturnUrl();
  324. }
  325. $notifyUrl = Yii::$service->payment->getStandardIpnUrl();
  326. /*
  327. echo $returnUrl;
  328. echo '#';
  329. echo $notifyUrl;
  330. echo '#';
  331. echo $bizContent;
  332. exit;
  333. */
  334. $this->_alipayRequest->setReturnUrl($returnUrl);
  335. $this->_alipayRequest->setNotifyUrl($notifyUrl);
  336. $this->_alipayRequest->setBizContent($bizContent);
  337. return $this->_AopClient->pageExecute($this->_alipayRequest, $type);
  338. }
  339. /**
  340. * 通过订单信息,得到支付宝支付传递的参数数据
  341. * 也就是一个json格式的数组。
  342. */
  343. protected function getStartBizContentAndSetPaymentMethod()
  344. {
  345. $currentOrderInfo = Yii::$service->order->getCurrentOrderInfo();
  346. if (isset($currentOrderInfo['products']) && is_array($currentOrderInfo['products'])) {
  347. $subject_arr = [];
  348. foreach ($currentOrderInfo['products'] as $product) {
  349. $subject_arr[] = $product['name'];
  350. }
  351. if (!empty($subject_arr)) {
  352. $subject = implode(',', $subject_arr);
  353. $increment_id = $currentOrderInfo['increment_id'];
  354. //$base_grand_total = $currentOrderInfo['base_grand_total'];
  355. //$total_amount = Yii::$service->page->currency->getCurrencyPrice($base_grand_total,'CNY');
  356. $total_amount = $currentOrderInfo['grand_total'];
  357. Yii::$service->payment->setPaymentMethod($currentOrderInfo['payment_method']);
  358. return json_encode([
  359. // param 参看:https://docs.open.alipay.com/common/105901
  360. 'out_trade_no' => $increment_id,
  361. 'product_code' => $this->_productCode,
  362. 'total_amount' => $total_amount,
  363. 'subject' => $subject,
  364. //'body' => '',
  365. ]);
  366. }
  367. }
  368. }
  369. // 支付宝的 标示
  370. public function getAlipayHandle()
  371. {
  372. return 'alipay_standard';
  373. }
  374. }