第一步: 不管微信登录,微信支付,微信分享都需要到微信开放平台注册账号后并注册应用,拿到应用唯一标识AppID
和应用密钥 AppSecret
然后集成SDK,具体如何集成查看官方文档,文档有详细介绍
微信开放平台–iOS 接入指南
第二步:微信SDK初始化,注意universal_link
必须添加
let universal_link = "https://wx.universal_link.url" //此处填写微信后台写的universal_link 地址
WXApi.registerApp(WX_APPID, universalLink: universal_link)
.png)
微信配置代理
,接收微信请求后的返回信息(用户登录/微信支付订单信息)
// 9.0之后 打开第三方应用之后返回程序内 设置系统回调 --------待完善---------
func application(_ app: UIApplication, open url: URL, options: [UIApplication.OpenURLOptionsKey : Any] = [:]) -> Bool {
if url.absoluteString.hasPrefix(WX_APPID){
//微-信
WXApi.handleOpen(url, delegate: NK_WXUtils.sharedManager)
return true
}
}
func application(_ application: UIApplication, continue userActivity: NSUserActivity, restorationHandler: @escaping ([UIUserActivityRestoring]?) -> Void) -> Bool {
if userActivity.activityType == NSUserActivityTypeBrowsingWeb {
if let url = userActivity.webpageURL{
return WXApi.handleOpenUniversalLink(userActivity, delegate: NK_WXUtils.sharedManager)
}
}
return true
}
微信调用方法
class NK_WXUtils: NSObject , WXApiDelegate{
//微信登录
static func wxLogin(){
if WXApi.isWXAppInstalled() {
let req = SendAuthReq()
req.state = "wx_oauth_authorization_state";//用于保持请求和回调的状态,授权请求或原样带回
req.scope = "snsapi_userinfo";//授权作用域:获取用户个人信息
// req.scope = "snsapi_userinfo,snsapi_base";//授权作用域:获取用户个人信息
DispatchQueue.main.async {
WXApi.send(req)
}
}else{
MBProgressHUD.showJustText(msg: "您尚未安装微信客户端,请安装后重试!")
}
}
//微信发送请求,这里不用处理
func onReq(_ req: BaseReq) {
MYLog( "\n\n----openID:"+req.openID)
}
//微信请求返回结果,这里处理返回的结果
func onResp(_ resp: BaseResp) {
if resp.isKind(of: SendAuthResp.self) {
let res = resp as? SendAuthResp
if res?.state == "wx_oauth_authorization_state" {
NK_WXUtils.getWechatAccessToken(code: res!.code!)
}
}
}
static func getWechatAccessToken(code:String) {
let url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=\(WX_APPID)&secret=\(WX_SECRET)&code=\(code)&grant_type=authorization_code"
MBProgressHUD.showLoadingHUD(msg: nil, view: nil)
NK_HttpManager().requestData(with: url, cache: false, method: .get, params: nil).success { (code, res) in
MYLog(res)
guard let dic = res as? [String: Any] else{
return
}
guard let access_token = dic["access_token"] as? String, let openid = dic["openid"] as? String else{
MBProgressHUD.hideToastHUD(view: nil)
return
}
getWechatUserInfo(with: access_token, openId: openid )
}.fail { (error, msg) in
// MYLog(msg)
MBProgressHUD.showJustText(msg: msg)
}
}
static func getWechatUserInfo(with access_token:String, openId:String) {
let url = "https://api.weixin.qq.com/sns/userinfo?access_token=\(access_token)&openid=\(openId)"
NK_HttpManager().requestData(with: url, cache: false, method: .get, params: nil).success { (code, res) in
MBProgressHUD.hideToastHUD(view: nil)
// MYLog(res)
if let dic = res as? [String: Any]{
// 获取到的用户信息json格式,可以拿来给服务端绑定用户信息
}
}.fail { (error, msg) in
MBProgressHUD.showJustText(msg: msg)
}
}
}