IntraCityExpress.php 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652
  1. <?php
  2. namespace common\components;
  3. use hd\models\IntraCity\StoreFeeForm;
  4. use Yii;
  5. use yii\helpers\Json;
  6. //use linslin\yii2\curl;
  7. use bizHd\wx\classes\WxOpenClass;
  8. use phpseclib\Crypt\RSA;
  9. class IntraCityExpress
  10. {
  11. /**
  12. * 获取 access_token
  13. * @param $merchant
  14. * @param int $ptStyle
  15. * @return string
  16. */
  17. public static function getAccessToken($merchant, $ptStyle = 0)
  18. {
  19. if ($ptStyle == 0) {
  20. $ptStyle = dict::getDict('ptStyle', 'hd');
  21. }
  22. // 直接复用 miniUtil 的获取小程序 access_token 方法
  23. return miniUtil::getMiniProgramAccessToken($merchant, $ptStyle);
  24. }
  25. public static function getMerchant()
  26. {
  27. $merchant = WxOpenClass::getWxInfo();
  28. return $merchant;
  29. }
  30. /**
  31. * 使用 WxApi 方式生成微信API签名
  32. * @param string $url 请求URL
  33. * @param string $appId 小程序AppID
  34. * @param int $timestamp 时间戳
  35. * @param string $reqData 请求体JSON字符串
  36. * @return string 签名字符串
  37. */
  38. private static function generateWxApiSignature($url, $appId, $timestamp, $reqData)
  39. {
  40. // 获取私钥
  41. $env = getenv('YII_ENV') == 'production' ? 'production' : 'dev';
  42. $privateKeyPath = __DIR__ . '/wxapi/' . $env . '/rsa-private-key.txt';
  43. if (!file_exists($privateKeyPath)) {
  44. throw new \Exception("私钥文件不存在: {$privateKeyPath}");
  45. }
  46. $privateKey = file_get_contents($privateKeyPath);
  47. if (!$privateKey) {
  48. throw new \Exception('无法获取私钥文件');
  49. }
  50. // 构建签名载荷,格式:$url\n$appId\n$timestamp\n$reqData
  51. $payload = "$url\n$appId\n$timestamp\n$reqData";
  52. // 方案一: 使用 OpenSSL(推荐方式,与微信官方示例一致)
  53. // $signature = '';
  54. // $result = openssl_sign($payload, $signature, $privateKey, OPENSSL_ALGO_SHA256);
  55. // if (!$result) {
  56. // throw new \Exception('OpenSSL签名失败: ' . openssl_error_string());
  57. // }
  58. // $base64Signature = base64_encode($signature);
  59. // \Yii::info("生成的签名: " . $base64Signature, 'intracity_signature');
  60. // return $base64Signature;
  61. // 方案二:使用 RSA SHA256签名
  62. try {
  63. // 使用RSA SHA256签名
  64. $rsa = new RSA();
  65. $rsa->loadKey($privateKey);
  66. $rsa->setHash("sha256");
  67. $rsa->setMGFHash("sha256");
  68. $signature = $rsa->sign($payload);
  69. // $rsa = new RSA();
  70. // $rsa->loadKey($privateKey);
  71. // $rsa->setSignatureMode(RSA::SIGNATURE_PKCS1); // 明确使用PKCS#1 v1.5
  72. // $rsa->setHash("sha256");
  73. // 不要设置MGF,PKCS#1 v1.5不使用MGF
  74. // $signature = $rsa->sign($payload);
  75. $base64Signature = base64_encode($signature);
  76. \Yii::info("phpseclib生成的签名: " . $base64Signature, 'intracity_signature');
  77. return $base64Signature;
  78. } catch (\Exception $e) {
  79. \Yii::error("所有签名方法都失败 - OpenSSL: " . $e->getMessage() . " phpseclib: " . $e->getMessage(), 'intracity_signature');
  80. throw new \Exception('签名生成失败: OpenSSL和phpseclib都失败');
  81. }
  82. }
  83. /**
  84. * 发送HTTP请求
  85. * @param string $url 请求URL
  86. * @param array $data 请求数据
  87. * @param string $accessToken access_token
  88. * @return array
  89. */
  90. public static function sendRequest($url, $data, $accessToken)
  91. {
  92. // ================ 选择哪个 appId =================
  93. // 微信开放平台 appId
  94. $open = \biz\wx\classes\WxOpenClass::getByCondition(['style' => dict::getDict('ptStyle', 'hd')]);
  95. if (empty($open)) {
  96. util::fail('没有找到平台信息');
  97. }
  98. $component_app_id = $open['appId'];
  99. $appId = $component_app_id;
  100. // 当前小程序的 appId
  101. //$appId = $merchant['miniAppId'] ?? util::fail('app-id 出错');
  102. // 方式一: 使用WxApi方式处理请求 ============================
  103. try {
  104. $wxApi = new \common\components\wxapi\WxApi($appId, $accessToken);
  105. $result = $wxApi->request($url, $data);
  106. return $result;
  107. } catch (\Exception $e) {
  108. Yii::error($e->getMessage());
  109. // 如果WxApi方式失败,回退到简单方式
  110. util::fail('error');
  111. }
  112. // 添加access_token到URL
  113. $urlWithToken = $url . (strpos($url, '?') !== false ? '&' : '?') . 'access_token=' . $accessToken;
  114. $timestamp = time();
  115. $body = Json::encode($data);
  116. if ($body === '[]') {
  117. $body = '{}';
  118. }
  119. // 方式二: 自己处理请求 =========== 失败,不使用(可删除)
  120. // $signature = self::generateWxApiSignature($url, $appId, $timestamp, $body);
  121. // 构建请求头,包含微信API签名所需的头部
  122. // $headers = [
  123. // 'Content-Type: application/json',
  124. // 'Accept: application/json',
  125. // 'Wechatmp-Appid: ' . $appId,
  126. // 'Wechatmp-TimeStamp: ' . $timestamp,
  127. // 'Wechatmp-Signature: ' . $signature
  128. // ];
  129. // $curl = new curl\Curl();
  130. // $response = $curl->setOption(CURLOPT_POSTFIELDS, $body)
  131. // ->setOption(CURLOPT_HTTPHEADER, $headers)
  132. // ->post($urlWithToken);
  133. // if (is_array($response)) {
  134. // return $response;
  135. // }
  136. // return Json::decode($response, true);
  137. }
  138. // ==================== API URL常量 ====================
  139. const API_BASE_URL = 'https://api.weixin.qq.com/cgi-bin/express/intracity';
  140. // 门店管理
  141. const API_CREATE_STORE = self::API_BASE_URL . '/createstore';
  142. const API_UPDATE_STORE = self::API_BASE_URL . '/updatestore';
  143. const API_QUERY_STORE = self::API_BASE_URL . '/querystore';
  144. // 开通门店权限
  145. const API_APPLY_STORE = self::API_BASE_URL . '/apply';
  146. // 订单管理
  147. const API_ADD_ORDER = self::API_BASE_URL . '/addorder';
  148. const API_CANCEL_ORDER = self::API_BASE_URL . '/cancelorder';
  149. const API_GET_ORDER = self::API_BASE_URL . '/queryorder';
  150. // 预下单
  151. const API_PRE_ADD_ORDER = self::API_BASE_URL . '/preaddorder';
  152. // 资金管理
  153. const API_BALANCE_QUERY = self::API_BASE_URL . '/balancequery';
  154. const API_STORE_CHARGE = self::API_BASE_URL . '/storecharge';
  155. const API_STORE_REFUND = self::API_BASE_URL . '/storerefund';
  156. const API_CHARGE_RECORD = self::API_BASE_URL . '/queryflow';
  157. // 测试接口
  158. const API_MOCK_NOTIFY = self::API_BASE_URL . '/mocknotify';
  159. // ==================== 门店管理接口 ====================
  160. /**
  161. * 创建门店
  162. * @param array $storeData 门店信息
  163. * @param string $merchant 商户信息
  164. * @param int $ptStyle
  165. * @return array
  166. */
  167. public static function createStore($storeData, $merchant = null, $ptStyle = 0)
  168. {
  169. if ($merchant === null) {
  170. $merchant = self::getMerchant();
  171. }
  172. $accessToken = self::getAccessToken($merchant, $ptStyle);
  173. $data = [
  174. 'out_store_id' => $storeData['out_store_id'],
  175. 'store_name' => $storeData['store_name'],
  176. 'order_pattern' => 1,
  177. "address_info" => $storeData['address_info']
  178. ];
  179. return self::sendRequest(self::API_CREATE_STORE, $data, $accessToken);
  180. }
  181. /**
  182. * 更新门店
  183. * @param array $storeData 门店信息
  184. * @param string $merchant 商户信息
  185. * @param int $ptStyle
  186. * @return array
  187. */
  188. public static function updateStore($storeData, $merchant = null, $ptStyle = 0)
  189. {
  190. if ($merchant === null) {
  191. $merchant = self::getMerchant();
  192. }
  193. $accessToken = self::getAccessToken($merchant, $ptStyle);
  194. $data = $storeData;
  195. return self::sendRequest(self::API_UPDATE_STORE, $data, $accessToken);
  196. }
  197. /**
  198. * 查询门店
  199. * @param string $outStoreId 门店ID
  200. * @param string $merchant 商户信息
  201. * @param int $ptStyle
  202. * @return array
  203. */
  204. public static function getStore($outStoreId, $merchant = null, $ptStyle = 0)
  205. {
  206. if ($merchant === null) {
  207. $merchant = self::getMerchant();
  208. }
  209. $accessToken = self::getAccessToken($merchant, $ptStyle);
  210. $data = [
  211. 'out_store_id' => $outStoreId,
  212. ];
  213. return self::sendRequest(self::API_QUERY_STORE, $data, $accessToken);
  214. }
  215. /**
  216. * 开通门店权限
  217. * @param null $merchant
  218. * @param int $ptStyle
  219. * @return array
  220. */
  221. public static function applyStore($merchant = null, $ptStyle = 0)
  222. {
  223. if ($merchant === null) {
  224. $merchant = self::getMerchant();
  225. }
  226. $accessToken = self::getAccessToken($merchant, $ptStyle);
  227. return self::sendRequest(self::API_APPLY_STORE, [], $accessToken);
  228. }
  229. // ==================== 订单管理接口 ====================
  230. /**
  231. * 创建订单
  232. * @param array $orderData 订单信息
  233. * @param string $merchant 商户信息
  234. * @param int $ptStyle
  235. * @return array
  236. */
  237. public static function createOrder($orderData, $merchant = null, $ptStyle = 0)
  238. {
  239. if ($merchant === null) {
  240. $merchant = self::getMerchant();
  241. }
  242. $accessToken = self::getAccessToken($merchant, $ptStyle);
  243. //开发环境只能使用沙箱 ssh
  244. if (getenv('YII_ENV') != 'production') {
  245. $orderData['use_sandbox'] = 1;
  246. $orderData['user_name'] = '顺丰同城';
  247. $orderData['user_phone'] = (string)13881979410;
  248. $orderData['user_address'] = '北京市海淀区学清嘉创大厦A座15层';
  249. $orderData['user_lng'] = (double)116.352954;
  250. $orderData['user_lat'] = (double)40.014747;
  251. }
  252. $data = $orderData;
  253. return self::sendRequest(self::API_ADD_ORDER, $data, $accessToken);
  254. }
  255. /**
  256. * 预下单(查询运费)
  257. * @param array $orderData
  258. * @param null $merchant
  259. * @param int $ptStyle
  260. * @return array
  261. */
  262. public static function preAddOrder($orderData, $merchant = null, $ptStyle = 0)
  263. {
  264. // 创建表单验证模型
  265. $form = new StoreFeeForm();
  266. $form->setScenario('query_fee');
  267. $form->load($orderData, ''); // 直接从 post 数据加载,不使用模型名作为前缀
  268. // 执行表单验证
  269. $form->validateForm();
  270. if ($merchant === null) {
  271. $merchant = self::getMerchant();
  272. }
  273. $accessToken = self::getAccessToken($merchant, $ptStyle);
  274. // 请求体
  275. $data = $orderData;
  276. return self::sendRequest(self::API_PRE_ADD_ORDER, $data, $accessToken);
  277. }
  278. /**
  279. * 取消订单
  280. * @param string $wxOrderId 微信订单号
  281. * @param string $storeOrderId 商户订单号
  282. * @param string $wxStoreId 门店ID
  283. * @param string $merchant 商户信息
  284. * @param int $ptStyle
  285. * @return array
  286. */
  287. public static function cancelOrder($wxOrderId = '', $storeOrderId = '', $wxStoreId = '', $merchant = null, $ptStyle = 0)
  288. {
  289. if ($merchant === null) {
  290. $merchant = self::getMerchant();
  291. }
  292. $accessToken = self::getAccessToken($merchant, $ptStyle);
  293. $data = [];
  294. if (!empty($wxOrderId)) {
  295. $data['wx_order_id'] = $wxOrderId;
  296. }
  297. if (!empty($storeOrderId)) {
  298. $data['store_order_id'] = $storeOrderId;
  299. }
  300. if (!empty($wxStoreId)) {
  301. $data['wx_store_id'] = $wxStoreId;
  302. }
  303. $cancelReasons = []; // 1:不需要了 2:信息填错 3:无人接单 99:其他
  304. $data['cancel_reason_id'] = 1;
  305. return self::sendRequest(self::API_CANCEL_ORDER, $data, $accessToken);
  306. }
  307. /**
  308. * 查询订单
  309. * @param string $wxOrderId 微信订单号
  310. * @param string $outOrderId 商户订单号
  311. * @param string $outStoreId 门店ID
  312. * @param string $merchant 商户信息
  313. * @param int $ptStyle
  314. * @return array
  315. */
  316. public static function queryOrder($wxStoreId, $storeOrderId='', $wxOrderId='', $merchant = null, $ptStyle = 0)
  317. {
  318. if ($merchant === null) {
  319. $merchant = self::getMerchant();
  320. }
  321. $accessToken = self::getAccessToken($merchant, $ptStyle);
  322. if (empty($wxOrderId) && (empty($storeOrderId) || empty($wxStoreId))) {
  323. util::fail("参数不足:wx_order_id 或 (store_order_id + wx_store_id) 必须提供一组");
  324. }
  325. $data = [];
  326. if ($wxStoreId != '') {
  327. $data['wx_order_id'] = $wxOrderId;
  328. }
  329. $data['store_order_id'] = $storeOrderId;
  330. $data['wx_store_id'] = $wxStoreId;
  331. return self::sendRequest(self::API_GET_ORDER, $data, $accessToken);
  332. }
  333. // ==================== 资金管理接口 ====================
  334. /**
  335. * 查询门店余额
  336. * @param string $wxStoreId
  337. * @param null $merchant
  338. * @param int $ptStyle
  339. * @return array
  340. */
  341. public static function getBalance($wxStoreId, $merchant = null, $ptStyle = 0)
  342. {
  343. if ($merchant === null) {
  344. $merchant = self::getMerchant();
  345. }
  346. $accessToken = self::getAccessToken($merchant, $ptStyle);
  347. $data = ['wx_store_id' => $wxStoreId]; //'out_store_id' => $outStoreId,
  348. return self::sendRequest(self::API_BALANCE_QUERY, $data, $accessToken);
  349. }
  350. /**
  351. * 门店充值
  352. * @param string $wxStoreId
  353. * @param string $outChargeId
  354. * @param int $amount
  355. * @param null $merchant
  356. * @param int $ptStyle
  357. * @return array
  358. */
  359. public static function storeCharge($wxStoreId, $chargeId, $amount, $merchant = null, $ptStyle = 0)
  360. {
  361. if ($merchant === null) {
  362. $merchant = self::getMerchant();
  363. }
  364. $accessToken = self::getAccessToken($merchant, $ptStyle);
  365. $data = [
  366. 'wx_store_id' => $wxStoreId,
  367. 'service_trans_id' => $chargeId,
  368. 'amount' => $amount,
  369. ];
  370. return self::sendRequest(self::API_STORE_CHARGE, $data, $accessToken);
  371. }
  372. /**
  373. * 门店退款
  374. * @param string $wxStoreId
  375. * @param string $payMode
  376. * @param string $transId
  377. * @param null $merchant
  378. * @param int $ptStyle
  379. * @return array
  380. */
  381. public static function storeFund($wxStoreId, $payMode, $transId, $merchant = null, $ptStyle = 0)
  382. {
  383. if ($merchant === null) {
  384. $merchant = self::getMerchant();
  385. }
  386. $accessToken = self::getAccessToken($merchant, $ptStyle);
  387. $data = [
  388. 'wx_store_id' => $wxStoreId,
  389. 'pay_mode' => $payMode,
  390. 'service_trans_id' => $transId,
  391. ];
  392. return self::sendRequest(self::API_STORE_REFUND, $data, $accessToken);
  393. }
  394. /**
  395. * 查询充值记录
  396. * @param string $outChargeId
  397. * @param null $merchant
  398. * @param int $ptStyle
  399. * @return array
  400. */
  401. public static function getChargeRecord($outChargeId, $merchant = null, $ptStyle = 0)
  402. {
  403. if ($merchant === null) {
  404. $merchant = self::getMerchant();
  405. }
  406. $accessToken = self::getAccessToken($merchant, $ptStyle);
  407. $data = ['out_charge_id' => $outChargeId];
  408. return self::sendRequest(self::API_CHARGE_RECORD, $data, $accessToken);
  409. }
  410. // ==================== 测试接口 ====================
  411. /**
  412. * 模拟回调接口
  413. * @param string $wxOrderId 微信订单号
  414. * @param string $outStoreId 门店ID
  415. * @param string $outOrderId 商户订单号
  416. * @param int $orderStatus 订单状态
  417. * @param string $merchant 商户信息
  418. * @param int $ptStyle
  419. * @return array
  420. */
  421. public static function mockNotify($orderStatus, $wxOrderId = '', $outStoreId = '', $outOrderId = '', $merchant = null, $ptStyle = 0)
  422. {
  423. if ($merchant === null) {
  424. $merchant = self::getMerchant();
  425. }
  426. $accessToken = self::getAccessToken($merchant, $ptStyle);
  427. $data = [
  428. 'order_status' => $orderStatus,
  429. ];
  430. if (!empty($wxOrderId)) {
  431. $data['wx_order_id'] = $wxOrderId;
  432. }
  433. // 注意:文档中模拟回调使用的是 wx_store_id 和 store_order_id
  434. if (!empty($outStoreId) && !empty($outOrderId)) {
  435. $data['wx_store_id'] = $outStoreId;
  436. $data['store_order_id'] = $outOrderId;
  437. }
  438. return self::sendRequest(self::API_MOCK_NOTIFY, $data, $accessToken);
  439. }
  440. /**
  441. * 生成回调签名
  442. * @param array $params 回调参数
  443. * @param string $token 安全token
  444. * @return string
  445. */
  446. public static function generateCallbackSignature($params, $token)
  447. {
  448. // 1. 筛选出参与签名的字段
  449. $signParams = [];
  450. $fieldsToSign = ['appid', 'order_status', 'service_trans_id', 'status_change_time', 'store_order_id', 'timestamp', 'wx_order_id', 'wx_store_id'];
  451. foreach ($fieldsToSign as $field) {
  452. if (isset($params[$field])) {
  453. $signParams[$field] = $params[$field];
  454. }
  455. }
  456. // 2. 按字典序排序参数
  457. ksort($signParams);
  458. // 3. 拼接参数字符串
  459. $signStr = '';
  460. foreach ($signParams as $key => $value) {
  461. $signStr .= $key . '=' . $value . '&';
  462. }
  463. $signStr .= 'token=' . $token;
  464. // 4. 计算MD5并转为小写
  465. return strtolower(md5($signStr));
  466. }
  467. // ==================== 回调验证接口 ====================
  468. /**
  469. * 验证回调签名
  470. * @param array $params 回调参数
  471. * @param string $token 安全token
  472. * @return bool
  473. */
  474. public static function verifyCallback($params, $token)
  475. {
  476. if (!isset($params['sign'])) {
  477. return false;
  478. }
  479. $receivedSign = $params['sign'];
  480. unset($params['sign']);
  481. $calculatedSign = self::generateCallbackSignature($params, $token);
  482. return $receivedSign === $calculatedSign;
  483. }
  484. /**
  485. * 处理订单状态回调
  486. * @param array $callbackData 回调数据
  487. * @param string $token 安全token
  488. * @return array
  489. */
  490. public static function handleOrderCallback($callbackData, $token)
  491. {
  492. // 验证签名
  493. if (!self::verifyCallback($callbackData, $token)) {
  494. return [
  495. 'return_code' => 1,
  496. 'return_msg' => '签名验证失败'
  497. ];
  498. }
  499. // 处理订单状态变化
  500. $orderStatus = $callbackData['order_status'];
  501. $wxOrderId = $callbackData['wx_order_id'];
  502. $outOrderId = $callbackData['store_order_id'] ?? '';
  503. $outStoreId = $callbackData['wx_store_id'] ?? '';
  504. // 这里可以添加具体的业务逻辑处理
  505. // 例如:更新数据库中的订单状态、发送通知等
  506. // 伪代码示例:
  507. /*
  508. switch ($orderStatus) {
  509. case 10000: // 订单创建成功
  510. // 处理订单创建成功逻辑
  511. break;
  512. case 30000: // 配送员接单
  513. // 处理配送员接单逻辑
  514. break;
  515. case 40000: // 配送员到店
  516. // 处理配送员到店逻辑
  517. break;
  518. case 50000: // 配送中
  519. // 处理配送中逻辑
  520. break;
  521. case 70000: // 配送完成
  522. // 处理配送完成逻辑
  523. break;
  524. case 20000: // 商家取消订单
  525. case 20001: // 配送方取消订单
  526. case 60000: // 配送员撤单
  527. // 处理订单取消逻辑
  528. break;
  529. case 90000: // 配送异常
  530. // 处理配送异常逻辑
  531. break;
  532. }
  533. */
  534. return [
  535. 'return_code' => 0,
  536. 'return_msg' => 'OK'
  537. ];
  538. }
  539. // ==================== 常量定义 ====================
  540. /**
  541. * 订单状态常量
  542. */
  543. const ORDER_STATUS_CREATED = 10000; // 订单创建成功
  544. const ORDER_STATUS_CANCELED_BY_MERCHANT = 20000; // 商家取消订单
  545. const ORDER_STATUS_CANCELED_BY_DELIVERY = 20001; // 配送方取消订单
  546. const ORDER_STATUS_ACCEPTED = 30000; // 配送员接单
  547. const ORDER_STATUS_ARRIVED = 40000; // 配送员到店
  548. const ORDER_STATUS_DELIVERING = 50000; // 配送中
  549. const ORDER_STATUS_WITHDRAWN = 60000; // 配送员撤单
  550. const ORDER_STATUS_COMPLETED = 70000; // 配送完成
  551. const ORDER_STATUS_EXCEPTION = 90000; // 配送异常
  552. const GOODS_TYPE_FLOWER = 14; // 鲜花
  553. }