Alipay.php 18 KB

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