wechatlogic.php 14 KB

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