Wechat.php 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307
  1. <?php
  2. namespace app\api\controller;
  3. use app\admin\model\WechatPlan;
  4. use app\admin\model\WechatPlanRecord;
  5. use app\common\model\UserRelation;
  6. use app\common\controller\Api;
  7. use app\common\library\Auth;
  8. use liuniu\WechatService;
  9. use app\common\model\User;
  10. use Overtrue\Socialite\AuthorizeFailedException;
  11. use think\Exception;
  12. use think\Hook;
  13. use think\Request;
  14. class Wechat extends Api
  15. {
  16. protected $noNeedLogin = ['*'];
  17. /**
  18. * 微信公众号服务
  19. * @return \think\Response
  20. */
  21. public function serve()
  22. {
  23. ob_clean();
  24. return WechatService::serve();
  25. }
  26. /**
  27. * 支付异步回调
  28. */
  29. public function notify()
  30. {
  31. ob_clean();
  32. WechatService::handleNotify(input('cid', 0));
  33. }
  34. /**
  35. * 公众号权限配置信息获取
  36. * @param Request $request
  37. * @return mixed
  38. */
  39. public function config(Request $request)
  40. {
  41. return app('json')->success(json_decode(WechatService::jsSdk($request->get('url')), true));
  42. }
  43. /**
  44. * 公众号授权登陆
  45. * @param Request $request
  46. * @return mixed
  47. * @throws \think\db\exception\DataNotFoundException
  48. * @throws \think\db\exception\ModelNotFoundException
  49. * @throws \think\exception\DbException
  50. */
  51. public function auth(Request $request)
  52. {
  53. $spreadId = intval($request->param('spread'));
  54. $login_type = $request->param('login_type', 1);
  55. @file_put_contents("auth.txt", json_encode(input()));
  56. try {
  57. $wechatInfo = WechatService::oauthService($this->cid)->user()->getOriginal();
  58. } catch (\Exception $e) {
  59. $this->error(['message' => $e->getMessage(), 'line' => $e->getLine()]);
  60. }
  61. @file_put_contents("auth.txt", "\r\n" . json_encode($wechatInfo), 8);
  62. try {
  63. if (!isset($wechatInfo['nickname'])) {
  64. try {
  65. $wechatInfo = WechatService::getUserInfo($this->cid, $wechatInfo['openid']);
  66. } catch (\Exception $e) {
  67. $this->error(['message' => $e->getMessage(), 'line' => $e->getLine()]);
  68. }
  69. if (!$wechatInfo['subscribe'] && !isset($wechatInfo['nickname']))
  70. exit(WechatService::oauthService($this->cid)->scopes(['snsapi_userinfo'])
  71. ->redirect($this->request->url(true))->send());
  72. if (isset($wechatInfo['tagid_list']))
  73. $wechatInfo['tagid_list'] = implode(',', $wechatInfo['tagid_list']);
  74. } else {
  75. if (isset($wechatInfo['privilege'])) unset($wechatInfo['privilege']);
  76. if (!UserRelation::where(['openid' => $wechatInfo['openid']])->find())
  77. $wechatInfo['subscribe'] = 0;
  78. }
  79. $openid = $wechatInfo['openid'];
  80. $wechatInfo['cid'] = $this->cid;
  81. $params = [$openid, $wechatInfo, $spreadId, $login_type];
  82. @file_put_contents("auth.txt", "\r\n" . json_encode($params), 8);
  83. Hook::exec("\\app\admin\\behavior\\User", "WechatOauth", $params);
  84. $user = User::where('id', UserRelation::openidToUid($openid, 'openid'))->find();
  85. if (!$user)
  86. $this->error('获取用户失败');
  87. $this->auth->direct($user['id']);
  88. // 设置推广关系
  89. User::setSpread(intval($spreadId), $user->id);
  90. return $this->success('登录成功', $this->auth->getUserinfo());
  91. } catch (Exception $e) {
  92. @file_put_contents("error.txt", $e->getFile() . '-', $e->getLine(), '-' . $e->getMessage());
  93. }
  94. }
  95. /**
  96. * 扣款服务
  97. * @param Request $request
  98. * @return mixed
  99. * @throws \think\db\exception\DataNotFoundException
  100. * @throws \think\db\exception\ModelNotFoundException
  101. * @throws \think\exception\DbException
  102. */
  103. public function signing(Request $request)
  104. {
  105. $price = intval($request->param('price'));
  106. $uid = intval($request->param('uid'));
  107. $plan_id = WechatPlan::where('price',$price)->value('plan_id');
  108. $p_id = WechatPlan::where('price',$price)->value('id');
  109. $plan_id=11;
  110. $p_id=12;
  111. // try {
  112. // $notify_url=Request::instance()->domain() . "/api/wechat/notify/" . $cid; //回调接口
  113. $app_id='wx5681205d1ef4d9d3';
  114. $mch_id ='1623907696';
  115. $sub_mch_id ='';
  116. $contract_code =$this->generateRandomString(12);
  117. $notify_url=Request::instance()->domain() . "/api/wechat/notify/" . 12; //回调接口 $cid 企业id
  118. // $num = time() + mt_rand(10, 999999) . '' . substr($msec, 2, 3);//生成随机数
  119. // $request_serial=$this->generateUniqueSerialNumber();
  120. $request_serial=WechatPlanRecord::where('is_signing',0)->order('request_serial desc')->value('request_serial');
  121. if (empty($request_serial)){
  122. $request_serial=100000;
  123. }else{
  124. $request_serial=$request_serial+1;
  125. }
  126. $contract_display_account='咸宁红十字';
  127. $timestamp=time();
  128. $version='1.0';
  129. $array = array(
  130. 'appid' => $app_id,
  131. 'mch_id' => $mch_id,
  132. 'plan_id' => $plan_id,
  133. // 'sub_mch_id' => $sub_mch_id,
  134. 'contract_code' => $contract_code,
  135. 'notify_url' => $notify_url,
  136. 'contract_display_account' => $contract_display_account,
  137. 'request_serial' => $request_serial,
  138. 'timestamp' => $timestamp,
  139. 'version' => $version,
  140. );
  141. ksort($array);
  142. $xml='';
  143. foreach ($array as $key => $value){
  144. $xml=$xml.$key.'='.$value.'&';
  145. }
  146. $xml=substr($xml, 0, -1);
  147. @file_put_contents("quanju.txt", json_encode($xml)."-签约内容\r\n", 8);
  148. $sign=$this->md5_sign($xml,'192006250b4c09247ec02edce69f6a2d');
  149. @file_put_contents("quanju.txt", $sign."-签名\r\n", 8);
  150. $url='https://api.mch.weixin.qq.com/papay/entrustweb?'.$xml.'&sign='. $sign;
  151. @file_put_contents("quanju.txt", $url."-链接\r\n", 8);
  152. var_dump($url);
  153. // $response = $this->curl_get($url);
  154. // $url=$this->OfficialAccountSigning($app_id,$mch_id,$plan_id,$contract_code,$request_serial,$contract_display_account,$notify_url,$version,$sign,$timestamp);
  155. // @file_put_contents("quanju.txt", $response.'返回链接');
  156. WechatPlanRecord::create([
  157. 'uid' => $uid,
  158. 'plan_id' => $p_id,
  159. 'price' => $price,
  160. 'is_signing' => 0,
  161. 'request_serial' => $request_serial,
  162. 'contract_code' => $contract_code,
  163. 'contract_display_account' => $contract_display_account,
  164. 'createtime' => time(),
  165. 'cid' => 12,
  166. 'wechat_plan_id' => $plan_id,
  167. ]);
  168. die();
  169. return 1;
  170. // } catch (Exception $e) {
  171. // var_dump($e->getMessage());
  172. // @file_put_contents("error.txt", $e->getFile() . '-', $e->getLine(), '-' . $e->getMessage());
  173. // }
  174. }
  175. public function generateRandomString($length) {
  176. $characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
  177. $charactersLength = strlen($characters);
  178. $randomString = '';
  179. for ($i = 0; $i < $length; $i++) {
  180. $randomString .= $characters[rand(0, $charactersLength - 1)];
  181. }
  182. return $randomString;
  183. }
  184. // 生成唯一序列号
  185. public function generateUniqueSerialNumber() {
  186. // 使用uniqid生成一个唯一ID,并去除前缀的'0'
  187. $uniqueId = ltrim(uniqid('', true), '0');
  188. // 确保生成的ID不以0开头且长度不超过19位(int64的最大长度)
  189. while (strlen($uniqueId) > 19 || substr($uniqueId, 0, 1) === '0') {
  190. $uniqueId = ltrim(uniqid('', true), '0');
  191. }
  192. // 将生成的ID转换为纯数字
  193. $serialNumber = preg_replace('/\D/', '', $uniqueId);
  194. // 确保生成的序列号不以0开头
  195. if (substr($serialNumber, 0, 1) === '0') {
  196. $serialNumber = generateUniqueSerialNumber(); // 递归调用以重新生成
  197. }
  198. return $serialNumber;
  199. }
  200. public function curl_post($url = '', $name = array(), $timeout = 100)
  201. {
  202. // var_dump($url);die();
  203. $ch = curl_init();
  204. curl_setopt($ch, CURLOPT_URL, $url);
  205. curl_setopt($ch, CURLOPT_HEADER, false); //是否显示头部
  206. curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);//是否直接输出到屏幕
  207. curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
  208. curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); // 跳过证书检查
  209. curl_setopt($ch, CURLOPT_POST, true); //是否以post方式
  210. //设置post数据
  211. $post_data = json_encode($name);
  212. // curl_setopt($curl, CURLOPT_POSTFIELDS, $post_data);
  213. curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);
  214. $content = curl_exec($ch);
  215. // var_dump($content);die();
  216. curl_close($ch);
  217. $content = json_decode($content, true);
  218. return $content;
  219. }
  220. public function curl_get(string $url, $timeout = 100)
  221. {
  222. // if (!empty($name)) {
  223. // $data = '&';
  224. // foreach ($name as $k => $v) {
  225. // $data = $data . $k . '=' . $v.'&';
  226. // }
  227. // $url = $url . $data;
  228. // }
  229. // $url = substr($url,0,-1);
  230. $ch = curl_init();
  231. curl_setopt($ch, CURLOPT_URL, $url);
  232. curl_setopt($ch, CURLOPT_HEADER, false); //是否显示头部
  233. curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);//是否直接输出到屏幕
  234. curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
  235. curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); // 跳过证书检查
  236. $content = curl_exec($ch);
  237. curl_close($ch);
  238. $content = json_decode($content,true);
  239. // $content = (array)$content;
  240. // var_dump($content);
  241. return $content;
  242. }
  243. public function md5_sign($data, $key){
  244. $stringSignTemp=$data."&key=$key"; //注:key为商户平台设置的密钥key
  245. $sign=MD5($stringSignTemp); //MD5加密
  246. $sign=strtoupper($sign); //大写
  247. return $sign;
  248. }
  249. /**
  250. * 公众号签约
  251. * see:https://pay.weixin.qq.com/wiki/doc/api/wxpay_v2/papay/chapter3_1.shtml
  252. * @param array $data
  253. *
  254. * @return array
  255. * @throws AuthorizeFailedException
  256. */
  257. public function OfficialAccountSigning(string $appid,string $mch_id, string $plan_id, string $contract_code, string $request_serial, string $contract_display_account, string $notify_url, string $version, string $sign,string $timestamp): array
  258. {
  259. $url = 'https://api.mch.weixin.qq.com/papay/entrustweb';
  260. $info = [
  261. 'appid' => $appid, //应用ID
  262. 'mch_id' => $mch_id, //商户号
  263. 'plan_id' => $plan_id, //模板id
  264. // 'sub_mch_id' => $sub_mch_id, //子商户号
  265. 'contract_code' => $contract_code, //签约协议号
  266. 'request_serial' => $request_serial, //请求序列号
  267. 'contract_display_account' => $contract_display_account, //用户账户展示名称
  268. 'notify_url' => $notify_url, //回调通知url
  269. 'version' => $version, //版本号 固定值1.0
  270. 'sign' => $sign, //签名
  271. 'timestamp' => $timestamp
  272. ];
  273. $response = $this->curl_get($url, $info);
  274. return $response;
  275. }
  276. public function test() {
  277. return '123456';
  278. }
  279. public function signing_plan() {
  280. $this->success('获取成功',WechatPlan::where('cid',$this->cid)->select());
  281. }
  282. }