AlipayThirdAppForm.php 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479
  1. <?php
  2. /**
  3. * 重庆赤晓店信息科技有限公司
  4. * https://www.chixiaodian.com
  5. * Copyright (c) 2023 赤店商城 All rights reserved.
  6. */
  7. namespace app\modules\admin\models;
  8. use AopClient;
  9. use app\models\AliMiniSign;
  10. use app\models\Option;
  11. use app\models\Salesman;
  12. use app\models\StoreAliMini;
  13. use app\models\StoreMiniToken;
  14. use app\utils\Alipay\alipaySdk\aop\request\AlipayOpenAgentConfirmRequest;
  15. use app\utils\Alipay\alipaySdk\aop\request\AlipayOpenAgentCreateRequest;
  16. use app\utils\Alipay\alipaySdk\aop\request\AlipayOpenAgentMobilepaySignRequest;
  17. use app\utils\Alipay\alipaySdk\aop\request\AlipayOpenAgentOrderQueryRequest;
  18. use app\utils\CurlHelper;
  19. use app\utils\QrCode;
  20. use yii\base\Model;
  21. include_once \Yii::$app->basePath . "/utils/Alipay/alipaySdk/aop/AopClient.php";;
  22. class AlipayThirdAppForm extends Model
  23. {
  24. public $store_id;
  25. public $status;
  26. public $params_info;
  27. public $base_info;
  28. public $template_info;
  29. public function rules()
  30. {
  31. return [
  32. [['store_id', 'status'], 'integer'],
  33. [['params_info'], 'safe']
  34. ];
  35. }
  36. //构造函数
  37. public function __construct($config = [])
  38. {
  39. parent::__construct($config);
  40. //获取三方平台信息
  41. //三方平台Appid
  42. $this->base_info['appid'] = Option::get("alipay_appid", 0, 'saas')['value'];
  43. //获取当前时间戳
  44. $this->base_info['timestamp'] = date("Y-m-d H:i:s");
  45. //设置加解密方式
  46. $this->base_info['sign_type'] = "RSA2";
  47. //获取私钥
  48. $this->base_info['private_key'] = Option::get("alipay_app_private_key", 0, 'saas')['value'];
  49. //获取公钥
  50. $this->base_info['public_key'] = Option::get("alipay_public_key", 0, 'saas')['value'];
  51. //获取ase_key,加签方式
  52. $this->base_info['alipay_aes_key'] = Option::get("alipay_aes_key", 0, 'saas')['value'];
  53. //获取模板aes加签方式
  54. $this->template_info['ali_template_aes'] = Option::get("ali_template_aes", 0, 'saas')['value'];
  55. //获取模板appid
  56. $this->template_info['ali_template_appid'] = Option::get("ali_template_appid", 0, 'saas')['value'];
  57. //获取模板auth_token
  58. $this->template_info['ali_template_token'] = Option::get("ali_template_token", 0, 'saas')['value'];
  59. }
  60. public function miniCommon($request, $biz_content = null, $is_hidden_token = 0, $token = '')
  61. {
  62. try {
  63. //模板信息
  64. $template_info = $this->template_info;
  65. //请求的基础信息
  66. $base_info = $this->base_info;
  67. //模板token
  68. $auth_token = $template_info['ali_template_token'];
  69. //小程序ID
  70. $store_id = $this->store_id;
  71. if (!empty($store_id)) {
  72. $store_token = StoreMiniToken::findOne(['store_id' => $store_id]);
  73. //如果小程序ID存在,则将token从模板转成商家小程序的token
  74. if (!empty($store_token->app_auth_token)) {
  75. $auth_token = $store_token->app_auth_token;
  76. }
  77. }
  78. //设置基础请求数据
  79. $aop = new AopClient();
  80. //设置appid
  81. $aop->appId = $base_info['appid'];
  82. //设置私钥
  83. $aop->rsaPrivateKey = $base_info['private_key'];
  84. //设置公钥
  85. $aop->alipayrsaPublicKey = $base_info['public_key'];
  86. //设置ase_key,加签方式
  87. $aop->encryptKey = $base_info['alipay_aes_key'];
  88. //设置加解密方式
  89. $aop->signType = $base_info['sign_type'];
  90. //处理没有biz_content情况
  91. if ($biz_content) {
  92. $request->setBizContent($biz_content);
  93. }
  94. //处理不需要token情况
  95. if ($is_hidden_token === 0) {
  96. //开始请求
  97. $result = $aop->execute($request, null, ($token ?: $auth_token));
  98. } else {
  99. //开始请求
  100. $result = $aop->execute($request);
  101. }
  102. //请求后的数据处理
  103. $responseNode = str_replace(".", "_", $request->getApiMethodName()) . "_response";
  104. return $result->$responseNode;
  105. } catch (\Exception $e) {
  106. return [
  107. 'sub_msg' => $e->getMessage()
  108. ];
  109. }
  110. }
  111. public function getParams()
  112. {
  113. try {
  114. $store_id = $this->store_id;
  115. $data = [
  116. 'appid' => $this->base_info['appid'],
  117. 'redirect_uri' => urlencode(\Yii::$app->request->hostInfo . '/index.php/alipay/token'),
  118. 'state' => $store_id
  119. ];
  120. $token_log = StoreMiniToken::findOne(['store_id' => $store_id]) ?: new StoreMiniToken();
  121. $token_log->store_id = $store_id;
  122. $token_log->created_at = time();
  123. $token_log->type = 1;
  124. $token_log->salesman_id = 0;
  125. $token_log->save();
  126. $url = "https://openauth.alipay.com/oauth2/appToAppBatchAuth.htm?app_id=" . $data['appid'] . "&application_type=WEBAPP&redirect_uri=" . $data['redirect_uri'] . '&state=' . $data['state'];
  127. $filename = md5(date('Ym') . 'token' . $token_log->id);
  128. $path = \Yii::$app->runtimePath . '/image/' . $filename . '.jpg';
  129. $pic_url = str_replace('http://', 'https://', \Yii::$app->request->hostInfo . '/runtime/image/' . $filename . '.jpg');
  130. QrCode::image($url, 500, false, 'L', 'JPEG', 0, ['255,255,255', '0,0,0'], 1, false, $path);
  131. $token_log->url = $pic_url;
  132. if (!$token_log->save()) {
  133. throw new \Exception("生成授权链接失败");
  134. }
  135. return [
  136. 'code' => 0,
  137. 'url' => $pic_url,
  138. 'msg' => "获取成功"
  139. ];
  140. } catch (\Exception $e) {
  141. return [
  142. 'code' => 1,
  143. 'msg' => $e->getMessage()
  144. ];
  145. }
  146. }
  147. /**
  148. * @return array|void
  149. * 查询授权状态
  150. */
  151. public function getStatus()
  152. {
  153. try {
  154. $store_id = $this->store_id;
  155. $token_log = StoreMiniToken::findOne(['store_id' => $store_id]);
  156. if ($token_log && ((int)$token_log->status === 1) && !empty($token_log->app_auth_token)) {
  157. return [
  158. 'code' => 0,
  159. 'msg' => '授权完成,请填写营业执照编号以及营业执照'
  160. ];
  161. }
  162. } catch (\Exception $e) {
  163. return [
  164. 'code' => 1,
  165. 'msg' => $e->getMessage()
  166. ];
  167. }
  168. }
  169. /**
  170. * @return array
  171. * 创建事务
  172. */
  173. public function getAppPay(): array
  174. {
  175. try {
  176. $store_id = $this->store_id;
  177. $params_info = $this->params_info;
  178. $token_log = StoreMiniToken::findOne(['store_id' => $store_id]);
  179. //获取事务状态
  180. $batch_status = intval($token_log->batch_status);
  181. //如果已经开始审核,且没有失败,没有被商户手动拒绝
  182. if ($batch_status > 4 && $batch_status !== 8) {
  183. throw new \Exception("审核中,无需操作");
  184. }
  185. if (
  186. empty($params_info['account']) ||
  187. empty($params_info['contact_name']) ||
  188. empty($params_info['contact_mobile']) ||
  189. empty($params_info['contact_email']) ||
  190. empty($params_info['license_no']) ||
  191. empty($params_info['license_pic'])
  192. ) {
  193. throw new \Exception("请完善信息");
  194. }
  195. $param = json_encode([
  196. 'account' => $params_info['account'] ?: $token_log->account,
  197. 'contact_info' => [
  198. 'contact_name' => $params_info['contact_name'] ?: $token_log->contact_name,
  199. 'contact_mobile' => $params_info['contact_mobile'] ?: $token_log->contact_mobile,
  200. 'contact_email' => $params_info['contact_email'] ?: $token_log->contact_email
  201. ]
  202. ]);
  203. //调用接口配置信息
  204. $request = new AlipayOpenAgentCreateRequest();
  205. //调用接口
  206. $result = $this->miniCommon($request, $param);
  207. if ($result->code == 10000) {
  208. //保存事务编号,用作签约等操作
  209. $batch_no = $result->batch_no;
  210. $token_log->batch_no = $batch_no;
  211. $token_log->account = $params_info['account'];
  212. $token_log->contact_name = $params_info['contact_name'];
  213. $token_log->contact_mobile = $params_info['contact_mobile'];
  214. $token_log->contact_email = $params_info['contact_email'];
  215. //保存状态信息
  216. $token_log->batch_status = 1;
  217. //保存信息
  218. if (!$token_log->save()) {
  219. throw new \Exception(json_encode($token_log->errors));
  220. }
  221. $result = $this->appPay($token_log, $batch_no);
  222. if ($result['code'] !== 0) {
  223. throw new \Exception($result['msg']);
  224. }
  225. $result = $this->openAgentConfirm($token_log, $batch_no);
  226. if ($result['code'] !== 0) {
  227. throw new \Exception($result['msg']);
  228. }
  229. return [
  230. 'code' => 0,
  231. 'msg' => $result['msg'],
  232. 'data' => $result['data']
  233. ];
  234. } else {
  235. throw new \Exception($result->sub_msg);
  236. }
  237. } catch (\Exception $e) {
  238. return [
  239. 'code' => 1,
  240. 'msg' => $e->getMessage()
  241. ];
  242. }
  243. }
  244. /**
  245. * @param $model
  246. * @param string $batch_no
  247. * @return array
  248. * 签约app支付
  249. */
  250. public function appPay($model, string $batch_no = '')
  251. {
  252. try {
  253. $params_info = $this->params_info;
  254. $request = new AlipayOpenAgentMobilepaySignRequest();
  255. $license_pic = $this->saveTempImage($params_info['license_pic']);
  256. //设置业务编号
  257. $request->setBatchNo($batch_no);
  258. //设置商家经营类目编码
  259. $request->setMccCode("A0002_B0201");
  260. //特殊资质证书
  261. if (!empty($params_info['special_license_pic'])) {
  262. $request->setSpecialLicensePic($params_info['other_data']);
  263. }
  264. $request->setBusinessLicenseNo($params_info['license_no']);
  265. $request->setDateLimitation("2099-12-31");
  266. $request->setBusinessLicensePic("@". $license_pic);
  267. $request->setAppName("应用签约");
  268. //调用接口
  269. $result = $this->miniCommon($request,null, 1);
  270. //如果请求成功或者报同类产品已经签约就显示成功
  271. if (($result->code == 10000) || $result->sub_code == "ANT_PRODUCT_CONFLICT") {
  272. $model->batch_status = 2;
  273. $model->license_pic = $params_info['license_pic'];
  274. $model->license_no = $params_info['license_no'];
  275. $model->other_data = $params_info['other_data'];
  276. if ($result->sub_code == "ANT_PRODUCT_CONFLICT") {
  277. $model->batch_status = 2;
  278. }
  279. if (!$model->save()) {
  280. throw new \Exception(json_encode($model->errors));
  281. }
  282. return [
  283. 'code' => 0,
  284. 'msg' => "操作成功",
  285. 'batch_status' => $model->batch_status
  286. ];
  287. }
  288. throw new \Exception($result->sub_msg);
  289. } catch (\Exception $e) {
  290. return [
  291. 'code' => 1,
  292. 'msg' => $e->getMessage()
  293. ];
  294. }
  295. }
  296. /**
  297. * @param $model
  298. * @param string $batch_no
  299. * @return array
  300. * 提交事务
  301. */
  302. public function openAgentConfirm($model, string $batch_no = '')
  303. {
  304. try {
  305. //请求参数
  306. $param = json_encode([
  307. //业务编号
  308. 'batch_no' => $batch_no
  309. ]);
  310. //请求配置信息
  311. $request = new AlipayOpenAgentConfirmRequest();
  312. $result = $this->miniCommon($request, $param, 1);
  313. //请求成功
  314. if ($result->code == 10000) {
  315. $model->batch_status = 3;
  316. if (!$model->save()) {
  317. throw new \Exception($model->errors);
  318. }
  319. return [
  320. 'code' => 0,
  321. 'msg' => "成功",
  322. 'data' => $result
  323. ];
  324. }
  325. throw new \Exception($result->sub_msg);
  326. } catch (\Exception $e) {
  327. return [
  328. 'code' => 1,
  329. 'msg' => $e->getMessage(),
  330. ];
  331. }
  332. }
  333. /**
  334. * @return array|void
  335. * 查询状态
  336. */
  337. public function openAgentOrderStatus()
  338. {
  339. try {
  340. $store_id = $this->store_id;
  341. $model = StoreMiniToken::find()->where(['and', ['in', 'batch_status', [3, 5, 6]], ['store_id' => $store_id]])->one();
  342. if (empty($model)) {
  343. throw new \Exception('没有待查询的信息');
  344. }
  345. $batch_no = $model->batch_no;
  346. if (empty($batch_no)) {
  347. throw new \Exception('未创建事务');
  348. }
  349. //请求参数
  350. $param = json_encode([
  351. //业务编号
  352. 'batch_no' => $batch_no
  353. ]);
  354. $request = new AlipayOpenAgentOrderQueryRequest();
  355. $result = $this->miniCommon($request, $param, 1);
  356. if ($result->code == 10000) {
  357. $status = $result->order_status;
  358. $msg = "成功";
  359. switch ($status) {
  360. case "MERCHANT_INFO_HOLD": //异常单 4
  361. $model->batch_status = 4;
  362. $model->fail_reason = "订单异常";
  363. break;
  364. case "MERCHANT_AUDITING": //审核中 3
  365. $model->batch_status = 3;
  366. $model->fail_reason = "订单审核中";
  367. break;
  368. case "MERCHANT_CONFIRM": //待确认 5
  369. $model->batch_status = 5;
  370. $model->batch_url = $result->confirm_url;
  371. $model->fail_reason = "等待商户确认,请注意查收邮件以及短信或访问" . $result->confirm_url . "进行授权";
  372. break;
  373. case "MERCHANT_CONFIRM_SUCCESS": //商户确认成功 6
  374. $model->batch_status = 2;
  375. $model->fail_reason = "商户确认成功";
  376. break;
  377. case "MERCHANT_CONFIRM_TIME_OUT": //商户超时未确认 7
  378. $model->batch_status = 7;
  379. $model->fail_reason = "商户超时未确认";
  380. break;
  381. case "MERCHANT_APPLY_ORDER_CANCELED": //审核失败或商户拒绝 8
  382. $model->batch_status = 8;
  383. $model->fail_reason = $result->reject_reason;
  384. break;
  385. }
  386. if (!$model->save()) {
  387. throw new \Exception($model->errors);
  388. }
  389. return [
  390. 'code' => 0,
  391. 'msg' => $msg,
  392. 'data' => $result
  393. ];
  394. }
  395. throw new \Exception($result->sub_msg);
  396. } catch (\Exception $e) {
  397. $file_name = \Yii::$app->runtimePath . '/logs/app_pay.log';
  398. file_put_contents($file_name, "\r\n" . '[商城申请App支付][' . date('Y-m-d H:i:s') . ']' . $e->getMessage(), FILE_APPEND);
  399. return ;
  400. }
  401. }
  402. public function getAppInfo()
  403. {
  404. try {
  405. $store_id = $this->store_id;
  406. $model = StoreMiniToken::find()->where(['store_id' => $store_id])
  407. ->select('id, status, batch_status, contact_name, contact_mobile, contact_email, license_no, license_pic,
  408. other_data, batch_url, fail_reason, account')->asArray()->one();
  409. $form = new AlipayThirdMerchantForm();
  410. $form->ali_mini_id = $model['id'];
  411. $form->app_type = 1;
  412. $form->openAgentOrderStatus();
  413. //获取app分账权限
  414. $ali_sign = AliMiniSign::findOne(['app_type' => 1, 'ali_mini_id' => $model['id'], 'type' => 1]);
  415. $model['ali_sign'] = $ali_sign ?: [
  416. 'batch_status' => 0
  417. ];
  418. return [
  419. 'code' => 0,
  420. 'data' => $model
  421. ];
  422. } catch (\Exception $e) {
  423. return [
  424. 'code' => 1,
  425. 'msg' => $e->getMessage(),
  426. ];
  427. }
  428. }
  429. //获取网络图片到临时目录
  430. public function saveTempImage($url)
  431. {
  432. if (strpos($url, 'http') === false) {
  433. $url = 'http:' . trim($url);
  434. }
  435. if (!is_dir(\Yii::$app->runtimePath . '/image')) {
  436. mkdir(\Yii::$app->runtimePath . '/image');
  437. }
  438. $save_path = \Yii::$app->runtimePath . '/image/' . md5($url) . '.jpg';
  439. CurlHelper::download($url, $save_path);
  440. return $save_path;
  441. }
  442. }