wechatlogic.php 14 KB

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