IntraCityExpress.php 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643
  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. $data = $orderData;
  244. return self::sendRequest(self::API_ADD_ORDER, $data, $accessToken);
  245. }
  246. /**
  247. * 预下单(查询运费)
  248. * @param array $orderData
  249. * @param null $merchant
  250. * @param int $ptStyle
  251. * @return array
  252. */
  253. public static function preAddOrder($orderData, $merchant = null, $ptStyle = 0)
  254. {
  255. // 创建表单验证模型
  256. $form = new StoreFeeForm();
  257. $form->setScenario('query_fee');
  258. $form->load($orderData, ''); // 直接从 post 数据加载,不使用模型名作为前缀
  259. // 执行表单验证
  260. $form->validateForm();
  261. if ($merchant === null) {
  262. $merchant = self::getMerchant();
  263. }
  264. $accessToken = self::getAccessToken($merchant, $ptStyle);
  265. // 请求体
  266. $data = $orderData;
  267. return self::sendRequest(self::API_PRE_ADD_ORDER, $data, $accessToken);
  268. }
  269. /**
  270. * 取消订单
  271. * @param string $wxOrderId 微信订单号
  272. * @param string $storeOrderId 商户订单号
  273. * @param string $wxStoreId 门店ID
  274. * @param string $merchant 商户信息
  275. * @param int $ptStyle
  276. * @return array
  277. */
  278. public static function cancelOrder($wxOrderId = '', $storeOrderId = '', $wxStoreId = '', $merchant = null, $ptStyle = 0)
  279. {
  280. if ($merchant === null) {
  281. $merchant = self::getMerchant();
  282. }
  283. $accessToken = self::getAccessToken($merchant, $ptStyle);
  284. $data = [];
  285. if (!empty($wxOrderId)) {
  286. $data['wx_order_id'] = $wxOrderId;
  287. }
  288. if (!empty($storeOrderId)) {
  289. $data['store_order_id'] = $storeOrderId;
  290. }
  291. if (!empty($wxStoreId)) {
  292. $data['wx_store_id'] = $wxStoreId;
  293. }
  294. $cancelReasons = []; // 1:不需要了 2:信息填错 3:无人接单 99:其他
  295. $data['cancel_reason_id'] = 1;
  296. return self::sendRequest(self::API_CANCEL_ORDER, $data, $accessToken);
  297. }
  298. /**
  299. * 查询订单
  300. * @param string $wxOrderId 微信订单号
  301. * @param string $outOrderId 商户订单号
  302. * @param string $outStoreId 门店ID
  303. * @param string $merchant 商户信息
  304. * @param int $ptStyle
  305. * @return array
  306. */
  307. public static function queryOrder($wxStoreId, $storeOrderId='', $wxOrderId='', $merchant = null, $ptStyle = 0)
  308. {
  309. if ($merchant === null) {
  310. $merchant = self::getMerchant();
  311. }
  312. $accessToken = self::getAccessToken($merchant, $ptStyle);
  313. if (empty($wxOrderId) && (empty($storeOrderId) || empty($wxStoreId))) {
  314. util::fail("参数不足:wx_order_id 或 (store_order_id + wx_store_id) 必须提供一组");
  315. }
  316. $data = [];
  317. if ($wxStoreId != '') {
  318. $data['wx_order_id'] = $wxOrderId;
  319. }
  320. $data['store_order_id'] = $storeOrderId;
  321. $data['wx_store_id'] = $wxStoreId;
  322. return self::sendRequest(self::API_GET_ORDER, $data, $accessToken);
  323. }
  324. // ==================== 资金管理接口 ====================
  325. /**
  326. * 查询门店余额
  327. * @param string $wxStoreId
  328. * @param null $merchant
  329. * @param int $ptStyle
  330. * @return array
  331. */
  332. public static function getBalance($wxStoreId, $merchant = null, $ptStyle = 0)
  333. {
  334. if ($merchant === null) {
  335. $merchant = self::getMerchant();
  336. }
  337. $accessToken = self::getAccessToken($merchant, $ptStyle);
  338. $data = ['wx_store_id' => $wxStoreId]; //'out_store_id' => $outStoreId,
  339. return self::sendRequest(self::API_BALANCE_QUERY, $data, $accessToken);
  340. }
  341. /**
  342. * 门店充值
  343. * @param string $wxStoreId
  344. * @param string $outChargeId
  345. * @param int $amount
  346. * @param null $merchant
  347. * @param int $ptStyle
  348. * @return array
  349. */
  350. public static function storeCharge($wxStoreId, $chargeId, $amount, $merchant = null, $ptStyle = 0)
  351. {
  352. if ($merchant === null) {
  353. $merchant = self::getMerchant();
  354. }
  355. $accessToken = self::getAccessToken($merchant, $ptStyle);
  356. $data = [
  357. 'wx_store_id' => $wxStoreId,
  358. 'service_trans_id' => $chargeId,
  359. 'amount' => $amount,
  360. ];
  361. return self::sendRequest(self::API_STORE_CHARGE, $data, $accessToken);
  362. }
  363. /**
  364. * 门店退款
  365. * @param string $wxStoreId
  366. * @param string $payMode
  367. * @param string $transId
  368. * @param null $merchant
  369. * @param int $ptStyle
  370. * @return array
  371. */
  372. public static function storeFund($wxStoreId, $payMode, $transId, $merchant = null, $ptStyle = 0)
  373. {
  374. if ($merchant === null) {
  375. $merchant = self::getMerchant();
  376. }
  377. $accessToken = self::getAccessToken($merchant, $ptStyle);
  378. $data = [
  379. 'wx_store_id' => $wxStoreId,
  380. 'pay_mode' => $payMode,
  381. 'service_trans_id' => $transId,
  382. ];
  383. return self::sendRequest(self::API_STORE_REFUND, $data, $accessToken);
  384. }
  385. /**
  386. * 查询充值记录
  387. * @param string $outChargeId
  388. * @param null $merchant
  389. * @param int $ptStyle
  390. * @return array
  391. */
  392. public static function getChargeRecord($outChargeId, $merchant = null, $ptStyle = 0)
  393. {
  394. if ($merchant === null) {
  395. $merchant = self::getMerchant();
  396. }
  397. $accessToken = self::getAccessToken($merchant, $ptStyle);
  398. $data = ['out_charge_id' => $outChargeId];
  399. return self::sendRequest(self::API_CHARGE_RECORD, $data, $accessToken);
  400. }
  401. // ==================== 测试接口 ====================
  402. /**
  403. * 模拟回调接口
  404. * @param string $wxOrderId 微信订单号
  405. * @param string $outStoreId 门店ID
  406. * @param string $outOrderId 商户订单号
  407. * @param int $orderStatus 订单状态
  408. * @param string $merchant 商户信息
  409. * @param int $ptStyle
  410. * @return array
  411. */
  412. public static function mockNotify($orderStatus, $wxOrderId = '', $outStoreId = '', $outOrderId = '', $merchant = null, $ptStyle = 0)
  413. {
  414. if ($merchant === null) {
  415. $merchant = self::getMerchant();
  416. }
  417. $accessToken = self::getAccessToken($merchant, $ptStyle);
  418. $data = [
  419. 'order_status' => $orderStatus,
  420. ];
  421. if (!empty($wxOrderId)) {
  422. $data['wx_order_id'] = $wxOrderId;
  423. }
  424. // 注意:文档中模拟回调使用的是 wx_store_id 和 store_order_id
  425. if (!empty($outStoreId) && !empty($outOrderId)) {
  426. $data['wx_store_id'] = $outStoreId;
  427. $data['store_order_id'] = $outOrderId;
  428. }
  429. return self::sendRequest(self::API_MOCK_NOTIFY, $data, $accessToken);
  430. }
  431. /**
  432. * 生成回调签名
  433. * @param array $params 回调参数
  434. * @param string $token 安全token
  435. * @return string
  436. */
  437. public static function generateCallbackSignature($params, $token)
  438. {
  439. // 1. 筛选出参与签名的字段
  440. $signParams = [];
  441. $fieldsToSign = ['appid', 'order_status', 'service_trans_id', 'status_change_time', 'store_order_id', 'timestamp', 'wx_order_id', 'wx_store_id'];
  442. foreach ($fieldsToSign as $field) {
  443. if (isset($params[$field])) {
  444. $signParams[$field] = $params[$field];
  445. }
  446. }
  447. // 2. 按字典序排序参数
  448. ksort($signParams);
  449. // 3. 拼接参数字符串
  450. $signStr = '';
  451. foreach ($signParams as $key => $value) {
  452. $signStr .= $key . '=' . $value . '&';
  453. }
  454. $signStr .= 'token=' . $token;
  455. // 4. 计算MD5并转为小写
  456. return strtolower(md5($signStr));
  457. }
  458. // ==================== 回调验证接口 ====================
  459. /**
  460. * 验证回调签名
  461. * @param array $params 回调参数
  462. * @param string $token 安全token
  463. * @return bool
  464. */
  465. public static function verifyCallback($params, $token)
  466. {
  467. if (!isset($params['sign'])) {
  468. return false;
  469. }
  470. $receivedSign = $params['sign'];
  471. unset($params['sign']);
  472. $calculatedSign = self::generateCallbackSignature($params, $token);
  473. return $receivedSign === $calculatedSign;
  474. }
  475. /**
  476. * 处理订单状态回调
  477. * @param array $callbackData 回调数据
  478. * @param string $token 安全token
  479. * @return array
  480. */
  481. public static function handleOrderCallback($callbackData, $token)
  482. {
  483. // 验证签名
  484. if (!self::verifyCallback($callbackData, $token)) {
  485. return [
  486. 'return_code' => 1,
  487. 'return_msg' => '签名验证失败'
  488. ];
  489. }
  490. // 处理订单状态变化
  491. $orderStatus = $callbackData['order_status'];
  492. $wxOrderId = $callbackData['wx_order_id'];
  493. $outOrderId = $callbackData['store_order_id'] ?? '';
  494. $outStoreId = $callbackData['wx_store_id'] ?? '';
  495. // 这里可以添加具体的业务逻辑处理
  496. // 例如:更新数据库中的订单状态、发送通知等
  497. // 伪代码示例:
  498. /*
  499. switch ($orderStatus) {
  500. case 10000: // 订单创建成功
  501. // 处理订单创建成功逻辑
  502. break;
  503. case 30000: // 配送员接单
  504. // 处理配送员接单逻辑
  505. break;
  506. case 40000: // 配送员到店
  507. // 处理配送员到店逻辑
  508. break;
  509. case 50000: // 配送中
  510. // 处理配送中逻辑
  511. break;
  512. case 70000: // 配送完成
  513. // 处理配送完成逻辑
  514. break;
  515. case 20000: // 商家取消订单
  516. case 20001: // 配送方取消订单
  517. case 60000: // 配送员撤单
  518. // 处理订单取消逻辑
  519. break;
  520. case 90000: // 配送异常
  521. // 处理配送异常逻辑
  522. break;
  523. }
  524. */
  525. return [
  526. 'return_code' => 0,
  527. 'return_msg' => 'OK'
  528. ];
  529. }
  530. // ==================== 常量定义 ====================
  531. /**
  532. * 订单状态常量
  533. */
  534. const ORDER_STATUS_CREATED = 10000; // 订单创建成功
  535. const ORDER_STATUS_CANCELED_BY_MERCHANT = 20000; // 商家取消订单
  536. const ORDER_STATUS_CANCELED_BY_DELIVERY = 20001; // 配送方取消订单
  537. const ORDER_STATUS_ACCEPTED = 30000; // 配送员接单
  538. const ORDER_STATUS_ARRIVED = 40000; // 配送员到店
  539. const ORDER_STATUS_DELIVERING = 50000; // 配送中
  540. const ORDER_STATUS_WITHDRAWN = 60000; // 配送员撤单
  541. const ORDER_STATUS_COMPLETED = 70000; // 配送完成
  542. const ORDER_STATUS_EXCEPTION = 90000; // 配送异常
  543. const GOODS_TYPE_FLOWER = 14; // 鲜花
  544. }