Wechat.php 9.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248
  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. $peice = intval($request->param('peice'));
  106. $uid = intval($request->param('uid'));
  107. $plan_id = WechatPlan::where('price',$peice)->value('plan_id');
  108. $login_type = $request->param('login_type', 1);
  109. @file_put_contents("auth.txt", json_encode(input()));
  110. try {
  111. // $notify_url=Request::instance()->domain() . "/api/wechat/notify/" . $cid; //回调接口
  112. $app_id='wx5681205d1ef4d9d3';
  113. $mch_id ='';
  114. $sub_mch_id ='';
  115. $contract_code =$this->generateRandomString(6);
  116. $notify_url=Request::instance()->domain() . "/api/wechat/notify/" . 12; //回调接口 $cid 企业id
  117. // $num = time() + mt_rand(10, 999999) . '' . substr($msec, 2, 3);//生成随机数
  118. // $request_serial=$this->generateUniqueSerialNumber();
  119. $request_serial=WechatPlanRecord::where('is_signing',0)->order('request_serial desc')->value('request_serial');
  120. $contract_display_account='咸宁红十字';
  121. $timestamp=time();
  122. $version=1.0;
  123. $array = array(
  124. 'appid' => $app_id,
  125. 'mch_id' => $mch_id,
  126. 'plan_id' => $plan_id,
  127. // 'sub_mch_id' => $sub_mch_id,
  128. 'contract_code' => $contract_code,
  129. 'notify_url' => $notify_url,
  130. 'contract_display_account' => $contract_display_account,
  131. 'request_serial' => $request_serial,
  132. 'timestamp' => $timestamp,
  133. 'version' => $version,
  134. );
  135. ksort($array);
  136. $sign=$this->md5_sign($array,'192006250b4c09247ec02edce69f6a2d');
  137. var_dump($array);
  138. var_dump($sign);die();
  139. $url=$this->OfficialAccountSigning($app_id,$mch_id,$plan_id,$contract_code,$request_serial,$contract_display_account,$notify_url,$version,$sign,$timestamp);
  140. return $url;
  141. } catch (Exception $e) {
  142. @file_put_contents("error.txt", $e->getFile() . '-', $e->getLine(), '-' . $e->getMessage());
  143. }
  144. }
  145. public function generateRandomString($length) {
  146. $characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
  147. $charactersLength = strlen($characters);
  148. $randomString = '';
  149. for ($i = 0; $i < $length; $i++) {
  150. $randomString .= $characters[rand(0, $charactersLength - 1)];
  151. }
  152. return $randomString;
  153. }
  154. // 生成唯一序列号
  155. public function generateUniqueSerialNumber() {
  156. // 使用uniqid生成一个唯一ID,并去除前缀的'0'
  157. $uniqueId = ltrim(uniqid('', true), '0');
  158. // 确保生成的ID不以0开头且长度不超过19位(int64的最大长度)
  159. while (strlen($uniqueId) > 19 || substr($uniqueId, 0, 1) === '0') {
  160. $uniqueId = ltrim(uniqid('', true), '0');
  161. }
  162. // 将生成的ID转换为纯数字
  163. $serialNumber = preg_replace('/\D/', '', $uniqueId);
  164. // 确保生成的序列号不以0开头
  165. if (substr($serialNumber, 0, 1) === '0') {
  166. $serialNumber = generateUniqueSerialNumber(); // 递归调用以重新生成
  167. }
  168. return $serialNumber;
  169. }
  170. public function curl_post($url = '', $name = array(), $timeout = 100)
  171. {
  172. // var_dump($url);die();
  173. $ch = curl_init();
  174. curl_setopt($ch, CURLOPT_URL, $url);
  175. curl_setopt($ch, CURLOPT_HEADER, false); //是否显示头部
  176. curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);//是否直接输出到屏幕
  177. curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
  178. curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); // 跳过证书检查
  179. curl_setopt($ch, CURLOPT_POST, true); //是否以post方式
  180. //设置post数据
  181. $post_data = json_encode($name);
  182. // curl_setopt($curl, CURLOPT_POSTFIELDS, $post_data);
  183. curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);
  184. $content = curl_exec($ch);
  185. // var_dump($content);die();
  186. curl_close($ch);
  187. $content = json_decode($content, true);
  188. return $content;
  189. }
  190. public function md5_sign($data, $key){
  191. $stringSignTemp=$data."&key=$key"; //注:key为商户平台设置的密钥key
  192. $sign=MD5($stringSignTemp); //MD5加密
  193. $sign=strtoupper($sign); //大写
  194. return $sign;
  195. }
  196. /**
  197. * 公众号签约
  198. * see:https://pay.weixin.qq.com/wiki/doc/api/wxpay_v2/papay/chapter3_1.shtml
  199. * @param array $data
  200. *
  201. * @return array
  202. * @throws AuthorizeFailedException
  203. */
  204. 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
  205. {
  206. $url = 'https://api.mch.weixin.qq.com/papay/entrustweb';
  207. $info = [
  208. 'appid' => $appid, //应用ID
  209. 'mch_id' => $mch_id, //商户号
  210. 'plan_id' => $plan_id, //模板id
  211. // 'sub_mch_id' => $sub_mch_id, //子商户号
  212. 'contract_code' => $contract_code, //签约协议号
  213. 'request_serial' => $request_serial, //请求序列号
  214. 'contract_display_account' => $contract_display_account, //用户账户展示名称
  215. 'notify_url' => $notify_url, //回调通知url
  216. 'version' => $version, //版本号 固定值1.0
  217. 'sign' => $sign, //签名
  218. 'timestamp' => $timestamp
  219. ];
  220. $response = $this->curl_post($url, $info);
  221. return $response;
  222. }
  223. public function test() {
  224. return '123456';
  225. }
  226. }