获取openid

2022-03-11  本文已影响0人  无疆wj

公众号设置授权回调页面域名: example.com
example.com/get_openid.php

<?php
$appid = '***';
$appsecret = '***';
$code = $_GET[ 'code' ];

if ( !$code ) {
    $redirect_uri_web =  str_replace( '&', '@@@', $_GET[ 'redirect_uri' ] );
    $redirect_uri = urlencode( 'http://example.com/get_openid.php' ).'?redirect_uri_web='.$redirect_uri_web;

    $url = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=$appid&redirect_uri=$redirect_uri&response_type=code&scope=snsapi_base&state=STATE#wechat_redirect";

    header( "Location: $url" );
    exit();
}

if ( $code ) {
    $url = 'https://api.weixin.qq.com/sns/oauth2/access_token';
    $params = [ 'appid'=>$appid, 'secret'=>$appsecret, 'code'=>$code, 'grant_type'=>'authorization_code' ];
    $result = do_get( $url, $params );
    $result =  json_decode( $result, true );

    $redirect_uri_web =  str_replace( '@@@', '&', $_GET[ 'redirect_uri_web' ] );
    $redirect_uri_web = $redirect_uri_web. ( strchr( $redirect_uri_web, '?' )? '&':'?' ) .'openid='.$result[ 'openid' ];

    header( "Location:  $redirect_uri_web" );
    exit();
}

function do_get( $url, $params ) {
    $url = "{$url}?" . http_build_query ( $params );
    $ch = curl_init ();

    curl_setopt ( $ch, CURLOPT_URL, $url );

    curl_setopt ( $ch, CURLOPT_RETURNTRANSFER, 1 );

    curl_setopt ( $ch, CURLOPT_CUSTOMREQUEST, 'GET' );

    curl_setopt ( $ch, CURLOPT_TIMEOUT, 60 );

    curl_setopt ( $ch, CURLOPT_POSTFIELDS, $params );
    $result = curl_exec ( $ch );

    curl_close ( $ch );
    return $result;

}

使用:

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>获取openId</title>
  </head>
  <body>
    <script>
      if (!getQueryVariable('openid')) {
        const redirect_uri = encodeURIComponent(location.href + '?a=1&b=2');
        const url = 'http://example.com/get_openid.php?redirect_uri=' + redirect_uri;

        window.location.href = url;
      }else{
        console.log(getQueryVariable('openid'));
      }

      function getQueryVariable(variable) {
        var query = window.location.search.substring(1);
        var vars = query.split('&');
        for (var i = 0; i < vars.length; i++) {
          var pair = vars[i].split('=');
          if (pair[0] == variable) {
            return pair[1];
          }
        }
        return false;
      }
    </script>
  </body>
</html>

上一篇 下一篇

猜你喜欢

热点阅读