微信小程序获取openid,api.weixin.qq.com不能设为安全域名,通过php转发

1、首先wx.login是可以获取到code的
2、其次通过code可以很容易获取到openid,但是直接通过小程序不行。
网上很多示例,例如

wx.request({  
      url: 'https://api.weixin.qq.com/sns/jscode2session?appid=‘+<code></code>appid+’&secret=‘+secret+’&grant_type=authorization_code&js_code='+loginCode.code,  
      header: {  
          'content-type': 'application/json'  
      },  
      success: function(res) {  
        console.log(res.data.openid) //获取openid  
      }  
    })  

这样请求只会提示api.weixin.qq.com不在域名白名单内!
而且在官方平台上设置合法域名,微信却提示“为保障帐号安全不可使用此域名地址,请修改”,这样就郁闷了。
只能转一下,向自己的php服务器发送code,在通过php请求openid再返回openid
3、小程序向php发送get数据
php网址?jsonData={“resCode”:10001,” data”:{“code”:”abcdefghijklmnopq…”}}
php回应数据{“resCode”:10001,”data”:{“openid”:”abcdefg…..”}}
4、小程序代码如下


wx.login({
      success:function(res){
        var data = {'resCode':10001,'data':{'code':res.code}};//自定义的格式 ,主要就是传递给服务器一个code
        utils.myRequestByGet(  //请求获取openid
          getApp().globalData.phpUrl,//php网址
          data,
          function callback(obj){
            if (obj.data.resCode != 10001){ //忽略此错误处理内容
              wx.showModal({
                title:'错误',
                content: obj.data.error,
                showCancel:true
              });
            }else{
              that.setData({
                openid: obj.data.data.openid  //obj.data.data.openid为获取到的openid
              });
            }
          }
        )
      }
    });

utils.myRequestByGet代码如下:

/**
 * get方式的请求都在这里
 */
function myRequestByGet(url,data,callback){
  wx.request({
    url: url,
    data:{
      jsonData:data
    },
    success:function(obj){
      callback(obj);
    },
    header: {
      'Content-type': 'application/json'
    }
  })

}

服务器端php代码如下,通过code获取openid的方法,具体返回内容自己处理

function getOpenid($code){
    $appid = '小程序对应的appid';
    $appsecret = '小程序对应的appsecret ';
    $weixin =  file_get_contents("https://api.weixin.qq.com/sns/oauth2/access_token?appid=$appid&secret=$appsecret&code=".$code."&grant_type=authorization_code");//通过code换取网页授权access_token
    $jsondecode = json_decode($weixin); //对JSON格式的字符串进行编码
    $array = get_object_vars($jsondecode);//转换成数组
    return $array['openid'];//输出openid
}

猜你喜欢

转载自blog.csdn.net/jinyulong84/article/details/73741287