营业执照、1-2个工作如审批、300元AppID: 申请的IDAppSecret: 申请的Secrethttps://res.wx.qq.com/connect/zh_CN/htmledition/js/wxLogin.jsvar obj = new WxLogin(
{
self_redirect: true,
id: "放置二维码的容器id",
appid: "",
scope: "",
redirect_uri: "",
state: "",
style: "",
href: ""
}
);
wx.open.app_id=上面提供的AppID
wx.open.app_secret=上面提供的AppSecret
wx.open.redirect_uri=http://localhost:8160/api/user/wx/callback
web.base_url=http://localhost:3000
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
@Component
public class WxConstantProperties implements InitializingBean {
@Value("${wx.open.app_id}")
private String appId;
@Value("${wx.open.app_secret}")
private String appSecret;
@Value("${wx.open.redirect_uri}")
private String redirectUri;
@Value("${web.base_url}")
private String webBaseUrl;
public static String WX_OPEN_APP_ID;
public static String WX_OPEN_APP_SECRET;
public static String WX_OPEN_REDIRECT_URL;
public static String WEB_BASE_URL;
@Override
public void afterPropertiesSet() throws Exception {
WX_OPEN_APP_ID = appId;
WX_OPEN_APP_SECRET = appSecret;
WX_OPEN_REDIRECT_URI = redirectUri;
WEB_BASE_URL = webBaseUrl;
}
}
import java.util.HashMap;
@Controller
@RequestMapping("/api/user/wx")
public class WxApiController {
@GetMapper("/getWxParam")
@ResponseBody
public Result<Map<String, Object>> getParam() {
try {
Map<String, Object> map = new HashMap<>();
map.put("appid", WxConstantProperties.WX_OPEN_APP_ID);
// 固定值
map.put("scope", "snsapi_login");
String wxOpenRedirectUri = WxConstantProperties.WX_OPEN_REDIRECT_URI;
// 应微信开放平台要求,需要使用URLEncoder规范url
wxOpenRedirectUri = URLEncoder.encode(wxOpenRedirectUri, "utf-8");
map.put("redirect_uri", wxOpenRedirectUri);
// 随意值
map.put("state", System.currentTimeMillis() + "");
return Result.ok(map);
} catch (Exception e) {
e.printStackTrace();
return Result.fail();
}
}
}
import request from '@/utils/request'
export default {
getWxParam() {
return request({
url: `/api/user/wx/getWxParam`,
method: 'get'
})
}
}
<template></template>
<script>
<!-- 引入上面的js文件 -->
import wxApi from '@/api/wx/wxApi.js'
export default {
data() {
return {}
},
mounted() {
// 注册全局登录事件对象
window.loginEvent = new Vue();
// (注册)监听登录事件
loginEvent.$on('loginDialogEvent', function () {
document.getElementById("loginDialog").click();
})
// 触发事件,显示登录层:loginEvent.$emit('loginDialogEvent')
//初始化微信js(包好上面提及的登录js文件)
const script = document.createElement('script')
script.type = 'text/javascript'
script.src = 'https://res.wx.qq.com/connect/zh_CN/htmledition/js/wxLogin.js'
document.body.appendChild(script)
// 微信登录回调处理
let self = this;
window["loginCallback"] = (name,token, openid) => {
self.loginCallback(name, token, openid);
}
},
methods: {
// 第一个接口:获取参数,生成二维码
wxLogin() {
// 可以忽略的文本信息
this.dialogAtrr.showLoginType = 'weixin'
wxApi.getWxParam().then(response => {
var obj = new WxLogin({
self_redirect:true,
id: 'weixinLogin', // 需要显示的容器id
appid: response.data.appid, // 公众号appid wx*******
scope: response.data.scope, // 网页默认即可
redirect_uri: response.data.redirect_uri, // 授权成功后回调的url
state: response.data.state, // 可设置为简单的随机数加session用来校验
style: 'black', // 提供"black"、"white"可选。二维码的样式
href: '' // 外部css文件url,需要https
})
})
},
// 第二个接口:重定向到某个页面并保存cookie信息
loginCallback(name, token, openid) {
// 打开手机登录层,绑定手机号,改逻辑与手机登录一致
if(openid != '') {
this.userInfo.openid = openid
this.showLogin()
} else {
this.setCookies(name, token)
}
},
setCookies(name, token) {
cookie.set('token', token, { domain: 'localhost' })
cookie.set('name', name, { domain: 'localhost' })
window.location.reload()
},
}
}
</script>
<style></style>
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.http.Consts;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.config.RequestConfig.Builder;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpRequestBase;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.conn.ssl.X509HostnameVerifier;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.ssl.SSLContextBuilder;
import org.apache.http.ssl.TrustStrategy;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLException;
import javax.net.ssl.SSLSession;
import javax.net.ssl.SSLSocket;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.security.GeneralSecurityException;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
public class HttpClientUtils {
public static final int CONN_TIMEOUT = 10000;
public static final int READ_TIMEOUT = 10000;
public static final String CHARSET = "UTF-8";
public static final String CONTENT_TYPE = "application/x-www-form-urlencoded";
private static HttpClient client;
static {
PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager();
cm.setMaxTotal(128);
cm.setDefaultMaxPerRoute(128);
client = HttpClients.custom().setConnectionManager(cm).build();
}
public static String postParameters(String url, String params) throws Exception {
return post(url, params, CONTENT_TYPE, CHARSET, CONN_TIMEOUT, READ_TIMEOUT);
}
public static String postParameters(String url, String params, String charset, Integer connTimeout, Integer readTimeout) throws Exception {
return post(url, params, CONTENT_TYPE, charset, connTimeout, readTimeout);
}
public static String postParameters(String url, Map<String, String> params) throws Exception {
return postForm(url, params, null, CONN_TIMEOUT, READ_TIMEOUT);
}
public static String postParameters(String url, Map<String, String> params, Integer connTimeout, Integer readTimeout) throws Exception {
return postForm(url, params, null, connTimeout, readTimeout);
}
public static String get(String url) throws Exception {
return get(url, CHARSET, null, null);
}
public static String get(String url, String charset) throws Exception {
return get(url, charset, CONN_TIMEOUT, READ_TIMEOUT);
}
/**
* 发送一个get请求
* @param url 请求地址
* @param charset 字符集编码
* @param connTimeout 连接超时时间
* @param readTimeout 响应超时时间
* @return String
* @throws Exception ConnectTimeoutException、SocketTimeoutException等其他异常
*/
public static String get(String url, String charset, Integer connTimeout, Integer readTimeout) throws Exception {
HttpClient client = null;
HttpGet get = new HttpGet(url);
String result = "";
try {
// 设置参数
getHttpRequestBase(get, connTimeout, readTimeout);
// 获取响应信息
HttpResponse res = getHttpResponse(url, get, client);
result = IOUtils.toString(res.getEntity().getContent(), charset);
}finally {
get.releaseConnection();
if (url.startsWith("https") && client instanceof CloseableHttpClient) {
((CloseableHttpClient) client).close();
}
}
return result;
}
/**
* 发送一个post请求
* @param url 请求地址
* @param body 请求体
* @param mimeType 类似于Content-Type
* @param charset 字符集编码
* @param connTimeout 连接超时时间
* @param readTimeout 响应超时时间
* @return String
* @throws Exception ConnectTimeoutException、SocketTimeoutException等其他异常
*/
public static String post(String url, String body, String mimeType, String charset, Integer connTimeout, Integer readTimeout) throws Exception {
HttpClient client = null;
HttpPost post = new HttpPost(url);
String result = "";
try {
if(!StringUtils.isEmpty(body)) {
HttpEntity entity = new StringEntity(body, ContentType.create(mimeType, charset));
post.setEntity(entity);
}
// 设置参数
getHttpRequestBase(post, connTimeout, readTimeout);
// 获取响应信息
HttpResponse res = getHttpResponse(url, post, client);
result = IOUtils.toString(res.getEntity().getContent(), charset);
} finally {
post.releaseConnection();
if (url.startsWith("https") && client instanceof CloseableHttpClient) {
((CloseableHttpClient) client).close();
}
}
return result;
}
/**
* form表单提交方式请求
* @param url 请求地址
* @param params 表单参数
* @param headers 请求头
* @param connTimeout 连接超时时间
* @param readTimeout 响应超时时间
* @return String
* @throws Exception ConnectTimeoutException、SocketTimeoutException等其他异常
*/
public static String postForm(String url, Map<String, String> params, Map<String, String> headers, Integer connTimeout, Integer readTimeout) throws Exception {
HttpClient client = null;
HttpPost post = new HttpPost(url);
try {
if (params != null && !params.isEmpty()) {
List<NameValuePair> formParams = new ArrayList<>();
Set<Entry<String, String>> entrySet = params.entrySet();
for (Entry<String, String> entry : entrySet) {
formParams.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
}
UrlEncodedFormEntity entity = new UrlEncodedFormEntity(formParams, Consts.UTF_8);
post.setEntity(entity);
}
if (headers != null && !headers.isEmpty()) {
for (Entry<String, String> entry : headers.entrySet()) {
post.addHeader(entry.getKey(), entry.getValue());
}
}
// 设置参数
getHttpRequestBase(post, connTimeout, readTimeout);
// 获取响应信息
HttpResponse res = getHttpResponse(url, post, client);
return IOUtils.toString(res.getEntity().getContent(), String.valueOf(StandardCharsets.UTF_8));
}finally {
post.releaseConnection();
if (url.startsWith("https") && client instanceof CloseableHttpClient) {
((CloseableHttpClient) client).close();
}
}
}
/**
* 设置参数
* @param base 协议请求对象
* @param connTimeout 连接超时时间
* @param readTimeout 响应超时时间
*/
private static void getHttpRequestBase(HttpRequestBase base, Integer connTimeout, Integer readTimeout) {
Builder customReqConf = RequestConfig.custom();
if(connTimeout != null) customReqConf.setConnectTimeout(connTimeout);
if(readTimeout != null) customReqConf.setSocketTimeout(readTimeout);
base.setConfig(customReqConf.build());
}
/**
* 获取响应信息
* @param url 请求地址
* @param base 协议请求对象
* @return HttpResponse
* @throws Exception 异常信息
*/
private static HttpResponse getHttpResponse(String url, HttpRequestBase base, HttpClient client) throws Exception{
if (url.startsWith("https")) {
// 执行 Https 请求.
client = createSSLInsecureClient();
} else {
// 执行 Http 请求.
client = HttpClientUtils.client;
}
return client.execute(base);
}
/**
* 创建SSL连接供https协议请求
* @return CloseableHttpClient
* @throws GeneralSecurityException 安全异常
*/
private static CloseableHttpClient createSSLInsecureClient() throws GeneralSecurityException {
try {
SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial(null, new TrustStrategy() {
@Override
public boolean isTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException {
return true;
}
}).build();
SSLConnectionSocketFactory sslConnectionSocketFactory = new SSLConnectionSocketFactory(sslContext, new X509HostnameVerifier() {
@Override
public void verify(String s, SSLSocket sslSocket) throws IOException {}
@Override
public void verify(String s, X509Certificate x509Certificate) throws SSLException {}
@Override
public void verify(String s, String[] strings, String[] strings1) throws SSLException {}
@Override
public boolean verify(String s, SSLSession sslSession) {
return true;
}
});
return HttpClients.custom().setSSLSocketFactory(sslConnectionSocketFactory).build();
} catch (GeneralSecurityException e) {
throw e;
}
}
/**
* 从 response 里获取 charset
* @param response 响应信息
*/
@SuppressWarnings("unused")
private static String getCharsetFromResponse(HttpResponse response) {
// Content-Type:text/html; charset=GBK
if (response.getEntity() != null && response.getEntity().getContentType() != null && response.getEntity().getContentType().getValue() != null) {
String contentType = response.getEntity().getContentType().getValue();
if (contentType.contains("charset=")) {
return contentType.substring(contentType.indexOf("charset=") + 8);
}
}
return null;
}
}
@Controller
@RequestMapping("/api/user/wx")
public class WxApiController {
@GetMapping("/callback")
public String callback(String code, String state) {
// 根据临时票据code和微信id及密钥请求微信固定地址,获取两个值(access_token和openid)
StringBuffer baseAccessTokenUrl = new StringBuffer()
.append("https://api.weixin.qq.com/sns/oauth2/access_token")
.append("?appid=%s").append("&secret=%s")
.append("&code=%s").append("&grant_type=authorization_code");
String accessTokenUrl = String.format(
baseAccessTokenUrl.toString(), ConstantWxPropertiesUtils.WX_OPEN_APP_ID,
ConstantWxPropertiesUtils.WX_OPEN_APP_SECRET, code);
try {
// 使用HttpClientUtils工具类请求地址
String accessTokenInfo = HttpClientUtils.get(accessTokenUrl);
JSONObject jsonObject = JSONObject.parseObject(accessTokenInfo);
String accessToken = jsonObject.getString("access_token");
String openid = jsonObject.getString("openid");
// 如果数据库表中存在openid值,
UserInfo userInfo = userInfoService.selectWxInfoOpenId(openid);
if(userInfo == null) {
// 根据access_token和openid获取扫码人信息
String baseUserInfoUrl = "https://api.weixin.qq.com/sns/userinfo" +
"?access_token=%s" + "&openid=%s";
String userInfoUrl = String.format(baseUserInfoUrl, accessToken, openid);
String userInfoResult = HttpClientUtils.get(userInfoUrl);
JSONObject userObject = JSONObject.parseObject(userInfoResult);
String nickname = userObject.getString("nickname");
String headImageUrl = userObject.getString("headimgurl");
// 信息保存到数据库中(省略)
}
// 最后重定向到前端某一个页面,期间可以随带一些重要的信息
return "redirect:" + WxConstantProperties.WEB_BASE_URL + "/weixin/callback?token=" +
token + "&openid=" + openid + "&name=" + URLEncoder.encode(name, "utf-8");
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
}
前言一般来说,前端根据后台返回code码展示对应内容只需要在前台判断code值展示对应的内容即可,但要是匹配的code码比较多或者多个页面用到时,为了便于后期维护,后台就会使用字典表让前端匹配,下面我将在微信小程序中通过wxs的方法实现这个操作。为什么要使用wxs?{{method(a,b)}}可以看到,上述代码是一个调用方法传值的操作,在vue中很常见,多用于数据之间的转换,但由于微信小程序诸多限制的原因,你并不能优雅的这样操作,可能有人会说,为什么不用if判断实现呢?但是if判断的局限性在于如果存在数据量过大时,大量重复性操作和if判断会让你的代码显得异常冗余。wxswxs相当于是一个独立
项目介绍随着我国经济迅速发展,人们对手机的需求越来越大,各种手机软件也都在被广泛应用,但是对于手机进行数据信息管理,对于手机的各种软件也是备受用户的喜爱小学生兴趣延时班预约小程序的设计与开发被用户普遍使用,为方便用户能够可以随时进行小学生兴趣延时班预约小程序的设计与开发的数据信息管理,特开发了小程序的设计与开发的管理系统。小学生兴趣延时班预约小程序的设计与开发的开发利用现有的成熟技术参考,以源代码为模板,分析功能调整与小学生兴趣延时班预约小程序的设计与开发的实际需求相结合,讨论了小学生兴趣延时班预约小程序的设计与开发的使用。开发环境开发说明:前端使用微信微信小程序开发工具:后端使用ssm:VU
@作者:SYFStrive @博客首页:HomePage📜:微信小程序📌:个人社区(欢迎大佬们加入)👉:社区链接🔗📌:觉得文章不错可以点点关注👉:专栏连接🔗💃:感谢支持,学累了可以先看小段由小胖给大家带来的街舞👉微信小程序(🔥)目录自定义组件-behaviors 1、什么是behaviors 2、behaviors的工作方式 3、创建behavior 4、导入并使用behavior 5、behavior中所有可用的节点 6、同名字段的覆盖和组合规则总结最后自定义组件-behaviors 1、什么是behaviorsbehaviors是小程序中,用于实现
我需要从站点抓取数据,但它需要我先登录。我一直在使用hpricot成功地抓取其他网站,但我是使用mechanize的新手,我真的对如何使用它感到困惑。我看到这个例子经常被引用:require'rubygems'require'mechanize'a=Mechanize.newa.get('http://rubyforge.org/')do|page|#Clicktheloginlinklogin_page=a.click(page.link_with(:text=>/LogIn/))#Submittheloginformmy_page=login_page.form_with(:act
提供3种Ubuntu系统安装微信的方法,在Ubuntu20.04上验证都ok。1.WineHQ7.0安装微信:ubuntu20.04安装最新版微信--可以支持微信最新版,但是适配的不是特别好;比如WeChartOCR.exe报错。2.原生微信安装:linux系统下的微信安装(ubuntu20.04)--微信适配的最好,反应最快,但是微信版本只到2.1.1,版本太老,很多功能都没有。3.深度deepin-wine6安装微信:ubuntu20.04+系统deepin-wine6安装新版微信--综合比较好,当前个人使用此种方法1个月,微信版本3.4;没什么大问题,尚可。一、WineHQ7.0安装微信
对传统的餐饮商家来说,小程序很好地解决了餐厅线下线上连接的问题,在引流获客、节约人力、营销宣传、塑造会员体系、改善消费体验等方面都有很大帮助。小程序点餐可以帮助餐饮企业节省一大把人力开支。一个包含扫码点单、菜品管理、优惠券推送、外卖配送的小程序,商家花几万元就能完成开发测试并投入。商家为什么要开通“扫码点餐”1.解决服务员不够用的问题。2.不怕顾客跑单漏单。3.在微信就能管理菜品、查看营业额。4.订单小票显示顾客桌号和已点菜品。5.可在“附近的小程序”找到您的门店。如今餐饮业常用的三种经营模式:1堂食点单模式客人通过小程序堂食点单。商家可以在微信扫码点餐小程序管理后台根据自己店内情况来设置不同
我为Devise用户和管理员提供了不同的模型。我也在使用Basecamp风格的子域。除了我需要能够以用户或管理员身份进行身份验证的一些Controller和操作外,一切都运行良好。目前我有authenticate_user!在我的application_controller.rb中设置,对于那些只有管理员才能访问的Controller和操作,我使用skip_before_filter跳过它。不幸的是,我不能简单地指定每个Controller的身份验证要求,因为我仍然需要一些Controller和操作才能被用户或管理员访问。我尝试了一些方法都无济于事。看来,如果我移动authentica
我想用一个(自己的)omniauth提供商来衡量每秒可以登录多少次。我需要了解此omniauth/oauth请求的性能如何,以及此身份验证是否具有可扩展性?到目前为止我得到了什么:defperformance_auth(user_count=10)bm=Benchmark.realtimedouser_count.timesdo|n|forkdoclick_on'Logout'omniauth_config_mock(:provider=>"foo",:uid=>n,:email=>"foo#{n}@example.net")visit"/account/auth/foo/"enden
我正在使用Ruby和Eventmachine库编写一个应用程序。我真的很喜欢非阻塞I/O和事件驱动系统的想法,我遇到的问题是日志记录。我正在使用Ruby的标准记录器库。并不是说日志记录需要永远,但它似乎不应该阻塞,但它确实阻塞了。是否有某个库将Ruby的标准记录器实现扩展为非阻塞的,或者我应该只调用EM::defer进行日志记录调用?有没有办法让eventmachine已经为我做这件事? 最佳答案 我最终将记录器包装在一个启动线程并具有FIFO队列的单例类中。日志记录会将日志信息转储到队列中,线程只是循环,从队列中拉出内容并使用真正
当尝试创建一个heroku应用程序并通过git推送到它时,我收到以下错误:$herokucreate'"C:\ProgramFiles\ruby-1.9.2\bin\ruby.exe"isnotrecognizedasaninternalorexternalcommand,operableprogramorbatchfile.但是,$ruby-vruby1.9.3p125[i386-mingw32]我已经检查了PATH环境,它肯定包含“C:\ProgramFiles(x86)\ruby-1.9.2\bin”。同样有趣的是,当导航到该目录时,它实际上并不包含名为ruby.exe的文件