wechatlogic.php 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409
  1. <?php
  2. /*
  3. * @Author: wang jun
  4. * @Date: 2022-01-18 11:12:23
  5. * @Last Modified by: wang jun
  6. * @Last Modified time: 2022-01-19 10:38:13
  7. * 微信类
  8. */
  9. namespace app\index\logic;
  10. use app\common\model\payordermodel;
  11. use app\common\model\wxusermodel;
  12. use think\facade\Log;
  13. class wechatlogic extends baselogic
  14. {
  15. /**
  16. * 设置请求数据规则
  17. * 20220107
  18. * wj
  19. */
  20. protected function setrules()
  21. {
  22. $list = [
  23. 'getOpenid' => [
  24. ['name' => 'code', 'title' => 'code', 'require' => true, 'type' => 'string'],
  25. ],
  26. 'create_qrcode' => [
  27. ['name' => 'scene', 'title' => 'scene', 'require' => true, 'type' => 'string'],
  28. ['name' => 'page', 'title' => 'page', 'require' => true, 'type' => 'string'],
  29. ['name' => 'width', 'title' => 'width', 'require' => true, 'type' => 'numeric'],
  30. ['name' => 'dir', 'title' => '文件夹', 'require' => false, 'type' => 'string', 'default' => ""],
  31. ],
  32. 'createorder' => [
  33. ['name' => 'openid', 'title' => 'openid', 'require' => true, 'type' => 'string'],
  34. ['name' => 'total_fee', 'title' => '支付费用', 'require' => true, 'type' => 'numeric'], //以分为单位
  35. ['name' => 'body', 'title' => '支付说明', 'require' => true, 'type' => 'string'],
  36. ['name' => 'out_trade_no', 'title' => '商户支付单号', 'require' => true, 'type' => 'string'],
  37. ['name' => 'notify_url', 'title' => '回调地址', 'require' => true, 'type' => 'string'],
  38. ['name' => 'trade_type', 'title' => 'trade_type', 'require' => true, 'type' => 'string'],
  39. ],
  40. ];
  41. return $list;
  42. }
  43. /**
  44. * 获取小程序配置信息
  45. *
  46. * @return void
  47. * @author wj
  48. * @date 2022-07-22
  49. */
  50. public function getselfwxconfig()
  51. {
  52. $config = [
  53. //'appid' => 'wx47d6be96fb2d466c',
  54. //'appSecret' => 'c0252b0cea090a1f3fb41ea7c71d55d6',
  55. 'appid' => 'wxcacf6eb6e7478e29',
  56. 'appSecret' => '3722c3f95df0569498a0e32ae6e85153',
  57. ];
  58. return $config;
  59. }
  60. /**
  61. * 获取商户配置信息
  62. *
  63. * @return void
  64. * @author wj
  65. * @date 2022-07-22
  66. */
  67. public function getpayconfig()
  68. {
  69. $config = [
  70. 'mchid' => '1616316171', //零散务工工会
  71. 'key' => 'WaterCat20211001ShuiMaoGongJiang', //商户号key
  72. ];
  73. return $config;
  74. }
  75. private function curl_get($url, &$httpCode = 0)
  76. {
  77. $ch = curl_init();
  78. curl_setopt($ch, CURLOPT_URL, $url);
  79. curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
  80. //不做证书校验,部署在linux环境下请改为true
  81. curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
  82. curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10);
  83. $file_contents = curl_exec($ch);
  84. $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
  85. curl_close($ch);
  86. return $file_contents;
  87. }
  88. private function getAccessToken()
  89. {
  90. $config = $this->getselfwxconfig();
  91. $appid = $config['appid'];
  92. $appSecret = $config['appSecret'];
  93. $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" . $appid . "&secret=" . $appSecret;
  94. $result = $this->curl_get($url);
  95. $wxResult = json_decode($result, true);
  96. return $wxResult;
  97. }
  98. //开启curl post请求
  99. private function sendCmd($url, $data)
  100. {
  101. $curl = curl_init(); // 启动一个CURL会话
  102. curl_setopt($curl, CURLOPT_URL, $url); // 要访问的地址
  103. curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, 0); // 对认证证书来源的检测
  104. curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 2); // 从证书中检查SSL加密算法是否存在
  105. curl_setopt($curl, CURLOPT_HTTPHEADER, array('Expect:')); //解决数据包大不能提交
  106. curl_setopt($curl, CURLOPT_FOLLOWLOCATION, 1); // 使用自动跳转
  107. curl_setopt($curl, CURLOPT_AUTOREFERER, 1); // 自动设置Referer
  108. curl_setopt($curl, CURLOPT_POST, 1); // 发送一个常规的Post请求
  109. curl_setopt($curl, CURLOPT_POSTFIELDS, $data); // Post提交的数据包
  110. curl_setopt($curl, CURLOPT_TIMEOUT, 30); // 设置超时限制防止死循
  111. curl_setopt($curl, CURLOPT_HEADER, 0); // 显示返回的Header区域内容
  112. curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1); // 获取的信息以文件流的形式返回
  113. $tmpInfo = curl_exec($curl); // 执行操作
  114. if (curl_errno($curl)) {
  115. echo 'Errno' . curl_error($curl);
  116. }
  117. curl_close($curl); // 关键CURL会话
  118. return $tmpInfo; // 返回数据
  119. }
  120. /**
  121. * 获取openid
  122. * 20220118
  123. * wj
  124. * code 必填
  125. */
  126. public function getOpenid($arr)
  127. {
  128. $result = $this->checkparam(__FUNCTION__, $arr);
  129. if (1 != $result['status']) {
  130. return $result;
  131. }
  132. $data = $result['data'];
  133. $code = $data['code'];
  134. $config = $this->getselfwxconfig();
  135. $appid = $config['appid'];
  136. $appSecret = $config['appSecret'];
  137. $wxUrl = 'https://api.weixin.qq.com/sns/jscode2session?appid=%s&secret=%s&js_code=%s&grant_type=authorization_code';
  138. $getUrl = sprintf($wxUrl, $appid, $appSecret, $code);
  139. $result = $this->curl_get($getUrl);
  140. $wxResult = json_decode($result, true);
  141. Log::info($wxResult);
  142. if (empty($wxResult)) {
  143. return backarr(0, "无返回数据");
  144. }
  145. $logfail = array_key_exists('errcode', $wxResult);
  146. if ($logfail) {
  147. return backarr(0, 'error', $logfail['errmsg']);
  148. }
  149. $openid = $wxResult['openid'];
  150. $data = ['openid' => $openid];
  151. if (isset($wxResult['unionid'])) {
  152. $unionid = $wxResult['unionid'];
  153. $m_wu = new wxusermodel();
  154. $result = $m_wu->updateunionidbyopenid($openid, $unionid);
  155. if (empty($result['status'])) {
  156. return backarr(0, $result['msg']);
  157. }
  158. }
  159. return backarr(1, 'success', $data);
  160. }
  161. //获得二维码
  162. public function create_qrcode($arr)
  163. {
  164. $result = $this->checkparam(__FUNCTION__, $arr);
  165. if (1 != $result['status']) {
  166. return $result;
  167. }
  168. $data = $result['data'];
  169. $scene = $data['scene'];
  170. $width = $data['width'];
  171. $page = $data['page'];
  172. $dir = $data['dir'];
  173. $qr_path = "./Uploads/";
  174. if (empty($dir)) {
  175. $dir = 'default';
  176. }
  177. $uploaddir = $qr_path . 'qrcode/' . $dir . "/";
  178. $getdir = '/Uploads/qrcode/' . $dir . "/";
  179. if (!file_exists($uploaddir)) {
  180. mkdir($uploaddir, 0700, true); //判断保存目录是否存在,不存在自动生成文件目录
  181. }
  182. $filename = time() . '.png';
  183. $file = $uploaddir . $filename;
  184. $getdir .= $filename;
  185. $access = $this->getAccessToken();
  186. $access_token = $access['access_token'];
  187. $url = 'https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token=' . $access_token;
  188. $qrcode = array(
  189. 'scene' => $scene, //二维码所带参数
  190. 'width' => $width,
  191. 'page' => $page, //二维码跳转路径(要已发布小程序)
  192. 'auto_color' => true,
  193. );
  194. $result = $this->sendCmd($url, json_encode($qrcode)); //请求微信接口
  195. Log::info($result);
  196. $errcode = json_decode($result, true)['errcode'];
  197. $errmsg = json_decode($result, true)['errmsg'];
  198. if ($errcode) {
  199. return backarr(0, $errmsg);
  200. }
  201. $res = file_put_contents($file, $result); //将微信返回的图片数据流写入文件
  202. if ($res === false) {
  203. return backarr(0, '生成二维码失败');
  204. } else {
  205. $path = getselfurl('default') . $getdir;
  206. return backarr(1, 'success', ['path' => $path]);
  207. }
  208. }
  209. /**
  210. * 创建支付订单 统一下单接口
  211. *
  212. * @param [type] $arr
  213. * @return void
  214. * @author wj
  215. * @date 2022-07-22
  216. */
  217. public function createorder($arr)
  218. {
  219. $result = $this->checkparam(__FUNCTION__, $arr);
  220. if (1 != $result['status']) {
  221. return $result;
  222. }
  223. $data = $result['data'];
  224. $openid = $data['openid'];
  225. $total_fee = $data['total_fee'];
  226. $body = $data['body'];
  227. $out_trade_no = $data['out_trade_no'];
  228. $notify_url = $data['notify_url'];
  229. $trade_type = $data['trade_type'];
  230. //$wid = $data['wid'];
  231. $appointentid = $data['appointent_id'];
  232. $payconfig = $this->getpayconfig();
  233. $mchid = $payconfig['mchid'];
  234. $key = $payconfig['key'];
  235. $nonce_str = getRandomStrings($mchid);
  236. $config = $this->getselfwxconfig();
  237. $appid = $config['appid'];
  238. $data = [
  239. 'appid' => $appid,
  240. 'mch_id' => $mchid,
  241. 'nonce_str' => $nonce_str,
  242. 'openid' => $openid,
  243. 'body' => $body,
  244. 'out_trade_no' => $out_trade_no,
  245. 'total_fee' => $total_fee,
  246. 'spbill_create_ip' => '8.8.8.8',
  247. 'notify_url' => $notify_url,
  248. 'trade_type' => $trade_type,
  249. ];
  250. $url = "https://api.mch.weixin.qq.com/pay/unifiedorder";
  251. ksort($data);
  252. $sign_str = $this->ToUrlParams($data);
  253. $sign_str = $sign_str . "&key=" . $key;
  254. $data['sign'] = strtoupper(md5($sign_str));
  255. $xml = $this->arrayToXml($data);
  256. log::info($xml);
  257. $r = $this->postXmlCurl($xml, $url, true);
  258. log::info($r);
  259. $result = json_decode($this->xml_to_json($r));
  260. log::info($result); //保留这个做记录,以便出错后查询
  261. if ($result->return_code == 'SUCCESS') {
  262. if ($result->result_code == 'FAIL') {
  263. $msg = $result->err_code_des;
  264. return backarr(0, $msg);
  265. }
  266. $sdata['appId'] = $appid;
  267. $sdata['timeStamp'] = time();
  268. $sdata['nonceStr'] = md5(time() . rand() . rand() . $openid);
  269. $sdata['package'] = "prepay_id=" . $result->prepay_id;
  270. $sdata['signType'] = "MD5";
  271. $payorder['openid'] = $openid;
  272. $payorder['prepay_id'] = $result->prepay_id;
  273. $payorder['create_date'] = date('Y-m-d H:i:s');
  274. $payorder['payfee'] = $data['total_fee'];
  275. $payorder['outorderno'] = $data['out_trade_no'];
  276. $payorder['order_type'] = 1;
  277. //$payorder['wid'] = $wid;
  278. $payorder['appointent_id'] = $appointentid;
  279. $l_po = new payordermodel();
  280. $poid = $l_po->insertData($payorder);
  281. if (empty($poid)) {
  282. return backarr(0, '订单创建失败');
  283. }
  284. ksort($sdata);
  285. $sign_str = $this->ToUrlParams($sdata);
  286. $sign_str = $sign_str . "&key=" . $key;
  287. $sdata['paySign'] = strtoupper(md5($sign_str));
  288. $sdata['outorderno'] = $data['out_trade_no'];
  289. return backarr(1, '订单创建成功', $sdata);
  290. }
  291. }
  292. /*
  293. * 用于微信支付转换认证的信息用的
  294. * by:leoyi
  295. * date:2018-4-8
  296. */
  297. public function ToUrlParams($data)
  298. {
  299. $buff = "";
  300. foreach ($data as $k => $v) {
  301. if ($k != "sign" && $v != "" && !is_array($v)) {
  302. $buff .= $k . "=" . $v . "&";
  303. }
  304. }
  305. $buff = trim($buff, "&");
  306. return $buff;
  307. }
  308. /*
  309. * 微信支付-数组转xml
  310. * by:leoyi
  311. * date:2018-4-8
  312. */
  313. public function arrayToXml($arr)
  314. {
  315. $xml = "<xml>";
  316. foreach ($arr as $key => $val) {
  317. if (is_numeric($val)) {
  318. $xml .= "<" . $key . ">" . $val . "</" . $key . ">";
  319. } else {
  320. $xml .= "<" . $key . "><![CDATA[" . $val . "]]></" . $key . ">";
  321. }
  322. }
  323. $xml .= "</xml>";
  324. return $xml;
  325. }
  326. /*
  327. * 微信支付-数组转xml
  328. * by:leoyi
  329. * date:2018-4-8
  330. */
  331. public function xml_to_json($xmlstring)
  332. {
  333. return json_encode($this->xml_to_array($xmlstring), JSON_UNESCAPED_UNICODE);
  334. }
  335. /*
  336. * 把xml转换成array
  337. * by:leoyi
  338. * Date:2018-4-11
  339. */
  340. public function xml_to_array($xml)
  341. {
  342. //return ((array) simplexml_load_string($xmlstring));
  343. return simplexml_load_string($xml, 'SimpleXMLElement', LIBXML_NOCDATA);
  344. //return json_decode(xml_to_json($xmlstring));
  345. }
  346. /**
  347. * 用户post方法请求xml信息用的 支付用
  348. * @author write by leoyi 2018-04-8
  349. */
  350. public function postXmlCurl($xml, $url, $useCert = false, $second = 10)
  351. {
  352. $ch = curl_init();
  353. //设置超时
  354. curl_setopt($ch, CURLOPT_TIMEOUT, $second);
  355. curl_setopt($ch, CURLOPT_URL, $url);
  356. curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
  357. curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false); //严格校验2
  358. //设置header
  359. curl_setopt($ch, CURLOPT_HEADER, false);
  360. //要求结果为字符串且输出到屏幕上
  361. curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
  362. curl_setopt($ch, CURLOPT_POST, true);
  363. curl_setopt($ch, CURLOPT_POSTFIELDS, $xml);
  364. //运行curl
  365. $data = curl_exec($ch);
  366. //返回结果
  367. if ($data) {
  368. curl_close($ch);
  369. return $data;
  370. } else {
  371. $error = curl_errno($ch);
  372. curl_close($ch);
  373. return $error;
  374. }
  375. }
  376. /**
  377. * 微信回调返回信息
  378. *
  379. * @param [type] $data
  380. * @return void
  381. * @author wj
  382. * @date 2022-07-23
  383. */
  384. public function paybackxml($data)
  385. {
  386. $xmlback = $this->arrayToXml($data);
  387. Log::info('返回信息');
  388. Log::info($xmlback);
  389. exit($xmlback);
  390. }
  391. }