Model_wechat.php 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. <?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
  2. class Model_wechat extends Lin_Model
  3. {
  4. function __construct(){
  5. parent::__construct();
  6. $this->load->database();
  7. }
  8. public function getopenid($code){
  9. $query1 = $this->db->get_where('setting',array('skey' => 'lywx_id'));
  10. $app_id = $query1->row_array();
  11. $query2 = $this->db->get_where('setting',array('skey' => 'lywx_secret'));
  12. $app_secret = $query2->row_array();
  13. $url = 'https://api.weixin.qq.com/sns/jscode2session';
  14. $params = [
  15. 'appid' => $app_id['svalue'],
  16. 'secret' => $app_secret['svalue'],
  17. 'js_code' => $code,
  18. 'grant_type' => 'authorization_code'
  19. ];
  20. $query = http_build_query($params);
  21. $requestUrl = $url . '?' . $query;
  22. $ch = curl_init();
  23. curl_setopt($ch, CURLOPT_URL, $requestUrl);
  24. curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
  25. curl_setopt($ch, CURLOPT_TIMEOUT, 10);
  26. curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
  27. $response = curl_exec($ch);
  28. $errorNo = curl_errno($ch);
  29. $errorMsg = curl_error($ch);
  30. curl_close($ch);
  31. if ($errorNo !== 0) {
  32. $str = "cURL Error ($errorNo): $errorMsg";
  33. return [
  34. "code"=>-1,
  35. "msg"=>$str
  36. ];
  37. }
  38. $result = json_decode($response, true);
  39. // 检查微信返回的错误码
  40. if (isset($result['errcode'])) {
  41. $str ="WeChat API Error: " . $result['errmsg'] . " (Code: " . $result['errcode'] . ")";
  42. return [
  43. "code"=>-1,
  44. "msg"=>$str
  45. ];
  46. }
  47. return [
  48. "code"=>1,
  49. "msg"=>"success",
  50. "data"=>$result
  51. ];
  52. }
  53. }