IntraCityExpress.php 21 KB

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